import json, pathlib, subprocess, sys
checkout, home = map(pathlib.Path, sys.argv[1:3])
project = home / 'workspaces' / 'nested-repository-demo'
project.mkdir(parents=True, exist_ok=True)
(project / '.gitignore').write_text('/backend/\n')
(project / 'README.md').write_text('Synthetic cleanup demonstration\n')
def git(cwd, *args):
    return subprocess.check_output(['git', *args], cwd=cwd, text=True).strip()
def cli(*args):
    return subprocess.check_output(['node', 'apps/server/src/bin.ts', *args, '--base-dir', str(home)], cwd=checkout, text=True).strip()
git(project, 'init', '--quiet', '--initial-branch=main')
git(project, 'add', '.')
git(project, '-c', 'user.name=Scenario', '-c', 'user.email=scenario@example.invalid', 'commit', '--quiet', '-m', 'Initial project')
cli('project', 'add', str(project), '--title', 'Nested repository demo')
thread = json.loads(cli('thread', 'start', str(project), 'Prepare the workspace', '--title', 'Keep precious backend files', '--provider', 'devReplay', '--model', 'multi-turn', '--worktree', 'main', '--branch', 'nested-backend-demo', '--wait', '--json'))
worktree = next(line[9:] for line in git(project, 'worktree', 'list', '--porcelain').splitlines() if line.startswith('worktree ') and line[9:] != str(project))
independent = home / 'independent-backend'
independent.mkdir()
(independent / 'README.md').write_text('Independent backend repository\n')
git(independent, 'init', '--quiet', '--initial-branch=main')
git(independent, 'add', '.')
git(independent, '-c', 'user.name=Scenario', '-c', 'user.email=scenario@example.invalid', 'commit', '--quiet', '-m', 'Initial backend')
backend = pathlib.Path(worktree) / 'backend'
git(independent, 'worktree', 'add', '--quiet', '-b', 'precious-backend', str(backend))
(backend / 'precious.txt').write_text('Precious uncommitted backend work\n')
assert git(worktree, 'status', '--porcelain') == ''
print(json.dumps({'threadId': thread['threadId'], 'worktree': worktree, 'precious': str(backend / 'precious.txt'), 'outerGitStatus': 'clean'}))
