#!/usr/bin/env python3
"""Drive a handoff through the real app CLI. Pass checkout and action as arguments."""
import datetime, json, pathlib, subprocess, sys
checkout = pathlib.Path(sys.argv[1]).resolve()
action = sys.argv[2]
home = checkout / '.t3'
state = home / 'evidence-driver.json'
def run(args, cwd=checkout):
    result = subprocess.run(args, cwd=cwd, text=True, capture_output=True)
    if result.returncode:
        print(result.stdout, file=sys.stderr)
        print(result.stderr, file=sys.stderr)
        result.check_returncode()
    return result.stdout.strip()
def cli(*args):
    return run(['node', 'apps/server/src/bin.ts', *args, '--base-dir', str(home)])
if action == 'seed':
    root = pathlib.Path(__file__).parent / datetime.datetime.now(datetime.timezone.utc).strftime('run-%Y%m%d-%H%M%S-%f')
    root.mkdir()
    origin = root / 'origin.git'
    workspace = root / 'handoff-demo'
    run(['git', 'init', '--bare', '--initial-branch=main', str(origin)])
    run(['git', 'clone', str(origin), str(workspace)])
    (workspace / 'README.md').write_text('# Handoff demonstration\nSynthetic evidence workspace.\n')
    run(['git', 'add', '.'], workspace)
    run(['git', '-c', 'user.name=Scenario', '-c', 'user.email=scenario@example.invalid', 'commit', '-m', 'Initial commit'], workspace)
    run(['git', 'push', 'origin', 'main'], workspace)
    cli('project', 'add', str(workspace), '--title', 'Handoff demonstration')
    launched = json.loads(cli('thread', 'start', str(workspace), 'Reply with Ready only.', '--title', 'Released-session handoff', '--wait', '--json'))
    state.write_text(json.dumps({'launch': launched, 'workspace': str(workspace)}))
    print(json.dumps(launched))
else:
    saved = json.loads(state.read_text())
    launch = saved['launch']
    thread_id = launch.get('threadId') or launch.get('thread', {}).get('id')
    if action == 'handoff':
        message = 'Call t3_worktree_handoff now with branch "handoff-demo-branch", startFromOrigin=true, runSetupScript=false, and continuationPrompt="Report your current directory, then say Continuation complete.". Call the handoff last in this turn.'
        print(cli('thread', 'send', thread_id, message, '--wait', '--json'))
    elif action == 'followup':
        print(cli('thread', 'send', thread_id, 'Reply with Ordinary turn complete only.', '--wait', '--json'))
    elif action == 'read':
        print(cli('thread', 'show', thread_id, '--json'))
