#!/usr/bin/env python3
"""Verify platform-build wrappers include the current headless target matrix."""

from __future__ import annotations

import json
import re
import sys
from pathlib import Path


REQUIRED_COMPONENT_TARGETS = [
    "pp_foundation",
    "pp_assets",
    "pp_paint",
    "pp_document",
    "pp_renderer_api",
    "pp_renderer_gl",
    "pp_paint_renderer",
    "pp_ui_core",
    "pp_platform_api",
    "pp_app_core",
    "pano_cli",
]

REQUIRED_ANDROID_PRESETS = [
    "android-arm64",
    "android-x64",
    "android-quest-arm64",
    "android-focus-arm64",
]

EXPECTED_CMAKE_PLATFORM_TARGETS = [
    "panopainter_platform_build_headless",
    "panopainter_platform_build_android_assets",
    "panopainter_platform_build_vcpkg_ui_core",
    "panopainter_platform_build_apple_remote",
]


def repo_root() -> Path:
    return Path(__file__).resolve().parents[2]


def cmake_test_targets(root: Path) -> list[str]:
    cmake_lists = root / "tests" / "CMakeLists.txt"
    text = cmake_lists.read_text(encoding="utf-8")
    return sorted(set(re.findall(r"^\s*add_executable\(([^\s\)]+)", text, re.MULTILINE)))


def powershell_default_targets(root: Path) -> list[str]:
    script = root / "scripts" / "automation" / "platform-build.ps1"
    targets: list[str] = []
    in_targets = False

    for line in script.read_text(encoding="utf-8").splitlines():
        if "[string[]]$Targets" in line:
            in_targets = True
        if not in_targets:
            continue

        targets.extend(re.findall(r'"([^"]+)"', line))
        if in_targets and line.strip() == ")":
            break

    return sorted(set(targets))


def powershell_default_presets(root: Path) -> list[str]:
    script = (root / "scripts" / "automation" / "platform-build.ps1").read_text(encoding="utf-8")
    match = re.search(r"\[string\[\]\]\$Presets\s*=\s*@\((.*?)\)", script, re.S)
    if not match:
        raise RuntimeError("Could not find default presets in platform-build.ps1")
    return sorted(set(re.findall(r'"([^"]+)"', match.group(1))))


def shell_default_targets(root: Path) -> list[str]:
    script = root / "scripts" / "automation" / "platform-build.sh"
    text = script.read_text(encoding="utf-8")
    match = re.search(r'targets="\$\{[^:]+:-(.*)\}"', text)
    if not match:
        raise RuntimeError("Could not find default targets in platform-build.sh")
    return sorted(set(match.group(1).split()))


def shell_default_presets(root: Path) -> list[str]:
    script = (root / "scripts" / "automation" / "platform-build.sh").read_text(encoding="utf-8")
    match = re.search(r'presets="\$\{[^:]+:-(.*)\}"', script)
    if not match:
        raise RuntimeError("Could not find default presets in platform-build.sh")
    return sorted(set(match.group(1).split()))


def missing(expected: list[str], actual: list[str]) -> list[str]:
    actual_set = set(actual)
    return [target for target in expected if target not in actual_set]


def main() -> int:
    root = repo_root()
    expected = sorted(set(REQUIRED_COMPONENT_TARGETS + cmake_test_targets(root)))
    ps_targets = powershell_default_targets(root)
    sh_targets = shell_default_targets(root)
    ps_presets = powershell_default_presets(root)
    sh_presets = shell_default_presets(root)
    cmake_platform_module = (root / "cmake" / "PanoPainterPlatformTargets.cmake").read_text(encoding="utf-8")
    root_cmake = (root / "CMakeLists.txt").read_text(encoding="utf-8")
    cmake_platform_targets_present = {
        target: target in cmake_platform_module for target in EXPECTED_CMAKE_PLATFORM_TARGETS
    }
    cmake_platform_module_included = "include(PanoPainterPlatformTargets)" in root_cmake
    android_sdk_env = {
        "android-sdk-env.ps1": (root / "scripts" / "automation" / "android-sdk-env.ps1").read_text(encoding="utf-8"),
        "android-sdk-env.sh": (root / "scripts" / "automation" / "android-sdk-env.sh").read_text(encoding="utf-8"),
    }
    android_sdkmanager_update_support = {
        name: all(token in text for token in ("sdkmanager", "--list", "--install", "ndk", "cmake"))
        for name, text in android_sdk_env.items()
    }

    result = {
        "ok": True,
        "expectedTargetCount": len(expected),
        "powershellTargetCount": len(ps_targets),
        "shellTargetCount": len(sh_targets),
        "expectedAndroidPresets": REQUIRED_ANDROID_PRESETS,
        "defaultPresets": {
            "platform-build.ps1": ps_presets,
            "platform-build.sh": sh_presets,
        },
        "cmakePlatformTargetsPresent": cmake_platform_targets_present,
        "cmakePlatformModuleIncluded": cmake_platform_module_included,
        "androidSdkmanagerUpdateSupport": android_sdkmanager_update_support,
        "missing": {
            "platform-build.ps1.targets": missing(expected, ps_targets),
            "platform-build.sh.targets": missing(expected, sh_targets),
            "platform-build.ps1.presets": missing(REQUIRED_ANDROID_PRESETS, ps_presets),
            "platform-build.sh.presets": missing(REQUIRED_ANDROID_PRESETS, sh_presets),
        },
    }
    result["ok"] = (
        all(not values for values in result["missing"].values())
        and all(cmake_platform_targets_present.values())
        and cmake_platform_module_included
        and all(android_sdkmanager_update_support.values())
    )

    print(json.dumps(result, separators=(",", ":")))
    return 0 if result["ok"] else 1


if __name__ == "__main__":
    sys.exit(main())
