#!/usr/bin/env python3
"""Guard retained non-root platform CMake files during Phase 6 migration."""

from __future__ import annotations

import json
import re
import sys
from pathlib import Path


RETAINED_PLATFORM_CMAKE = [
    Path("linux/CMakeLists.txt"),
    Path("webgl/CMakeLists.txt"),
]


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


def cmake_minimum_version(text: str) -> tuple[int, ...] | None:
    match = re.search(r"cmake_minimum_required\s*\(\s*VERSION\s+([0-9.]+)", text, re.I)
    if not match:
        return None
    return tuple(int(part) for part in match.group(1).split("."))


def main() -> int:
    root = repo_root()
    results: dict[str, object] = {}
    ok = True

    for path in RETAINED_PLATFORM_CMAKE:
        text = (root / path).read_text(encoding="utf-8")
        minimum_version = cmake_minimum_version(text)
        has_target_cxx23 = "target_compile_features(panopainter PRIVATE cxx_std_23)" in text
        has_cxx_extensions_off = "CXX_EXTENSIONS OFF" in text
        uses_global_cxx_standard_flag = bool(re.search(r"-std=c\+\+14|-std=c\+\+17|-std=c\+\+20", text))
        platform_ok = (
            minimum_version is not None
            and minimum_version >= (3, 10)
            and has_target_cxx23
            and has_cxx_extensions_off
            and not uses_global_cxx_standard_flag
        )
        ok = ok and platform_ok
        results[str(path)] = {
            "ok": platform_ok,
            "minimumVersion": ".".join(str(part) for part in minimum_version) if minimum_version else None,
            "hasTargetCxx23": has_target_cxx23,
            "hasCxxExtensionsOff": has_cxx_extensions_off,
            "usesGlobalCxxStandardFlag": uses_global_cxx_standard_flag,
        }

    print(json.dumps({"ok": ok, "platforms": results}, separators=(",", ":")))
    return 0 if ok else 1


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