import org.jetbrains.intellij.tasks.RunIdeTask

plugins {
    java
    kotlin("jvm") version "1.9.24"
    id("org.jetbrains.intellij") version "1.17.4"
}

group = "com.huangzj"
version = "1.0.0"

repositories {
    // 国内镜像，失败再走中央仓库
    maven { url = uri("https://maven.aliyun.com/repository/public") }
    mavenCentral()
}

java {
    sourceCompatibility = JavaVersion.VERSION_17
    targetCompatibility = JavaVersion.VERSION_17
}

dependencies {
    implementation("com.google.code.gson:gson:2.10.1")
    implementation("com.mysql:mysql-connector-j:8.3.0")
    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.7.3")
    testImplementation("junit:junit:4.13.2")
}

// 国内网络下 JetBrains 依赖经 cache-redirector 会跳到 CloudFront，常出现 UnknownHostException。
// 优先使用本机已安装的 IDEA（与开发/沙箱一致，且无需下载 ideaIU）。
val ideaLocalPath: String? =
    (project.findProperty("ideaLocalPath") as String?)?.trim()?.takeIf { it.isNotEmpty() }
        ?: System.getenv("IDEA_LOCAL_PATH")?.trim()?.takeIf { it.isNotEmpty() }

intellij {
    if (ideaLocalPath != null) {
        localPath.set(file(ideaLocalPath).absolutePath)
    } else {
        // 未配置 ideaLocalPath 时仍尝试在线解析（需能访问 JetBrains CDN）
        version.set("2023.3")
        type.set("IU")
    }
    plugins.set(listOf("com.intellij.java"))
    // instrumentCode 会从 Maven 拉取插桩编译器类路径；离线/代理异常时出现 Connection refused。
    // 关闭后跳过 :instrumentCode（无 GUI Designer .form、一般插件可接受；若需插桩再改为 true 并保证网络可达）
    instrumentCode.set(false)
}

tasks {
    // 避免 :buildSearchableOptions 拉起 IDE 时 JDK/JBR 不一致触发 Font2D 等错误（intellij {} 无此属性，须禁用 Task）
    named("buildSearchableOptions") {
        enabled = false
    }

    /** 删除 runIde 沙箱。非正常退出易导致 VFS/option 损坏，进而出现 GradleJvmSupportMatrix、JavaVersion.parse 等启动异常。 */
    register<Delete>("cleanIdeaSandbox") {
        group = "intellij"
        description =
            "删除 build/idea-sandbox。出现 VFS 警告、GradleJvmSupportMatrix / IllegalArgumentException: 25 等可先执行本任务再 runIde"
        delete(layout.buildDirectory.dir("idea-sandbox"))
    }

    patchPluginXml {
        sinceBuild.set("233")
        untilBuild.set("243.*")
    }

    withType<JavaCompile> {
        options.encoding = "UTF-8"
    }

    withType<org.jetbrains.kotlin.gradle.tasks.KotlinCompile>().configureEach {
        kotlinOptions {
            jvmTarget = "17"
        }
    }

    // RunIdeBase 用 projectExecutable 启动进程，设置 JavaExec.executable 无效；无 jbr 时会退回 Gradle JDK（如 ms-17）。
    // 勿再加 -XX:+UseParallelGC：与 idea.vmoptions 里的 G1 叠加会报 Multiple garbage collectors selected。
    named<RunIdeTask>("runIde") {
        if (project.hasProperty("freshSandbox")) {
            dependsOn("cleanIdeaSandbox")
        }
        val jbrJava = ideaLocalPath?.let { root ->
            val base = file(root)
            sequenceOf(
                base.resolve("jbr/bin/java.exe"),
                base.resolve("jbr/bin/java"),
            ).firstOrNull { it.isFile }
        }
        if (jbrJava != null) {
            projectExecutable.set(jbrJava.absolutePath)
        }
        val maxHeap = (project.findProperty("runIdeMaxHeap") as String?)?.trim()?.takeIf { it.isNotEmpty() } ?: "2048m"
        maxHeapSize = maxHeap
        minHeapSize = "256m"
        jvmArgs("-XX:ReservedCodeCacheSize=256m")
    }
}
