import os, sys, json, subprocess, datetime
from pathlib import Path
checkout=Path(sys.argv[1]).resolve()
root=Path(sys.argv[2]).resolve()
side=sys.argv[3]
run=root/(side+"-"+datetime.datetime.now(datetime.timezone.utc).strftime("%Y%m%dT%H%M%SZ"))
run.mkdir(parents=True)
span=lambda name: json.dumps({"name":name,"durationMs":1,"endTimeUnixNano":"60000000000"})
cases=[("one span",[span("a")],False),("two names, one malformed line, limit 1",[span("a"),span("b"),"{not json"],True),("one malformed line only",["{not json"],False),("plural control: three names, two malformed lines, limit 1",[span("a"),span("b"),span("c"),"{not json","{not json"],True),("plural control: two malformed lines only",["{not json","{not json"],False)]
sha=subprocess.check_output(["git","rev-parse","HEAD"],cwd=checkout,text=True).strip()
parts=[f"T3 CLI trace summary — {side}",f"Commit: {sha}","Environment: Linux, Node "+subprocess.check_output(["node","--version"],text=True).strip()+", built CLI; synthetic JSONL; no server",""]
for i,(label,lines,limit) in enumerate(cases,1):
    folder=run/str(i); folder.mkdir()
    (folder/"trace.jsonl").write_text("\n".join(lines)+"\n")
    cmd=["node",str(checkout/"apps/server/dist/bin.mjs"),"trace","summary","--base-dir","./data"]+(["--limit","1"] if limit else [])
    env={**os.environ,"T3CODE_TRACE_FILE":"trace.jsonl","NO_COLOR":"1","T3CODE_DEV_SEED":"0"}
    result=subprocess.run(cmd,cwd=folder,env=env,text=True,capture_output=True)
    parts += [f"{i}. {label}","$ T3CODE_TRACE_FILE=trace.jsonl t3 trace summary --base-dir ./data"+(" --limit 1" if limit else ""),result.stdout.rstrip(),result.stderr.rstrip(),f"Exit: {result.returncode}",""]
    if result.returncode: raise RuntimeError(result.stderr)
text="\n".join(parts)
(root/(side+".txt")).write_text(text)
print(text)
