import sys,json,pathlib,subprocess
mode,checkout,run_dir=sys.argv[1:]
root=pathlib.Path(run_dir)
home=root/'home'
repo=root/'cache-check'

def call(args,cwd=checkout):
    return subprocess.run(args,cwd=cwd,text=True,capture_output=True,check=True).stdout

def cli(args):
    return call(['node','apps/server/src/bin.ts',*args,'--base-dir',str(home)])

if mode=='prepare':
    (home/'userdata').mkdir(parents=True)
    (home/'userdata'/'settings.json').write_text(json.dumps({'providerInstances':{'opencode':{'driver':'opencode','enabled':True,'config':{'binaryPath':'/usr/local/bin/opencode'}}},'defaultModelSelection':{'instanceId':'opencode','model':'openai/gpt-6-luna'}}))
    repo.mkdir()
    (repo/'README.md').write_text('# Cache check\nSynthetic preview reproduction.\n')
    call(['git','init','--quiet','--initial-branch=main'],str(repo))
    call(['git','add','README.md'],str(repo))
    call(['git','-c','user.name=Scenario','-c','user.email=scenario@example.invalid','commit','--quiet','-m','Initial commit'],str(repo))
    call(['git','remote','add','origin','https://github.com/rust-lang/rfcs.git'],str(repo))
    print('Prepared isolated synthetic state')
else:
    cli(['project','add',str(repo),'--title','cache-check'])
    markdown='Checked the cache first[^1] and it was stale.\n\n[^1]: Redis TTL is 60s.'
    prompt=markdown+'\n\nReply with exactly the Markdown above, without code fences or other text.'
    def start(title,message):
        return json.loads(cli(['thread','start',str(repo),message,'--title',title,'--provider','opencode','--model','openai/gpt-6-luna','--wait','--json']))['threadId']
    cache=start('Cache footnote',prompt)
    cli(['thread','send',cache,'Thanks, noted. Reply only Noted.','--wait','--json'])
    comment='https://github.com/rust-lang/rfcs/pull/3654#issuecomment-2151824935'
    pr=start('PR permalink footnote',f'This is preview test content. Do not open or change anything or call tools. Reply in this chat with only the word Noted.\n\nSee [the original comment]({comment}).')
    data={'cacheThreadId':cache,'prThreadId':pr,'commentUrl':comment,'markdown':markdown,'model':'OpenCode / GPT-6 Luna'}
    (root/'seed.json').write_text(json.dumps(data,indent=2))
    print(json.dumps(data))
