#!/usr/bin/env python3
"""Unified RepoKey PL QoR adapter for AI agents."""

from __future__ import annotations

import argparse
import subprocess
import sys
from pathlib import Path


ROOT = Path(__file__).resolve().parents[1]
SCRIPTS = ROOT / "scripts"
PROFILES = ROOT / "profiles"
DEFAULT_PROFILE = PROFILES / "vivado_2020_2.json"
DEFAULT_VIVADO_2020_2 = r"D:\Xilinx\vivado2020.2\Vivado\2020.2\bin\vivado.bat"


def default_out_root(project_root: str | None = None) -> Path:
    if project_root:
        return Path(project_root).resolve() / ".vivado_ai_mcp" / "qor"
    return Path.cwd().resolve() / ".vivado_ai_mcp" / "qor"


def run_script(script: str, args: list[str]) -> int:
    cmd = [sys.executable, str(SCRIPTS / script), *args]
    return subprocess.call(cmd, cwd=str(ROOT))


def main(argv: list[str]) -> int:
    parser = argparse.ArgumentParser(description="RepoKey PL QoR adapter")
    sub = parser.add_subparsers(dest="cmd", required=True)

    p = sub.add_parser("probe", help="probe Vivado/RapidWright compatibility")
    p.add_argument("--profile", default=str(DEFAULT_PROFILE))
    p.add_argument("--vivado", default=DEFAULT_VIVADO_2020_2)
    p.add_argument("--dcp", default=None)

    p = sub.add_parser("collect-baseline", help="collect Vivado-only QoR evidence")
    p.add_argument("--vivado", default=DEFAULT_VIVADO_2020_2)
    p.add_argument("--dcp", default=None)
    p.add_argument("--project", default=None)
    p.add_argument("--run", default=None)
    p.add_argument("--project-root", default=None, help="Vivado project root for .vivado_ai_mcp/qor output")
    p.add_argument("--out-root", default=None)
    p.add_argument("--name", required=True)
    p.add_argument("--dry-run", action="store_true")

    p = sub.add_parser("decide", help="generate AI decision record from QoR evidence")
    p.add_argument("--qor-dir", required=True)

    p = sub.add_parser("compare", help="compare two QoR evidence directories")
    p.add_argument("--before", required=True)
    p.add_argument("--after", required=True)
    p.add_argument("--out", default=None)

    p = sub.add_parser("make-experiment", help="generate reviewed Vivado experiment Tcl")
    p.add_argument("--experiment", required=True)
    p.add_argument("--dcp", required=True)
    p.add_argument("--project-root", default=None, help="Vivado project root for .vivado_ai_mcp/qor output")
    p.add_argument("--out-root", default=None)
    p.add_argument("--name", required=True)

    args = parser.parse_args(argv)

    if args.cmd == "probe":
        cmd_args = ["--profile", args.profile, "--vivado", args.vivado]
        if args.dcp:
            cmd_args.extend(["--dcp", args.dcp])
        return run_script("compat_probe.py", cmd_args)

    if args.cmd == "collect-baseline":
        out_root = args.out_root or str(default_out_root(args.project_root or args.project))
        cmd_args = ["--vivado", args.vivado, "--out-root", out_root, "--name", args.name]
        if args.dcp:
            cmd_args.extend(["--dcp", args.dcp])
        if args.project:
            cmd_args.extend(["--project", args.project])
        if args.run:
            cmd_args.extend(["--run", args.run])
        if args.dry_run:
            cmd_args.append("--dry-run")
        return run_script("vivado_qor_collect.py", cmd_args)

    if args.cmd == "decide":
        return run_script("qor_decision.py", [args.qor_dir])

    if args.cmd == "compare":
        cmd_args = [args.before, args.after]
        if args.out:
            cmd_args.extend(["--out", args.out])
        return run_script("qor_compare.py", cmd_args)

    if args.cmd == "make-experiment":
        out_root = args.out_root or str(default_out_root(args.project_root))
        return run_script(
            "vivado_safe_experiment.py",
            [
                "--experiment",
                args.experiment,
                "--dcp",
                args.dcp,
                "--out-root",
                out_root,
                "--name",
                args.name,
            ],
        )

    parser.error(f"unhandled command: {args.cmd}")
    return 2


if __name__ == "__main__":
    raise SystemExit(main(sys.argv[1:]))
