static boolean hasNonBlackProperty(Project proj, String key) {
    if (proj.hasProperty(key)) {
        return !proj.getProperties().get(key).isBlank()
    } else {
        return false
    }
}

def validateLink(url) {
    try {
        def connection = new URL(url).openConnection() as HttpURLConnection
        connection.requestMethod = "HEAD"
        connection.connectTimeout = 5000
        connection.readTimeout = 5000
        connection.connect()
        if (connection.responseCode >= 400) {
            url = ""
        }
    } catch (Exception e) {
        url = ""
    }
    return url
}

tasks.register("generatePacksYaml") {
    group "AnySoftKeyboard"
    description "Writing a YAML list of ${project.name} to PACKS.yml."

    doLast {
        def outputFile = project.file('PACKS.yml')
        def allPacksData = []

        subprojects.each {
            if (it.plugins.hasPlugin('com.android.application')) {
                def packName = it.parent.name.capitalize()
                def playStoreLink = "#"
                if (it.ext.shouldBePublished) {
                    playStoreLink = "https://play.google.com/store/apps/details?id=${it.android.defaultConfig.applicationId}"
                }
                def addOnDir = rootProject.projectDir.relativePath(it.projectDir)
                // Default to a placeholder if 'githubRootUrl' is not defined
                def githubBaseUrl = project.hasProperty('githubRootUrl') ? project.property('githubRootUrl') : "https://github.com/AnySoftKeyboard/AnySoftKeyboard"
                def githubLink = "${githubBaseUrl}/tree/main/${addOnDir}"
                // Not all packages are published to f-droid. Checking.
                def fdroidLink = validateLink("https://f-droid.org/en/packages/${it.android.defaultConfig.applicationId}/")

                // pack icon
                def image = "https://raw.githubusercontent.com/AnySoftKeyboard/AnySoftKeyboard/refs/heads/main/${addOnDir}/flag/{{IMAGE_FILENAME}}"
                if (it.file("flag/flag.png").exists()) {
                    image = image.replace("{{IMAGE_FILENAME}}", "flag.png")
                } else if (it.file("flag/flag.svg").exists()) {
                    image = image.replace("{{IMAGE_FILENAME}}", "flag.svg?sanitize=1")
                } else {
                    image = ""
                }
                def packDetails = [
                    name: packName,
                    play: playStoreLink,
                    'f-droid': fdroidLink,
                    github: githubLink,
                    icon: image
                ]
                allPacksData.add(packDetails)
            }
        }

        outputFile.withWriter { BufferedWriter writer ->
            writer.writeLine('languages:')
            allPacksData.each { packData ->
                writer.writeLine("- name: \"${packData.name}\"")
                writer.writeLine("  play: \"${packData.play}\"")
                writer.writeLine("  f-droid: \"${packData['f-droid']}\"")
                writer.writeLine("  github: \"${packData.github}\"")
                writer.writeLine("  icon: \"${packData.icon}\"")
            }
        }
    }
}

tasks.register("generatePacksMarkDown") {
    group "AnySoftKeyboard"
    description "Writing a MarkDown-friendly list of ${project.name} to PACKS.md."

    doLast {
        def outputFile = project.file('PACKS.md')
        outputFile.withWriter { BufferedWriter writer ->
            writer.writeLine('# Packs in this repository')
            writer.writeLine('')
            subprojects.each {
                if (it.plugins.hasPlugin('com.android.application')) {
                    // paths should be relating to this project
                    def image = "<img src='${project.projectDir.relativePath(it.projectDir)}/flag/{{IMAGE_FILENAME}}' height='16'>&nbsp;"
                    if (it.file("flag/flag.png").exists()) {
                        image = image.replace("{{IMAGE_FILENAME}}", "flag.png")
                    } else if (it.file("flag/flag.svg").exists()) {
                        image = image.replace("{{IMAGE_FILENAME}}", "flag.svg?sanitize=1")
                    } else {
                        image = ""
                    }
                    def packReadMeDetails = "1. ${image}${it.parent.name.capitalize()}: [Source](${project.projectDir.relativePath(it.parent.projectDir)})"

                    if (it.ext.shouldBePublished) {
                        packReadMeDetails += " • [Play Store](https://play.google.com/store/apps/details?id=${it.android.defaultConfig.applicationId})"
                        if (hasNonBlackProperty(it, 'openTestingTrackName')) {
                            packReadMeDetails += " • [Beta Channel](https://play.google.com/apps/testing/${it.android.defaultConfig.applicationId})"
                        }
                    } else if (it.ext.notPublishingReason) {
                        packReadMeDetails += " (not published reason: '${it.ext.notPublishingReason}')"
                    }

                    // Add F-Droid link if available
                    def fdroidLink = validateLink("https://f-droid.org/en/packages/${it.android.defaultConfig.applicationId}/")
                    if (fdroidLink) {
                        packReadMeDetails += " • [F-Droid](${fdroidLink})"
                    }

                    writer.writeLine(packReadMeDetails)
                }
            }
        }
    }
}
