#!/usr/bin/env python3
"""Generate a Vivado-only safe optimization experiment Tcl script."""

from __future__ import annotations

import argparse
import json
import sys
from datetime import datetime
from pathlib import Path


ALLOWED_EXPERIMENTS = {
    "phys_opt_default": ["phys_opt_design"],
    "phys_opt_aggressive_explore": ["phys_opt_design -directive AggressiveExplore"],
    "route_more_global_iterations": ["route_design -directive MoreGlobalIterations"],
}


def ps_path(path: Path) -> str:
    return str(path).replace("\\", "/")


def main(argv: list[str]) -> int:
    parser = argparse.ArgumentParser(description="Generate safe Vivado experiment")
    parser.add_argument("--experiment", required=True, choices=sorted(ALLOWED_EXPERIMENTS))
    parser.add_argument("--dcp", required=True, help="input DCP path")
    parser.add_argument("--out-root", default=".vivado_ai_mcp/qor")
    parser.add_argument("--name", default=None)
    parser.add_argument("--execute", action="store_true", help="reserved; use generated Tcl explicitly")
    args = parser.parse_args(argv)

    if args.execute:
        parser.error("--execute is intentionally not implemented; review and run the generated Tcl explicitly")

    in_dcp = Path(args.dcp).resolve()
    tag = args.name or f"{args.experiment}_{datetime.now().strftime('%Y%m%d_%H%M%S')}"
    out_dir = Path(args.out_root).resolve() / tag
    raw = out_dir / "raw"
    raw.mkdir(parents=True, exist_ok=True)
    out_dcp = out_dir / f"{tag}.dcp"
    tcl = out_dir / "experiment.tcl"

    lines = [
        f"open_checkpoint {{{ps_path(in_dcp)}}}",
        f"file mkdir {{{ps_path(raw)}}}",
        f"report_timing_summary -file {{{ps_path(raw / 'before_timing_summary.rpt')}}} -delay_type max -max_paths 20 -nworst 1",
        *ALLOWED_EXPERIMENTS[args.experiment],
        f"report_timing_summary -file {{{ps_path(raw / 'after_timing_summary.rpt')}}} -delay_type max -max_paths 20 -nworst 1",
        f"report_utilization -file {{{ps_path(raw / 'after_utilization.rpt')}}}",
        f"write_checkpoint -force {{{ps_path(out_dcp)}}}",
        "exit",
    ]
    tcl.write_text("\n".join(lines) + "\n", encoding="utf-8")

    manifest = {
        "created_at": datetime.now().isoformat(timespec="seconds"),
        "tool": "vivado_safe_experiment",
        "experiment": args.experiment,
        "input_dcp": str(in_dcp),
        "output_dcp": str(out_dcp),
        "artifacts": {"tcl": str(tcl), "out_dir": str(out_dir)},
        "safety": {
            "automatic_execution": False,
            "requires_review": True,
            "rtl_or_xdc_modified": False,
        },
    }
    (out_dir / "manifest.json").write_text(json.dumps(manifest, indent=2), encoding="utf-8")
    print(json.dumps(manifest, indent=2))
    return 0


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