"""Create two isolated worktrees in a new scratch repository.
python worktrunk-probe.py /path/to/wt
The scratch directory is retained for inspection; no existing repo is touched.
"""
import json, pathlib, subprocess, sys, tempfile
wt = str(pathlib.Path(sys.argv[1]).resolve())
root = pathlib.Path(tempfile.mkdtemp(prefix='worktrunk-probe-')).resolve()
repo = root / 'main'
repo.mkdir()
config = root / 'config.toml'
config.write_text('worktree-path = "' + root.as_posix() + '/{{ branch }}"\n', encoding='utf-8')
def run(args, cwd=repo, check=True):
    p = subprocess.run(args, cwd=cwd, text=True, encoding='utf-8', capture_output=True)
    if check and p.returncode: raise RuntimeError(p.stdout + p.stderr)
    return p
run(['git', 'init', '-b', 'main'])
for key, value in [('user.name', 'Fixture'), ('user.email', 'fixture@example.invalid'),
                   ('core.hooksPath', (root / 'empty-hooks').as_posix())]:
    run(['git', 'config', '--local', key, value])
(repo / 'agent.txt').write_text('base\n', encoding='utf-8')
run(['git', 'add', 'agent.txt'])
run(['git', 'commit', '-m', 'Initial fixture'])
base = [wt, '--config', str(config)]
for branch in ['agent-a', 'agent-b']:
    run(base + ['switch', '--create', branch, '--base', 'main', '--no-cd', '--no-hooks', '--format', 'json'])
    assert (root / branch).resolve().is_relative_to(root)
    (root / branch / 'agent.txt').write_text(branch + '\n', encoding='utf-8')
assert (repo / 'agent.txt').read_text() == 'base\n'
assert (root / 'agent-a/agent.txt').read_text() == 'agent-a\n'
assert (root / 'agent-b/agent.txt').read_text() == 'agent-b\n'
run(['git', 'add', 'agent.txt'], root / 'agent-a')
assert run(['git', 'diff', '--cached', '--name-only'], root / 'agent-b').stdout.strip() == ''
assert run(['git', 'diff', '--cached', '--name-only'], root / 'agent-a').stdout.strip() == 'agent.txt'
run(['git', 'config', '--local', 'probe.shared', 'yes'], root / 'agent-a')
assert run(['git', 'config', '--local', 'probe.shared'], root / 'agent-b').stdout.strip() == 'yes'
refusal = run(base + ['remove', 'agent-a', '--foreground', '--no-hooks', '--format', 'json'], check=False)
assert refusal.returncode != 0
assert (root / 'agent-a/agent.txt').read_text() == 'agent-a\n'
print(json.dumps({'scratch': str(root), 'separate_file_contents': True,
 'separate_indexes': True, 'repository_config_shared': True,
 'dirty_remove_exit': refusal.returncode,
 'dirty_remove_stdout': refusal.stdout.strip(), 'dirty_remove_stderr': refusal.stderr.strip()}, indent=2))
