"""Lift v1 deploy_test.json + eval_curve.jsonl to v2 field names (deployed/as_trained).

For runs whose process launched before the rename commit (e.g. the eval3 baseline
that was mid-flight). Run after the job finishes:
    uv run python scripts/migrate_deploy_v1_to_v2.py out/runs/<run_dir> [<run_dir> ...]
"""
from __future__ import annotations

import json
import sys
from pathlib import Path

RENAME = {
    "deploy_hack": "hack_deployed", "deploy_solve": "solve_deployed", "deploy_vhack": "vhack_deployed",
    "deploy_hack_on": "hack_as_trained", "deploy_solve_on": "solve_as_trained", "deploy_vhack_on": "vhack_as_trained",
    "train_hack": "hack_as_trained", "train_solve": "solve_as_trained", "train_vhack": "vhack_as_trained",
}


def _rename(d: dict) -> dict:
    return {RENAME.get(k, k): v for k, v in d.items()}


def migrate(run_dir: Path) -> None:
    deploy = run_dir / "deploy_test.json"
    rec = json.loads(deploy.read_text())
    if rec.get("schema") == "paired_final_v2":
        print(f"{run_dir.name}: already v2, skip")
        return
    rec = _rename(rec) | {"schema": "paired_final_v2"}
    deploy.write_text(json.dumps(rec, indent=2))
    curve = run_dir / "eval_curve.jsonl"
    if curve.exists():
        lines = [json.dumps(_rename(json.loads(l))) for l in curve.read_text().splitlines() if l.strip()]
        curve.write_text("\n".join(lines) + "\n")
    print(f"{run_dir.name}: migrated -> v2")


if __name__ == "__main__":
    for arg in sys.argv[1:]:
        migrate(Path(arg))
