# SPDX-License-Identifier: AGPL-3.0-or-later
#
# Bypass tests for scripts/check-scope. Every case here is a shape the gate must refuse: an
# enforcement without a bypass test is an enforcement that is never actually enforced.
#
# Each case builds a scratch git repository, because the gate reads real history with
# `git diff --no-renames` and a synthetic file list would not exercise the rename path.

import os
import shutil
import subprocess
import tempfile
from pathlib import Path

import pytest

REPO_ROOT = Path(__file__).resolve().parents[1]
SCRIPT = REPO_ROOT / "scripts" / "check-scope"

BASE = """\
SUBJECT: scope test
IN SCOPE: {scope}
OUT OF SCOPE: {out_of_scope}
ACCEPTANCE: rc 0
"""


def _git(*args: str, cwd: Path) -> str:
    return subprocess.run(
        ("git", *args), cwd=cwd, check=True, capture_output=True, text=True
    ).stdout.strip()


@pytest.fixture
def sandbox(tmp_path, monkeypatch):
    """A scratch repository with one commit, plus a working tree to commit as the step."""
    repo = tmp_path / "repo"
    repo.mkdir()
    _git("init", "-q", "-b", "main", cwd=repo)
    _git("config", "user.email", "t@t", cwd=repo)
    _git("config", "user.name", "t", cwd=repo)
    (repo / "seed.txt").write_text("seed\n")
    _git("add", "-A", cwd=repo)
    _git("commit", "-qm", "seed", cwd=repo)
    base = _git("rev-parse", "HEAD", cwd=repo)

    monkeypatch.setattr("shutil.which", lambda name: None, raising=False)
    monkeypatch.chdir(repo)
    yield repo, base
    shutil.rmtree(repo, ignore_errors=True)


def _run(repo: Path, base: str, brief: Path) -> subprocess.CompletedProcess:
    return subprocess.run(
        ("bash", str(SCRIPT), base, "HEAD", str(brief)),
        cwd=repo,
        capture_output=True,
        text=True,
    )


def _commit(repo: Path, message: str = "step") -> None:
    _git("add", "-A", cwd=repo)
    _git("commit", "-qm", message, cwd=repo)


def _brief(repo: Path, scope: str, out_of_scope: str = "none", name: str = "brief.md") -> Path:
    path = repo / name
    path.write_text(BASE.format(scope=scope, out_of_scope=out_of_scope))
    return path


def test_in_scope_change_passes(sandbox):
    repo, base = sandbox
    (repo / "src").mkdir()
    (repo / "src" / "a.py").write_text("a\n")
    _commit(repo)
    result = _run(repo, base, _brief(repo, "src/a.py"))
    assert result.returncode == 0, result.stderr


def test_out_of_scope_change_fails(sandbox):
    """The regression this test exists for: OUT OF SCOPE: was read as more IN SCOPE, because the
    header pattern `^[A-Z]+:` cannot match a multi-word header."""
    repo, base = sandbox
    (repo / "src").mkdir()
    (repo / "src" / "a.py").write_text("a\n")
    (repo / "src" / "c.py").write_text("c\n")
    _commit(repo)
    result = _run(repo, base, _brief(repo, "src/a.py", out_of_scope="src/c.py"))
    assert result.returncode == 1
    assert "src/c.py" in result.stderr


def test_out_of_scope_failure_with_multiline_in_scope(sandbox):
    repo, base = sandbox
    (repo / "src").mkdir()
    (repo / "src" / "a.py").write_text("a\n")
    (repo / "src" / "c.py").write_text("c\n")
    _commit(repo)
    brief = repo / "brief.md"
    brief.write_text(
        "SUBJECT: t\nIN SCOPE: src/a.py\n  docs/method.md\nOUT OF SCOPE: src/c.py\nACCEPTANCE: rc 0\n"
    )
    result = _run(repo, base, brief)
    assert result.returncode == 1
    assert "src/c.py" in result.stderr


def test_report_under_docs_research_needs_no_claim(sandbox):
    repo, base = sandbox
    (repo / "docs" / "research").mkdir(parents=True)
    (repo / "docs" / "research" / "x-report.md").write_text("r\n")
    _commit(repo)
    result = _run(repo, base, _brief(repo, "src/a.py"))
    assert result.returncode == 0, result.stderr


def test_rename_onto_in_scope_name_fails(sandbox):
    """`git diff --name-only` collapses a rename to its new name; --no-renames is what catches the
    deletion, and without it a file can be replaced by a rename that the brief never claimed."""
    repo, base = sandbox
    (repo / "secret.py").write_text("s\n")
    _commit(repo, "add secret")
    head = _git("rev-parse", "HEAD", cwd=repo)
    (repo / "secret.py").unlink()
    (repo / "src.py").write_text("s\n")
    _commit(repo, "rename onto src.py")
    result = _run(repo, head, _brief(repo, "src.py"))
    assert result.returncode == 1
    assert "secret.py" in result.stderr


def _arm_store(repo: Path, row: str) -> None:
    """Write the store in the real file's layout, shape table included: the gate selects rows by
    state rather than by position, and the tests must cover the layout it will actually read."""
    store = repo / "docs" / "residuals.md"
    store.parent.mkdir(parents=True, exist_ok=True)
    store.write_text(
        "# Residuals\n\n"
        "Accepted and rejected risk. Maintained by the PLANNER.\n\n"
        "## Entry shape\n\n"
        "| Column | Content |\n"
        "| --- | --- |\n"
        "| `ID` | short stable key |\n"
        "| `State` | `accepted` or `rejected` |\n"
        "| `Trigger` | one or more **globs over paths** |\n"
        "| `Risk` | what was left unfixed |\n"
        "\n## Entries\n\n"
        "| ID | State | Trigger | Risk | Rationale | Evidence |\n"
        "| --- | --- | --- | --- | --- | --- |\n" + row + "\n"
    )


def test_backticked_state_still_arms(sandbox):
    """The state column is documented with backticks, so a check that only matches unbackticked
    states is disabled by its own documentation."""
    repo, base = sandbox
    (repo / "risky.py").write_text("r\n")
    _commit(repo)
    _arm_store(repo, "| `R1` | `accepted` | `risky.py` | risk | why | ev |")
    result = _run(repo, base, _brief(repo, "risky.py"))
    assert result.returncode == 1
    assert "R1" in result.stderr


def test_carrying_the_residual_passes(sandbox):
    repo, base = sandbox
    (repo / "risky.py").write_text("r\n")
    _commit(repo)
    _arm_store(repo, "| `R1` | `accepted` | `risky.py` | risk | why | ev |")
    brief = repo / "brief.md"
    brief.write_text(
        "SUBJECT: t\nINHERITED:\nR1 risk\nIN SCOPE: risky.py\nACCEPTANCE: rc 0\n"
    )
    result = _run(repo, base, brief)
    assert result.returncode == 0, result.stderr


def test_tripped_line_names_the_matched_residuals(sandbox):
    """Two actors mis-voted the tripped set by hand in one round, in opposite directions. The gate
    computes it, prints it, and reports copy the line."""
    repo, base = sandbox
    (repo / "risky.py").write_text("r\n")
    _commit(repo)
    _arm_store(
        repo,
        "| `R1` | `accepted` | `risky.py` | risk | why | ev |\n"
        "| `R2` | `accepted` | other.py | risk | why | ev |\n"
        "| `R3` | `accepted` | `risky.py` | risk | why | ev |",
    )
    brief = repo / "brief.md"
    brief.write_text(
        "SUBJECT: t\nRESIDUALS:\nR1 risk\nR3 risk\nIN SCOPE: risky.py\nACCEPTANCE: rc 0\n"
    )
    result = _run(repo, base, brief)
    assert result.returncode == 0, result.stderr
    assert "tripped: R1 R3" in result.stdout


def test_tripped_line_reads_none_when_nothing_matches(sandbox):
    repo, base = sandbox
    (repo / "risky.py").write_text("r\n")
    _commit(repo)
    _arm_store(repo, "| `R1` | `accepted` | other.py | risk | why | ev |")
    result = _run(repo, base, _brief(repo, "risky.py"))
    assert result.returncode == 0, result.stderr
    assert "tripped: none" in result.stdout


def test_tripped_line_lists_an_id_once_when_several_paths_match(sandbox):
    """A row whose trigger named two changed paths listed its id twice: the dedupe matched whole
    lines, so a space-joined accumulator never matched. The list is a set."""
    repo, base = sandbox
    (repo / "a.py").write_text("a\n")
    (repo / "b.py").write_text("b\n")
    _commit(repo)
    _arm_store(repo, "| `R1` | `accepted` | a.py b.py | risk | why | ev |")
    brief = repo / "brief.md"
    brief.write_text(
        "SUBJECT: t\nRESIDUALS:\nR1 risk\nIN SCOPE: a.py b.py\nACCEPTANCE: rc 0\n"
    )
    result = _run(repo, base, brief)
    assert result.returncode == 0, result.stderr
    assert "tripped: R1\n" in result.stdout


def test_backticked_paths_are_stripped_from_claims(sandbox):
    """A markdown-natural `path` in IN SCOPE claimed the literal backticked token and matched
    nothing: the gate failed naming the brief's own intended files (FFR-1). The claimed: line is
    what the gate matched against, so the set is visible in every report."""
    repo, base = sandbox
    (repo / "risky.py").write_text("r\n")
    _commit(repo)
    brief = repo / "brief.md"
    brief.write_text("SUBJECT: t\nIN SCOPE: `risky.py`\nACCEPTANCE: rc 0\n")
    result = _run(repo, base, brief)
    assert result.returncode == 0, result.stderr
    assert "claimed: risky.py" in result.stdout


def test_claimed_line_prints_every_parsed_pattern(sandbox):
    repo, base = sandbox
    (repo / "a.py").write_text("a\n")
    (repo / "b.py").write_text("b\n")
    _commit(repo)
    result = _run(repo, base, _brief(repo, "a.py, b.py"))
    assert result.returncode == 0, result.stderr
    assert "claimed: a.py b.py" in result.stdout


def test_two_glob_trigger_matches_either(sandbox):
    repo, base = sandbox
    (repo / "b.py").write_text("b\n")
    _commit(repo)
    _arm_store(repo, "| R2 | accepted | a.py b.py | risk | why | ev |")
    result = _run(repo, base, _brief(repo, "b.py"))
    assert result.returncode == 1
    assert "R2" in result.stderr


def test_id_match_is_not_a_substring(sandbox):
    """`grep -qF R1` is satisfied by R10, so mentioning one residual satisfied every other."""
    repo, base = sandbox
    (repo / "risky.py").write_text("r\n")
    _commit(repo)
    _arm_store(repo, "| R1 | accepted | risky.py | risk | why | ev |")
    brief = repo / "brief.md"
    brief.write_text(
        "SUBJECT: t\nINHERITED:\nR10 unrelated\nIN SCOPE: risky.py\nACCEPTANCE: rc 0\n"
    )
    result = _run(repo, base, brief)
    assert result.returncode == 1
    assert "R1" in result.stderr


def test_unarmed_store_is_silent(sandbox):
    repo, base = sandbox
    (repo / "risky.py").write_text("r\n")
    _commit(repo)
    _arm_store(repo, "| R1 | proposed | risky.py | risk | why | ev |")
    result = _run(repo, base, _brief(repo, "risky.py"))
    assert result.returncode == 0, result.stderr


def test_missing_brief_is_a_usage_error(sandbox):
    repo, base = sandbox
    (repo / "a.py").write_text("a\n")
    _commit(repo)
    result = _run(repo, base, repo / "nope.md")
    assert result.returncode == 2


def test_existing_doc_under_research_must_be_claimed(sandbox):
    """The exemption is for reports a step *adds*. Rewriting a document already in the tree is a
    change the brief has to claim, or the research corpus can be edited without ever appearing in
    a scope diff."""
    repo, base = sandbox
    existing = repo / "docs" / "research"
    existing.mkdir(parents=True)
    (existing / "old-report.md").write_text("original\n")
    _commit(repo, "add old report")
    head = _git("rev-parse", "HEAD", cwd=repo)
    (existing / "old-report.md").write_text("rewritten\n")
    _commit(repo, "rewrite it")
    result = _run(repo, head, _brief(repo, "docs/method.md"))
    assert result.returncode == 1
    assert "old-report.md" in result.stderr


def test_comma_separated_triggers_each_match(sandbox):
    repo, base = sandbox
    (repo / "z.py").write_text("z\n")
    _commit(repo)
    _arm_store(repo, "| R1 | accepted | src/a.py, z.py | risk | why | ev |")
    result = _run(repo, base, _brief(repo, "z.py"))
    assert result.returncode == 1
    assert "R1" in result.stderr


def test_glob_trigger_is_matched_as_written(sandbox):
    """An unquoted expansion lets bash glob the pattern against the working tree, so `src/*.py`
    silently becomes whichever checked-out file matched. The result then depends on the checkout."""
    repo, base = sandbox
    (repo / "src").mkdir()
    (repo / "src" / "old.py").write_text("o\n")
    _commit(repo)
    (repo / "src" / "new.py").write_text("n\n")
    _commit(repo)
    _arm_store(repo, "| R1 | accepted | src/*.py | risk | why | ev |")
    result = _run(repo, base, _brief(repo, "src/new.py"))
    assert result.returncode == 1, result.stderr
    assert "src/*.py" in result.stderr


def test_run_from_a_subdirectory_still_finds_the_store(sandbox):
    repo, base = sandbox
    (repo / "risky.py").write_text("r\n")
    _commit(repo)
    _arm_store(repo, "| R1 | accepted | risky.py | risk | why | ev |")
    nested = repo / "deep" / "er"
    nested.mkdir(parents=True)
    brief = repo / "brief.md"
    brief.write_text("SUBJECT: t\nIN SCOPE: risky.py\nACCEPTANCE: rc 0\n")
    result = subprocess.run(
        ("bash", str(SCRIPT), base, "HEAD", "brief.md"),
        cwd=nested,
        capture_output=True,
        text=True,
        env={**os.environ, "GIT_DISCOVERY_ACROSS_FILESYSTEM": "1"},
    )
    assert result.returncode == 1, result.stderr
    assert "R1" in result.stderr
