#!/usr/bin/env python3
"""Driver for the real-app Unicode CI-log comparison.
Prerequisites: authenticated glab, vp i in both checkouts, fresh dev servers
started with T3CODE_DEV_SEED=0. No provider/forge mocks are used.

Seed once: python3 reproduce.py seed OUTPUT_DIR UNIQUE_PROJECT_NAME
Run on each checkout: python3 reproduce.py run CHECKOUT CLONE_DIR OUTPUT_DIR
Inspect with verify-ci-output.py CHECKOUT THREAD_ID REPORT_JSON.
Open the resulting thread in the paired web app and expand 'Worked for'.
"""
import datetime
import json
from pathlib import Path
import subprocess
import sys

def run(args, cwd=None):
    return subprocess.check_output(args, cwd=cwd, text=True)

def api(args):
    return json.loads(run(['glab', 'api', *args]))

if sys.argv[1] == 'seed':
    out = Path(sys.argv[2]).resolve() / datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%SZ')
    out.mkdir(parents=True)
    project = api(['-X','POST','projects','-f',f'name={sys.argv[3]}','-f','visibility=private','-f','initialize_with_readme=true'])
    project_id = project['id']
    api(['-X','POST',f'projects/{project_id}/repository/branches','-f','branch=ci-tail','-f','ref=main'])
    ci = 'default:\n  image: python:3.12-alpine\n'
    for letter in 'abcd':
        suffix = "+'y'" if letter in 'bd' else ''
        ci += f'rockets-{letter}:\n  script:\n    - python -c "print(chr(0x1f680)*20000{suffix})"\n    - exit 1\n'
    api(['-X','POST',f'projects/{project_id}/repository/files/.gitlab-ci.yml','-f','branch=ci-tail','-f','commit_message=Synthetic Unicode CI log','-f',f'content={ci}'])
    api(['-X','POST',f'projects/{project_id}/merge_requests','-f','source_branch=ci-tail','-f','target_branch=main','-f','title=Unicode CI log clipping'])
    run(['git','clone','--branch','ci-tail',project['http_url_to_repo'],str(out/'unicode-ci')])
    (out/'seed.json').write_text(json.dumps({'projectId':project_id,'clone':str(out/'unicode-ci')}))
    print('Wait until all four jobs fail; use the same completed pipeline on both commits.')
    print('Delete the synthetic project after evidence capture with glab api -X DELETE projects/PROJECT_ID.')
elif sys.argv[1] == 'run':
    checkout, clone, output = map(lambda p:Path(p).resolve(), sys.argv[2:5])
    output.mkdir(parents=True, exist_ok=True)
    cli = ['node','apps/server/src/bin.ts']
    run([*cli,'project','add',str(clone),'--title','Unicode CI proof','--base-dir','.t3'],cwd=checkout)
    prompt = 'Call ci_logs for merge request 1 with check "test / rockets-d" and tailLines 200. Do not run any shell commands. Reply concisely with truncated, whether the log starts with an unpaired low surrogate, and the first 3 UTF-16 code units of log as literal backslash-u escapes. Do not reproduce the full log.'
    result=run([*cli,'thread','start',str(clone),prompt,'--title','Unicode CI log — rockets-d','--provider','claudeAgent','--model','claude-haiku-5-5','--base-dir','.t3','--json'],cwd=checkout)
    (output/'thread.json').write_text(result)
    print(result)
    print('Wait for the real agent turn to complete before running the read-only verifier.')
else:
    raise SystemExit('Expected seed or run')
