import os, sys, subprocess, pathlib, json, time, datetime, threading
root = pathlib.Path(sys.argv[1]) / datetime.datetime.now().strftime("%Y%m%dT%H%M%S")
root.mkdir(parents=True)
os.chdir(root)
state = json.loads(pathlib.Path(sys.argv[2]).read_text())
tool = os.environ.get("PROOF_AGENT_DEVICE", "agent-device")
session = os.environ.get("PROOF_SESSION", "image-path-proof")
class LocalScreenRecording:
    def __init__(self, output):
        self.output=pathlib.Path(output)
        self.frames_dir=root/(self.output.stem+"-frames")
        self.frames_dir.mkdir()
        self.stopped=threading.Event()
        self.frames=[]
        self.started=time.monotonic()
        self.thread=threading.Thread(target=self.capture)
        self.thread.start()
    def capture(self):
        index=0
        while not self.stopped.is_set():
            timestamp=time.monotonic()-self.started
            frame=self.frames_dir/(f"frame-{index:05d}.png")
            result=subprocess.run([tool,"screenshot",str(frame),"--session",session],capture_output=True,text=True)
            if result.returncode==0 and frame.exists(): self.frames.append((timestamp,frame))
            index+=1
            self.stopped.wait(max(0,1-(time.monotonic()-self.started-timestamp)))
    def stop(self):
        self.stopped.set()
        self.thread.join()
        if len(self.frames)<2: raise RuntimeError("The device screenshot stream produced too few frames")
        ended=time.monotonic()-self.started
        manifest=self.frames_dir/"frames.txt"
        rows=[]
        for i,(timestamp,frame) in enumerate(self.frames):
            next_time=self.frames[i+1][0] if i+1<len(self.frames) else ended
            rows += ["file '"+str(frame)+"'", "duration "+str(max(.1,next_time-timestamp))]
        rows += ["file '"+str(self.frames[-1][1])+"'"]
        manifest.write_text("\n".join(rows)+"\n")
        subprocess.run(["ffmpeg","-y","-f","concat","-safe","0","-i",str(manifest),"-vf","fps=10","-c:v","libx264","-preset","veryfast","-crf","20","-pix_fmt","yuv420p",str(self.output)],stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL,check=True)
        print("LOCAL_RECORDING",self.output,flush=True)
local_recording=None
def call(*args):
    global local_recording
    if os.environ.get("PROOF_LOCAL_RECORD") == "1" and args[0] == "record":
        if args[1] == "start": local_recording=LocalScreenRecording(args[2])
        else:
            local_recording.stop()
            local_recording=None
        return {}
    args=[str(x) for x in args]
    p=subprocess.run([tool,*args,"--session",session]+([] if args[0]=="record" else ["--json"]),capture_output=True,text=True)
    with (root/"actions.jsonl").open("a") as f:
        f.write(json.dumps({"command":args,"stdout":p.stdout,"stderr":p.stderr,"exit":p.returncode})+"\n")
    if p.returncode: raise RuntimeError(p.stderr or p.stdout)
    if args[0]=="record": return {"output":p.stdout}
    result=json.loads(p.stdout)
    if not result.get("success"): raise RuntimeError(str(result))
    return result.get("data",{})
def tree():
    data=call("snapshot","-i")
    return [{**n,"_generation":data["refsGeneration"]} for n in data["nodes"]]
def ref(n): return "@"+n["ref"]+"~s"+str(n["_generation"])
def candidates(label,kind=None):
    return [n for n in tree() if n.get("label")==label and (kind is None or n.get("kind")==kind) and n.get("visibleToUser",True) and n.get("rect",{}).get("height",0)>0]
def target(label,kind=None):
    ns=candidates(label,kind)
    if not ns: raise RuntimeError("No visible target: "+label)
    return ref(ns[0])
def tap(label,kind=None):
    selector="label="+json.dumps(label)+(f" role={kind}" if kind else "")
    return call("press",selector,"--settle")
def shot(label):
    if os.environ.get("PROOF_RECORD_ONLY") == "1": return
    for i in range(12):
        a=root/(label+"-a.png");b=root/(label+"-b.png")
        call("screenshot",a);time.sleep(.5);call("screenshot",b)
        if a.read_bytes()==b.read_bytes():
            (root/(label+".png")).write_bytes(b.read_bytes())
            print("CAPTURE",root/(label+".png"),flush=True)
            return
    raise RuntimeError("Screen did not stabilize: "+label)
def row_label(i,f):
    return "Read "+("file://"+state["project"]+"/my%20shot.png" if i==3 else state["project"]+"/"+f)
results=[]
for i,f in enumerate(state["files"]):
    if i < int(os.environ.get("PROOF_START_CASE", "0")): continue
    if i >= int(os.environ.get("PROOF_END_CASE", "4")): break
    label=["percent","hash","question","file-url"][i]
    name=pathlib.PurePosixPath(f).name
    row=row_label(i,f)
    call("record","start",root/(root.parent.name+"-"+root.name+"-"+label+".mp4"),"--hide-touches")
    try:
        tap(row,"button")
        call("wait",1200)
        shot(label+"-preview")
        images=candidates(name,"button")
        if not images:
            results.append({"case":label,"imageControlPresent":False,"actions":False})
        else:
            call("longpress",ref(images[0]),"--settle")
            shot(label+"-actions")
            tap("Copy full path")
            call("wait","absent",'label="Dismiss copied text"',10000)
            tap("Ask anything","text-field")
            paste=[]
            for attempt in range(8):
                call("wait",700)
                paste=[n for n in tree() if n.get("label","").startswith("Paste item")]
                if paste: break
            if not paste: raise RuntimeError("Gboard did not offer the copied clipboard item")
            clipboard=paste[0]["label"][len("Paste item, "):] if paste[0]["label"].startswith("Paste item, ") else "Gboard clipboard item"
            call("press",ref(paste[0]),"--settle")
            call("wait",700)
            call("keyboard","dismiss")
            shot(label+"-clipboard")
            field=[n for n in tree() if n.get("kind")=="text-field"][0]
            observed=field.get("value",field.get("label"))
            call("fill",ref(field),"","--settle")
            call("keyboard","dismiss")
            call("wait",700)
            image=target(name,"button")
            call("longpress",image,"--settle")
            tap("Open in file viewer")
            call("wait","absent",'label="Add attachment"',20000)
            call("wait",1500)
            shot(label+"-file-viewer")
            viewer=tree()
            results.append({"case":label,"imageControlPresent":True,"actions":True,"clipboard":clipboard,"pasted":observed,"expected":state["project"]+"/"+f,"viewerLabels":[n.get("label") for n in viewer if n.get("label")]})
            tap("Navigate up","button")
            call("wait",'label="Add attachment"',20000)
            call("wait",700)
        tap(row,"button")
    finally:
        try:
            call("record","stop")
        except RuntimeError as error:
            if "ECONNRESET" not in str(error) and "unavailable" not in str(error): raise
            print("Recording export transport failed; retrying once after one minute",flush=True)
            time.sleep(60)
            try:
                call("record","stop")
            except RuntimeError as retry_error:
                if "no active recording" not in str(retry_error): raise
                print("EXPORT LOST: "+label+"; captures retained for a shorter recording pass",flush=True)
    (root/"outcomes.json").write_text(json.dumps(results,indent=2))
    print("CASE",label,results[-1].get("clipboard","no preview"),flush=True)
print("DONE",root,flush=True)
