import pathlib,json,time,sys,datetime,sqlite3
from fixture import api
from measure import extract
root=pathlib.Path(__file__).parent
fixture=json.loads((root/'fixture-private.json').read_text())
start=1794684604.0
checkouts=dict(zip(['head','base'],sys.argv[1:]))
run=root/('run-'+datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%SZ'))
run.mkdir()
merged={s:{'sweeps':{},'linkSyncCalls':{}} for s in checkouts}
events=[]; done=set(); observed=set()
def event(kind, **kwargs):
    record={'event':kind,'at':time.time(),'secondsFromWatch':round(time.time()-start,3),**kwargs};events.append(record)
    (run/'events.json').write_text(json.dumps(events,indent=2));print(json.dumps(record),flush=True)
event('monitor-start',watchStartedAt=start)
while time.time()<start+47*60:
    elapsed=time.time()-start
    if elapsed>=20*60 and 'success' not in done:
        api(f"projects/{fixture['id']}/statuses/{fixture['sha']}",{'state':'success','name':'ext-ci','ref':'feature'})
        done.add('success');event('external-status-success')
    if elapsed>=23*60 and 'comment' not in done:
        api(f"projects/{fixture['id']}/merge_requests/1/notes",{'body':'Synthetic proof: please review the updated check.'})
        done.add('comment');event('viewer-comment-posted')
    if elapsed>=37*60 and 'push' not in done:
        import subprocess
        p=subprocess.run(['glab','api',f"projects/{fixture['id']}/repository/files/proof.txt",'-X','PUT','-f','branch=feature','-f','content=synthetic outside update','-f','commit_message=Outside update for watch proof'],capture_output=True,text=True)
        if p.returncode:raise RuntimeError(p.stderr)
        branch=api(f"projects/{fixture['id']}/repository/branches/feature")
        done.add('push');event('outside-push',headSha=branch['commit']['id'])
    for side,checkout in checkouts.items():
        con=sqlite3.connect('file:'+str(pathlib.Path(checkout)/'.t3/userdata/statev2.sqlite')+'?mode=ro',uri=True)
        rows=con.execute("SELECT sequence,event_type,occurred_at,payload_json FROM orchestration_events WHERE event_type LIKE 'thread.pull-request%'").fetchall()
        con.close()
        for seq,kind,at,payload in rows:
            if (side,seq) in observed:continue
            observed.add((side,seq));p=json.loads(payload)
            links=p.get('pullRequests',[p])
            for link in links:
                w=link.get('watch')
                if w is not None:
                    event('watch-state',side=side,persistedAt=at,state={k:w.get(k) for k in ['headSha','checksPending','passed','remarksThrough','wakes','failedChecks','passedChecks']})
        data=extract(checkout)
        for s in data['sweeps']:
            if s['start']>=start:merged[side]['sweeps'][s['start']]=s
        for c in data['linkSyncCalls']:
            if c['start']>=start:merged[side]['linkSyncCalls'][c['start']]=c
    output={side:{k:sorted(v.values(),key=lambda x:x['start']) for k,v in data.items()} for side,data in merged.items()}
    (run/'measurements.json').write_text(json.dumps(output,indent=2))
    time.sleep(10)
event('monitor-finished')
print(str(run),flush=True)
