#!/usr/bin/env python3
import argparse
import subprocess
import sys
from pathlib import Path

from script_common import resolve_repo_root


def run_step(repo_root: Path, title: str, command: list[str]) -> int:
    print(f"\n== {title} ==")
    print("$", " ".join(command))
    proc = subprocess.run(command, cwd=str(repo_root), check=False)
    return proc.returncode


def main() -> int:
    parser = argparse.ArgumentParser(description="Cross-platform migration quality gate")
    parser.add_argument("--repo-root", default=None)
    parser.add_argument("--skip-tests", action="store_true")
    parser.add_argument("--test-project", default=None, help="Optional test csproj path")
    args = parser.parse_args()

    repo_root = resolve_repo_root(args.repo_root)

    code = run_step(repo_root, "Build", [sys.executable, "scripts/dotnet-min.py", "build"])
    if code != 0:
        return code

    if not args.skip_tests:
        if args.test_project:
            test_cmd = [sys.executable, "scripts/dotnet-min.py", "test", args.test_project]
        else:
            test_cmd = [sys.executable, "scripts/dotnet-min.py", "test"]
        code = run_step(repo_root, "Tests", test_cmd)
        if code != 0:
            return code

    print("\nMigration gate passed.")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
