"""Run one trial: <lang> <tier: simple|complex> <arm: process|outcome> <rep>.

Builds a fresh workspace outside the repo, (process arm) asks the planner for a step list,
runs the agent, copies the deliverable and logs back into trials/<id>/, then grades.
Needs AI_BUILDER_TOKEN in the environment (op run --env-file ../aib.env).
"""
import json, shutil, subprocess, sys
from pathlib import Path

sys.path.insert(0, "<chatgpt-oauth>/src")
from chat_gpt_oauth.client import request_result  # noqa: E402

HERE = Path(__file__).resolve().parent
PY = str(HERE.parents[1] / ".venv/bin/python")
RUNS = Path("<workspace>/tmp/3_7_runs")
MODEL = "gpt-6.1-sol"
lang, tier, arm, rep = sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4]
tid = f"{lang}_{tier}_{arm}_{rep}"
P = HERE / f"prompts_{lang}"
out_dir = HERE / "trials" / tid
out_dir.mkdir(parents=True, exist_ok=True)


def fill(tmpl: str, **kw) -> str:
    text = (P / tmpl).read_text(encoding="utf-8")
    for k, v in kw.items():
        text = text.replace("{" + k + "}", v)
    return text


def duration(p: Path) -> float:
    r = subprocess.run(["ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", str(p)],
                       capture_output=True, text=True)
    return float(r.stdout.strip())


# 1. workspace
run_root = RUNS / tid
if run_root.exists():
    subprocess.run(["trash", str(run_root)], check=True)
ws = run_root / "ws"
ws.mkdir(parents=True)
for f in ("API.md", "names.md"):
    shutil.copy(HERE / f"fixture_{lang}" / f, ws / f)
if tier == "complex":
    (ws / "meeting").mkdir()
    for f in sorted((HERE / f"meeting_{lang}" / "recordings").iterdir()):
        shutil.copy(f, ws / "meeting" / f.name)
else:
    (ws / "memos").mkdir()
    shutil.copy(HERE.parent / ("corpus" if lang == "zh" else "../experiments_en/corpus") / "audio" / "W01.wav", ws / "memos" / "W01.wav")

task = (P / f"task_{tier}.md").read_text(encoding="utf-8")
criteria = (P / f"criteria_{tier}.md").read_text(encoding="utf-8")

# 2. prompt
if arm == "outcome":
    prompt = fill("outcome.tmpl", task=task, criteria=criteria)
else:
    listing = []
    for p in sorted(ws.rglob("*")):
        if p.is_file():
            rel = p.relative_to(ws)
            if p.suffix in (".m4a", ".wav"):
                listing.append(f"- {rel}（{p.stat().st_size / 1e6:.1f} MB，{duration(p) / 60:.1f} 分钟）" if lang == "zh"
                               else f"- {rel} ({p.stat().st_size / 1e6:.1f} MB, {duration(p) / 60:.1f} min)")
            else:
                listing.append(f"- {rel}")
    planner_prompt = fill("planner.tmpl", task=task, criteria=criteria, listing="\n".join(listing) + "\n")
    (out_dir / "planner_prompt.md").write_text(planner_prompt, encoding="utf-8")
    plan = request_result(planner_prompt, model=MODEL, reasoning_effort="high", timeout=900)["answer"].strip()
    (out_dir / "plan.md").write_text(plan + "\n", encoding="utf-8")
    prompt = fill("process.tmpl", task=task, steps=plan + "\n")
(out_dir / "prompt.md").write_text(prompt, encoding="utf-8")
(run_root / "prompt.md").write_text(prompt, encoding="utf-8")

# 3. agent
subprocess.run([PY, str(HERE / "harness" / "mini_agent.py"), "--workspace", str(ws), "--prompt-file",
                str(run_root / "prompt.md"), "--log-dir", str(out_dir / "log"), "--model", MODEL], check=True)

# 4. copy deliverables and anything the agent wrote (skip audio and caches)
keep = out_dir / "workspace"
if keep.exists():
    shutil.rmtree(keep)
for p in ws.rglob("*"):
    if p.is_file() and p.suffix.lower() not in (".m4a", ".wav", ".mp3", ".flac", ".ogg", ".aac", ".pyc") \
            and not any(part.startswith(".") or part in ("__pycache__", ".venv", "venv") for part in p.relative_to(ws).parts) \
            and p.stat().st_size < 2_000_000:
        dst = keep / p.relative_to(ws)
        dst.parent.mkdir(parents=True, exist_ok=True)
        shutil.copy(p, dst)

# 5. grade
if tier == "complex":
    subprocess.run([PY, str(HERE / "grade.py"), lang, str(ws / "minutes" / ("会议逐字稿.md" if lang == "zh" else "transcript.md")),
                    "--json", str(out_dir / "grade.json")], check=True)
else:
    subprocess.run([PY, str(HERE / "grade_simple.py"), lang, str(ws / "notes" / "W01.md"), "--json", str(out_dir / "grade.json")], check=True)
print("done", tid)
