import os, sys, json, sqlite3, subprocess, pathlib, datetime
side = sys.argv[1]
root = pathlib.Path(os.environ['MAC_WORK'])
checkout = root / side
home = root / (side + '-data')
repo = root / (side + '-repo')
out = root / ('proof-' + side + '-' + datetime.datetime.now().strftime('%Y%m%dT%H%M%S'))
out.mkdir()
env = dict(os.environ)
for key in ['CLAUDECODE','CLAUDE_CODE_ENTRYPOINT','CLAUDE_CODE_SESSION_ID','CLAUDE_CODE_PARENT_SESSION_ID']:
    env.pop(key, None)
cli = ['node', 'apps/server/src/bin.ts']
def call(args, cwd=checkout):
    p = subprocess.run(args, cwd=cwd, env=env, capture_output=True, text=True, timeout=120)
    if p.returncode:
        raise RuntimeError(p.stderr)
    return json.loads(p.stdout)
first = call(cli + ['thread','start','--base-dir',str(home),'--provider','claudeAgent','--model','haiku','--title','Session continuation','--wait','--json',str(repo),'Remember the code word PELICAN. Reply with just OK.'])
first_time = datetime.datetime.now(datetime.timezone.utc)
thread = first['threadId']
db = sqlite3.connect('file:' + str(home / 'userdata/statev2.sqlite') + '?mode=ro', uri=True)
rows = db.execute('select payload_json from orchestration_v2_projection_provider_threads where thread_id=?', [thread]).fetchall()
provider_thread = json.loads(rows[-1][0])
session = provider_thread['nativeThreadRef']['nativeId']
if os.environ.get('PROOF_PAUSE'):
    gate = root / (side + '-go')
    os.mkfifo(gate)
    print(json.dumps(dict(threadId=thread, ready=True)), flush=True)
    with gate.open() as f: f.read()
terminal = call(['claude','-p','--model','haiku','--output-format','json','--resume',session,'The second code word is OTTER. Reply with just OK.'], cwd=repo)
last_time = datetime.datetime.now(datetime.timezone.utc)
last = call(cli + ['thread','send','--base-dir',str(home),'--wait','--json',thread,'List every code word so far, nothing else.'])
transcript_file = next((pathlib.Path.home()/'.claude/projects').rglob(session+'.jsonl'))
messages = []
for line in transcript_file.read_text().splitlines():
    row = json.loads(line)
    if row.get('type') not in ['user','assistant']: continue
    content = row.get('message',{}).get('content')
    text = content if isinstance(content,str) else '\n'.join(x.get('text','') for x in content or [] if x.get('type')=='text')
    messages.append(dict(type=row['type'],uuid=row.get('uuid'),parentUuid=row.get('parentUuid'),text=text))
proof = dict(side=side,commit=subprocess.check_output(['git','rev-parse','HEAD'],cwd=checkout,text=True).strip(),environment='macOS 26 Apple silicon; Claude Code 2.1.322; Haiku; real T3 development server; fresh data; empty git repository',first=first,terminal=dict(result=terminal.get('result'),session_id=session),last=last,firstReplyAt=first_time.isoformat(),finalPromptAt=last_time.isoformat(),secondsUntilFinalPrompt=(last_time-first_time).total_seconds(),providerThread=dict(nativeConversationHeadRef=provider_thread.get('nativeConversationHeadRef'),pendingBackgroundTasks=provider_thread.get('pendingBackgroundTasks')),messages=messages)
(out/'transcript.json').write_text(json.dumps(proof,indent=2))
(root/(side+'-proof-location')).write_text(str(out))
print(json.dumps(proof,indent=2),flush=True)
