import argparse, json, pathlib, subprocess, time, hashlib, sqlite3, urllib.request
p=argparse.ArgumentParser()
p.add_argument('--session', required=True); p.add_argument('--home', required=True); p.add_argument('--origin', required=True); p.add_argument('--out', required=True)
a=p.parse_args(); out=pathlib.Path(a.out); out.mkdir(parents=True,exist_ok=False)
log=open(out/'driver.log','w'); steps=[]
def run(*args):
    began=time.time(); r=subprocess.run(['agent-device',*args,'--session',a.session],capture_output=True,text=True)
    log.write(r.stdout+r.stderr); log.flush()
    steps.append({'command':list(args),'seconds':round(time.time()-began,2),'ok':r.returncode==0})
    (out/'steps.json').write_text(json.dumps(steps,indent=2))
    if r.returncode: raise RuntimeError(f'{args[0]} failed: {r.stderr}')
    return r.stdout

def capture(label):
    run('wait','stable','500','15000')
    last=None
    for i in range(5):
        file=out/f'{label}-{i}.png'
        try: run('screenshot',str(file))
        except RuntimeError:
            run('wait','stable','500','15000'); run('screenshot',str(file))
        digest=hashlib.sha256(file.read_bytes()).digest()
        if digest==last:
            print(f'Captured stable {label}: {file.name}',flush=True); return
        last=digest; time.sleep(.5)
    raise RuntimeError(f'{label} never produced two identical stills')

def link(path):
    run('open','com.t3tools.t3code.dev',f't3code-dev://{path}')

with urllib.request.urlopen(a.origin+'/.well-known/t3/environment') as r: env=json.load(r)['environmentId']
db=sqlite3.connect(f'file:{a.home}/userdata/statev2.sqlite?mode=ro',uri=True)
project=db.execute("SELECT project_id FROM projection_projects WHERE title='Link demo' AND deleted_at IS NULL").fetchone()[0]; db.close()
run('wait','text','Replay thread','60000')
run('record','start',str(out/'links.mp4'),'--hide-touches')
try:
    for path,title,background in [
        ('settings/about','About',False),
        ('settings/environment-new','Add environment',False),
        ('settings/appearance','Appearance',False),
        ('settings/usage?tab=limits','Usage',True),
        (f'new/draft/files?environmentId={env}&projectId={project}','Files',True),
    ]:
        run('wait','text','Replay thread','15000')
        if background: run('home')
        link(path); run('wait','text',title,'15000'); run('snapshot','-i')
        capture(path.split('?')[0].replace('/','-'))
        run('back','--in-app','--settle')
        if path.startswith('new/draft'):
            run('back','--in-app','--settle')
        else: run('press','id=workspace-tab-threads','--settle')
    link('settings/about'); run('wait','text','About','15000'); capture('about-before-link')
    link('settings'); run('snapshot','-i'); capture('bare-settings-link')
finally:
    run('record','stop')
print('Sequence completed',flush=True)
