#!/usr/bin/env python3
"""Real Antigravity Stop-hook reproduction. No simulated provider responses.

Start each checkout with T3CODE_DEV_SEED=0 and GOOGLE_GEMINI_BASE_URL set to
an available Gemini API endpoint. In Settings > Providers, add Antigravity,
choose Gemini API key, enter the endpoint's key, and Connect.
Run this script once per checkout, using the same --workspace on both sides.
Open the resulting thread in the web client, wait for completion, and toggle
Worked for. For the control, add --no-hook and use a separate workspace.
"""
import argparse, json, pathlib, subprocess, datetime

PROMPT = 'Rewrite this prompt so it is clearer and more detailed: "Make a CLI that backs up a photos folder nightly." Include scheduling, safe handling of existing files, logging, and error handling. Keep your rewritten prompt under 120 words. Reply with only the rewritten prompt. Do not use any tools.'
REASON = 'Before ending, verify your rewritten prompt is complete and covers error handling. Think carefully through each requirement. Do not repeat or rewrite the prompt. If it is complete, reply with only: The rewritten prompt above is complete.'
HOOK = '''import json,sys,pathlib
v=json.load(sys.stdin)
p=pathlib.Path(__file__).parent
c=v.get("conversationId","unknown")
m=p/("stop-"+c)
first=not m.exists()
m.touch()
with (p/"hook-log.jsonl").open("a") as f: f.write(json.dumps({"conversationId":c,"first":first,"continuationActive":v.get("continuationActive")})+"\\n")
print(json.dumps({"decision":"continue","reason":REASON} if first else {}))
'''

def main():
    a=argparse.ArgumentParser(description=__doc__)
    a.add_argument('--checkout',required=True,type=pathlib.Path)
    a.add_argument('--workspace',required=True,type=pathlib.Path)
    a.add_argument('--base-dir',default='.t3')
    a.add_argument('--output',required=True,type=pathlib.Path)
    a.add_argument('--no-hook',action='store_true')
    args=a.parse_args()
    p=args.workspace.resolve();p.mkdir(parents=True,exist_ok=True)
    subprocess.run(['git','init','-q',str(p)],check=True)
    if not args.no_hook:
        (p/'.agents').mkdir(exist_ok=True)
        (p/'stop.py').write_text(HOOK.replace('REASON',repr(REASON)))
        (p/'.agents/hooks.json').write_text(json.dumps({'verify-prompt':{'Stop':[{'type':'command','command':'python3 '+str(p/'stop.py')}] }},indent=2))
    elif (p/'.agents/hooks.json').exists():
        raise SystemExit('Use a fresh workspace without hooks for the control.')
    title='Normal turn without hook' if args.no_hook else 'Stop-hook continuation'
    cli=['node','apps/server/src/bin.ts']
    subprocess.run(cli+['project','add','--base-dir',args.base_dir,'--title',title,str(p)],cwd=args.checkout,check=True)
    result=subprocess.run(cli+['thread','start','--base-dir',args.base_dir,'--provider','antigravity','--model','gemini-4-neon','--title',title,'--wait','--json',str(p),'-'],input=PROMPT,text=True,capture_output=True,cwd=args.checkout)
    run=args.output/datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%S%fZ')
    run.mkdir(parents=True)
    (run/'result.json').write_text(result.stdout)
    (run/'stderr.txt').write_text(result.stderr)
    print(result.stdout)
    raise SystemExit(result.returncode)

if __name__=='__main__': main()
