#!/usr/bin/env/python3
import subprocess
import pathlib
import configparser

IGNORE = {
    # Frameworks not present in the latest SDK
    "GameCenter",
    "InterfaceBuilderKit"
    "Message",
    "PubSub",
    "QTKit",
    "XgridFoundation",
}


BASE = pathlib.Path(__file__).resolve().parent.parent

scan_failed = []
compile_failed = []
for nm in BASE.glob("pyobjc-framework-*"):
    cfg = configparser.RawConfigParser()
    cfg.read(nm / "metadata" / "metadata.ini")

    for section in cfg.sections():
        if section in IGNORE:
            continue
        print(nm.name, section)
        overrides = nm / "metadata" / (cfg[section]["framework"] + ".fwinfo")

        try:
            subprocess.check_call(
                [
                    "objective-metadata-tool",
                    f"--ini-section={section}",
                    "scan",
                    "--arch=x86_64,arm64",
                    "--sdk=14.0",
                ],
                cwd=nm,
            )

        except subprocess.CalledProcessError:
            scan_failed.append((nm.name, section))
            continue

        subprocess.call(["git", "checkout", overrides])

        try:
            subprocess.check_call(
                ["objective-metadata-tool", f"--ini-section={section}", "compile"],
                cwd=nm,
            )
        except subprocess.CalledProcessError:
            compile_failed.append((nm.name, section))

            # Undo the compile attempt
            if "python-package" in cfg[section]:
                subprocess.call(
                    [
                        "git",
                        "checkout",
                        nm
                        / "Lib"
                        / cfg[section]["python-package"].replace(".", "/")
                        / "_metadata.py",
                    ]
                )
            else:
                subprocess.call(
                    [
                        "git",
                        "checkout",
                        nm / "Lib" / cfg[section]["framework"] / "_metadata.py",
                    ]
                )
            continue


if scan_failed:
    print("Scanning failed for:")
    for wrapper, section in scan_failed:
        print(f"* {wrapper} - {section}")
    print("")

if compile_failed:
    print("Compiling failed for:")
    for wrapper, section in compile_failed:
        print(f"* {wrapper} - {section}")
    print("")
