pluginManagement {
    val flutterSdkPath =
        run {
            val properties = java.util.Properties()
            file("local.properties").inputStream().use { properties.load(it) }
            val flutterSdkPath = properties.getProperty("flutter.sdk")
            require(flutterSdkPath != null) { "flutter.sdk not set in local.properties" }
            flutterSdkPath
        }

    includeBuild("$flutterSdkPath/packages/flutter_tools/gradle")

    repositories {
        google()
        mavenCentral()
        gradlePluginPortal()
    }
}

plugins {
    id("dev.flutter.flutter-plugin-loader") version "1.0.0"
    id("com.android.application") version "8.11.1" apply false
    id("org.jetbrains.kotlin.android") version "2.2.20" apply false
}

include(":app")

// USB Camera 插件子模块引用
// flutter_usbcamera 的 build.gradle 写死了 implementation project(':libausbc')
// 必须在根项目 settings 中注册 :libausbc, :libuvc, :libnative
// 使用字符串 indexOf 从 .flutter-plugins-dependencies 中解析路径（避免正则转义问题）

val pluginsFile = java.io.File(rootProject.projectDir.parentFile, ".flutter-plugins-dependencies")
val text = pluginsFile.readText()

// JSON 格式: {"name":"flutter_usbcamera","path":"/some/path/",...}
// 找到 "flutter_usbcamera" 然后找它后面的第一个 "path" 值
val cameraKey = "\"flutter_usbcamera\""
val cameraIdx = text.indexOf(cameraKey)
if (cameraIdx >= 0) {
    // 从 cameraKey 之后找 "\"path\":\""
    val afterKey = text.substring(cameraIdx + cameraKey.length)
    val pathKey = "\"path\":\""
    val pathIdx = afterKey.indexOf(pathKey)
    if (pathIdx >= 0) {
        val pathStart = pathIdx + pathKey.length
        val pathEnd = afterKey.indexOf("\"", pathStart)
        if (pathEnd >= 0) {
            val pluginPath = afterKey.substring(pathStart, pathEnd) + "/android"
            include(":libuvc")
            project(":libuvc").projectDir = java.io.File(pluginPath, "libuvc")
            include(":libnative")
            project(":libnative").projectDir = java.io.File(pluginPath, "libnative")
            include(":libausbc")
            project(":libausbc").projectDir = java.io.File(pluginPath, "libausbc")
        }
    }
}
