#!/usr/bin/env python3
"""Create the synthetic managed-policy fixture. Run once for each fresh worktree."""
import json
import os
from pathlib import Path
import shlex
import shutil
import subprocess
import sys

checkout = Path(sys.argv[1]).resolve()
scratch = Path(sys.argv[2]).resolve()
real_codex = shutil.which('codex')
assert real_codex
scratch.mkdir(parents=True, exist_ok=True)
upper = scratch / 'upper'
work = scratch / 'work'
(upper / 'codex').mkdir(parents=True, exist_ok=True)
work.mkdir(exist_ok=True)
(upper / 'codex/requirements.toml').write_text(
    'allowed_approval_policies = ["untrusted", "on-request"]\n'
    'allowed_sandbox_modes = ["read-only", "workspace-write"]\n'
)
mount = 'mount -t overlay overlay -o ' + shlex.quote(
    f'lowerdir=/etc,upperdir={upper},workdir={work}'
) + ' /etc || exit; exec ' + shlex.quote(real_codex) + ' "$@"'
wrapper = scratch / 'codex-managed'
wrapper.write_text('#!/bin/sh\nexec unshare -Urnm sh -c ' + shlex.quote(mount) + ' sh "$@"\n')
wrapper.chmod(0o755)
state = checkout / '.t3/userdata'
state.mkdir(parents=True, exist_ok=True)
settings_file = state / 'settings.json'
settings = json.loads(settings_file.read_text()) if settings_file.exists() else {}
settings.setdefault('providers', {})['codex'] = {'binaryPath': str(wrapper)}
settings_file.write_text(json.dumps(settings))
demo = scratch / 'demo'
demo.mkdir(exist_ok=True)
subprocess.run(['git', 'init', '-q', str(demo)], check=True)
subprocess.run(['node', 'apps/server/src/bin.ts', 'project', 'add', '--base-dir',
                str(checkout / '.t3'), '--title', 'Managed policy demo', str(demo)],
               cwd=checkout, check=True)
