from __future__ import annotations

import argparse
import subprocess
import sys
from pathlib import Path


ROOT = Path(__file__).resolve().parents[1]
GENERATED_PATHS = [
    ROOT / "plugins" / "1c" / "rag" / "sources" / "metadata.health.generated.md",
]


def run(command: list[str]) -> tuple[str, int]:
    label = " ".join(command)
    print(f"\n== {label}")
    result = subprocess.run(command, cwd=ROOT, text=True, check=False)
    return label, result.returncode


def check_no_generated_artifacts() -> tuple[str, int]:
    label = "generated artifact check"
    print(f"\n== {label}")
    leftovers = [path for path in GENERATED_PATHS if path.exists()]
    if leftovers:
        print("Unexpected generated artifact(s):", file=sys.stderr)
        for path in leftovers:
            print(f"- {path.relative_to(ROOT)}", file=sys.stderr)
        return label, 1
    print("No unexpected generated artifacts.")
    return label, 0


def main() -> int:
    parser = argparse.ArgumentParser(description="Run local repository checks.")
    parser.add_argument(
        "--with-training-preflight",
        action="store_true",
        help="Run checks that may report blocked when local CUDA/training dependencies are unavailable.",
    )
    args = parser.parse_args()

    py_files = [str(path.relative_to(ROOT)) for path in sorted((ROOT / "scripts").glob("*.py"))]
    commands = [
        [sys.executable, "scripts/validate_model_cards.py"],
        [sys.executable, "scripts/validate_evals.py"],
        [sys.executable, "scripts/validate_gpu_profiles.py"],
        [sys.executable, "scripts/check_powershell_scripts.py"],
        [sys.executable, "scripts/check_model_storage.py", "--no-report", "--warn-only"],
        [sys.executable, "scripts/check_1c_plugin.py", "--no-report"],
        [sys.executable, "scripts/check_1c_mcp_adapter_contract.py"],
        [sys.executable, "scripts/check_1c_adapter_verification_stack.py"],
        [sys.executable, "scripts/smoke_1c_mcp_selector_chain.py", "--no-report"],
        [sys.executable, "-m", "py_compile", *py_files],
    ]
    if args.with_training_preflight:
        commands.append([sys.executable, "scripts/preflight_1c_training.py"])

    failures = []
    for command in commands:
        label, returncode = run(command)
        if returncode != 0:
            failures.append(label)

    label, returncode = check_no_generated_artifacts()
    if returncode != 0:
        failures.append(label)

    if failures:
        print("\nCheck failed:", file=sys.stderr)
        for failure in failures:
            print(f"- {failure}", file=sys.stderr)
        return 1

    print("\nAll checks passed.")
    return 0


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