"""REC-25: the pre-merge gate must
  (a) pass when tests exist and pass,
  (b) BLOCK when 0 tests are collected (the phantom-green hole it exists to close),
  (c) BLOCK when a test fails.
Uses BASE=HEAD (→ no changed files → ruff/py_compile skip) and tmp test dirs so the
test exercises the gate's own logic, not the real suite.
"""
import subprocess
from pathlib import Path

GATE = Path(__file__).resolve().parents[1] / "pre_merge_gate.sh"


def _run(*test_paths):
    return subprocess.run(
        ["bash", str(GATE), "HEAD", *test_paths],
        capture_output=True,
        text=True,
    )


def test_gate_green_when_tests_exist_and_pass(tmp_path):
    (tmp_path / "test_ok.py").write_text("def test_a():\n    assert True\n")
    r = _run(str(tmp_path))
    assert r.returncode == 0, r.stdout + r.stderr
    assert "PRE-MERGE GATE GREEN" in r.stdout


def test_gate_blocks_on_zero_collected_phantom_green(tmp_path):
    empty = tmp_path / "empty"
    empty.mkdir()
    r = _run(str(empty))
    assert r.returncode == 1, r.stdout + r.stderr
    assert "MIN-TEST-COUNT FAILED" in r.stdout


def test_gate_blocks_on_failing_test(tmp_path):
    (tmp_path / "test_fail.py").write_text("def test_a():\n    assert False\n")
    r = _run(str(tmp_path))
    assert r.returncode == 1, r.stdout + r.stderr
    assert "PYTEST FAILED" in r.stdout


def test_gate_blocks_when_no_diff_base_resolvable(tmp_path):
    """Codex review (PR #11): a base that can't resolve must BLOCK, not skip the
    diff gates and go green. Isolated in a fresh single-commit repo so HEAD~1 is
    also unavailable (the shallow/first-commit case)."""
    repo = tmp_path / "repo"
    repo.mkdir()

    def git(*a):
        subprocess.run(["git", *a], cwd=repo, check=True, capture_output=True)

    git("init", "-q")
    git("config", "user.email", "x@example.com")
    git("config", "user.name", "x")
    (repo / "f.py").write_text("x = 1\n")
    git("add", ".")
    git("commit", "-qm", "first")

    r = subprocess.run(
        ["bash", str(GATE), "no-such-base", "."],
        cwd=repo, capture_output=True, text=True,
    )
    assert r.returncode != 0, r.stdout + r.stderr
    assert "cannot resolve a diff base" in r.stdout
