"""Opt-in integration test for the sandbox enforcement.

Spawns the run_tier2_sandboxed.ps1 wrapper, then inside the sandboxed
session attempts each banned operation. Verifies each is denied at one
of the 3 layers (OpenCode permission system, Windows ACL, git hooks).
"""
import os
import subprocess
import sys
from pathlib import Path

import pytest

pytestmark = [
 pytest.mark.skipif(
  not os.environ.get("TIER2_SANDBOX_TESTS"),
  reason="opt-in: sandbox enforcement test off by default; set TIER2_SANDBOX_TESTS=1",
 ),
 pytest.mark.skipif(
  sys.platform != "win32",
  reason="sandbox enforcement is Windows-specific (uses Windows restricted tokens)",
 ),
 pytest.mark.tier2_sandbox,
]


def test_pre_push_hook_refuses_push(tmp_path: Path) -> None:
 """The pre-push hook in the Tier 2 clone refuses all pushes."""
 origin = tmp_path / "origin.git"
 origin.mkdir()
 subprocess.run(["git", "init", "--bare"], cwd=str(origin), check=True, capture_output=True)
 fake_clone = tmp_path / "fake_clone"
 fake_clone.mkdir()
 fake_clone_str = str(fake_clone)
 subprocess.run(["git", "init"], cwd=fake_clone_str, check=True, capture_output=True)
 subprocess.run(["git", "config", "user.email", "test@test"], cwd=fake_clone_str, check=True)
 subprocess.run(["git", "config", "user.name", "Test"], cwd=fake_clone_str, check=True)
 subprocess.run(["git", "remote", "add", "origin", str(origin)], cwd=fake_clone_str, check=True)
 (fake_clone / "README.md").write_text("test\n")
 subprocess.run(["git", "add", "README.md"], cwd=fake_clone_str, check=True)
 subprocess.run(["git", "commit", "-m", "init"], cwd=fake_clone_str, check=True)
 default_branch = subprocess.run(
  ["git", "symbolic-ref", "--short", "HEAD"],
  cwd=fake_clone_str, capture_output=True, text=True, check=True,
 ).stdout.strip()
 hooks_dir = fake_clone / ".git" / "hooks"
 real_hook = Path("conductor/tier2/githooks/pre-push").resolve()
 (hooks_dir / "pre-push").write_bytes(real_hook.read_bytes())
 result = subprocess.run(
  ["git", "push", "origin", default_branch],
  cwd=fake_clone_str, capture_output=True, text=True,
 )
 assert result.returncode != 0, f"push unexpectedly succeeded: {result.stdout} {result.stderr}"
 assert "git push" in result.stderr.lower() or "disabled" in result.stderr.lower()
