import pathlib, subprocess, sys, datetime, json
checkout=pathlib.Path(sys.argv[1]).resolve()
side=sys.argv[2]
run=pathlib.Path(__file__).parent/(side+'-'+datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%S'))
run.mkdir()
workspace=run/'workspace'
site=workspace/'site'
site.mkdir(parents=True)
log=[]
def command(args,cwd=checkout):
    p=subprocess.run(args,cwd=cwd,text=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
    output=p.stdout.replace(str(checkout),'CHECKOUT').replace(str(run),'FIXTURE')
    log.append('$ '+ ' '.join(str(x).replace(str(checkout),'CHECKOUT').replace(str(run),'FIXTURE') for x in args)+'\n'+output+'\n(exit '+str(p.returncode)+')\n')
    (run/'transcript.txt').write_text('\n'.join(log))
    print(output,flush=True)
    return p
command(['git','init','--initial-branch=main'],site)
(site/'README.md').write_text('Synthetic repository for nested repository selection proof.\n')
command(['git','add','.'],site)
command(['git','-c','user.name=Proof','-c','user.email=proof@example.invalid','commit','-m','Initial commit'],site)
command(['git','remote','add','origin','https://github.com/acme/site.git'],site)
command(['git','checkout','-b','feature/x'],site)
(site/'change.txt').write_text('Test change\n')
command(['git','add','.'],site)
command(['git','-c','user.name=Proof','-c','user.email=proof@example.invalid','commit','-m','Test change'],site)
cli=['node','apps/server/src/bin.ts']
command(cli+['project','add',str(workspace),'--base-dir',str(checkout/'.t3')])
prompt="Call the T3 MCP tool pull_request_create exactly once with title 'Test change' and body 'Testing'. Do not run shell commands, edit files, retry, or call any other tool. After it returns, quote the tool's complete raw result verbatim, including its error detail and reason, then stop."
p=command(cli+['thread','start','--provider','pi','--model','anthropic/claude-haiku-5-5','--wait','--json','--title','Nested repository PR proof','--base-dir',str(checkout/'.t3'),str(workspace),prompt])
(run/'launch.json').write_text(p.stdout)
print('RUN_DIRECTORY='+str(run))
