#!/usr/bin/env python3
import json
from pathlib import Path
import subprocess
import tempfile


def inside(root, candidate):
    root = root.resolve()
    candidate = candidate.resolve()
    return candidate == root or root in candidate.parents


with tempfile.TemporaryDirectory(prefix="agent-sandbox-") as tmp:
    root = Path(tmp)
    allowed_file = root / "result.txt"
    blocked_file = Path("/etc/passwd")

    execution = subprocess.run(
        ["python3", "-c", "from pathlib import Path; Path('result.txt').write_text('ok')"],
        cwd=root,
        capture_output=True,
        text=True,
        timeout=5,
    )

    result = {
        "sandbox_root": "temporary_directory",
        "allowed_write": {"path": "result.txt", "inside": inside(root, allowed_file), "content": allowed_file.read_text()},
        "blocked_read": {"path": "/etc/passwd", "inside": inside(root, blocked_file), "decision": "deny"},
        "execution": {"returncode": execution.returncode, "stderr": execution.stderr},
    }

Path(__file__).with_name("experiment-result.json").write_text(
    json.dumps(result, ensure_ascii=False, indent=2) + "\n", encoding="utf-8"
)
print(json.dumps(result, ensure_ascii=False, indent=2))
