#!/usr/bin/env python3
"""Generate a throwaway Gradle project that compiles every Vanta package
against the public SDK + real Compose, so Kotlin/Compose errors are caught on
Zo instead of on the build box. Soong is still what ships; this only checks.

Source and res dirs point straight at vendor/vanta/packages/*; manifests are
copied with package= stripped (AGP 8 rejects it) into build/shadow/.
"""
import os, re, shutil, sys

ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
PK = os.path.join(ROOT, "vendor/vanta/packages")
OUT = os.path.join(ROOT, "build/shadow-" + ("-".join(sys.argv[1:]) or "all"))

# The versions AOSP 17 vendors (prebuilts/sdk/current/androidx and external/
# kotlinc, kotlinx.coroutines at android-17.0.0_r1), so "compiles here" means
# "compiles in Soong": a deprecated-to-hidden API fails here first.
KOTLIN = "2.2.0"
COMPOSE = """
    implementation("androidx.compose.runtime:runtime:1.12.0-alpha01")
    implementation("androidx.compose.ui:ui:1.12.0-alpha01")
    implementation("androidx.compose.foundation:foundation:1.12.0-alpha01")
    implementation("androidx.compose.animation:animation:1.12.0-alpha01")
    implementation("androidx.compose.material3:material3:1.5.0-alpha16")
    implementation("androidx.activity:activity-compose:1.14.0-alpha01")
    implementation("androidx.lifecycle:lifecycle-runtime-ktx:2.11.0-alpha03")
    implementation("androidx.lifecycle:lifecycle-runtime-compose:2.11.0-alpha03")
    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.10.1")
"""


def module(name, kind, ns, deps):
    src = os.path.join(PK, name)
    d = os.path.join(OUT, name)
    os.makedirs(d, exist_ok=True)
    man = open(os.path.join(src, "AndroidManifest.xml")).read()
    man = re.sub(r'\s+package="[^"]+"', "", man, count=1)
    man = re.sub(r'\s+android:sharedUserId="[^"]+"', "", man)
    open(os.path.join(d, "AndroidManifest.xml"), "w").write(man)
    res = os.path.join(src, "res")
    plugin = "com.android.library" if kind == "lib" else "com.android.application"
    app_id = f'        applicationId = "{ns}"\n' if kind == "app" else ""
    open(os.path.join(d, "build.gradle.kts"), "w").write(f"""
plugins {{ id("{plugin}"); id("org.jetbrains.kotlin.android"); id("org.jetbrains.kotlin.plugin.compose") }}
android {{
    namespace = "{ns}"
    compileSdk = 36
    defaultConfig {{
{app_id}        minSdk = 34
    }}
    sourceSets["main"].manifest.srcFile("AndroidManifest.xml")
    sourceSets["main"].java.srcDirs("{src}/src")
    sourceSets["main"].res.srcDirs({('"' + res + '"') if os.path.isdir(res) else ''})
    compileOptions {{ sourceCompatibility = JavaVersion.VERSION_17; targetCompatibility = JavaVersion.VERSION_17 }}
    buildFeatures {{ compose = true }}
    lint {{ abortOnError = false; checkReleaseBuilds = false }}
}}
// No global -opt-in: Soong passes none, so an unmarked experimental call must fail here too.
kotlin {{
    compilerOptions {{
        jvmTarget.set(org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17)
    }}
}}
dependencies {{
{COMPOSE}{deps}
}}
""")


def main():
    if os.path.isdir(OUT):
        shutil.rmtree(OUT)
    os.makedirs(OUT)
    names = sorted(n for n in os.listdir(PK) if os.path.isfile(os.path.join(PK, n, "Android.bp")))
    only = sys.argv[1:]
    mods = []
    for n in names:
        if only and n not in only and n != "VantaCore":
            continue
        man = open(os.path.join(PK, n, "AndroidManifest.xml")).read()
        ns = re.search(r'package="([^"]+)"', man).group(1)
        bp = open(os.path.join(PK, n, "Android.bp")).read()
        kind = "lib" if "android_library" in bp else "app"
        deps = '    implementation(project(":VantaCore"))\n' if n != "VantaCore" else ""
        module(n, kind, ns, deps)
        mods.append(n)
    open(os.path.join(OUT, "settings.gradle.kts"), "w").write(
        'pluginManagement { repositories { google(); mavenCentral(); gradlePluginPortal() } }\n'
        'dependencyResolutionManagement { repositories { google(); mavenCentral() } }\n'
        'rootProject.name = "vanta-shadow"\n' + "".join(f'include(":{m}")\n' for m in mods))
    open(os.path.join(OUT, "build.gradle.kts"), "w").write(
        'plugins {\n  id("com.android.application") version "8.12.0" apply false\n'
        '  id("com.android.library") version "8.12.0" apply false\n'
        f'  id("org.jetbrains.kotlin.android") version "{KOTLIN}" apply false\n'
        f'  id("org.jetbrains.kotlin.plugin.compose") version "{KOTLIN}" apply false\n}}\n')
    open(os.path.join(OUT, "gradle.properties"), "w").write(
        "android.useAndroidX=true\norg.gradle.jvmargs=-Xmx4g\nandroid.suppressUnsupportedCompileSdk=36\n")
    open(os.path.join(OUT, "local.properties"), "w").write(f"sdk.dir={os.environ.get('ANDROID_SDK', '/opt/android-sdk')}\n")
    print("shadow: " + " ".join(mods))
    print(OUT)


main()
