"""Doc-contract checks for the bootstrap review path (#557).

Self-hosted MCP workflow fixes can deadlock live review daemons. These tests
pin the narrow controller-authorized bootstrap path so it cannot silently
regress into a general gate bypass.
"""

from pathlib import Path

REPO_ROOT = Path(__file__).resolve().parent.parent

DOC = REPO_ROOT / "docs" / "bootstrap-review-path.md"
RUNBOOK = REPO_ROOT / "docs" / "llm-workflow-runbooks.md"
SKILL = REPO_ROOT / "skills" / "llm-project-workflow" / "SKILL.md"


def _normalize(text: str) -> str:
    return " ".join(text.split())


def test_bootstrap_doc_exists_and_names_authorization_marker():
    text = DOC.read_text(encoding="utf-8")
    assert "BOOTSTRAP REVIEW AUTHORIZATION (#557)" in text
    assert "bootstrap deadlock" in text.lower() or "Bootstrap deadlock" in text


def test_bootstrap_doc_requires_validation_and_audits():
    text = _normalize(DOC.read_text(encoding="utf-8"))
    for phrase in (
        "git diff --check",
        "Duplicate-PR audit",
        "Mutation ledger audit",
        "Contamination audit",
        "workflow-contaminated",
    ):
        assert phrase in text, f"bootstrap doc missing: {phrase!r}"


def test_bootstrap_doc_lists_allowed_and_forbidden_actions():
    text = _normalize(DOC.read_text(encoding="utf-8"))
    lower = text.lower()
    for phrase in (
        "Allowed verification actions",
        "Forbidden actions",
        "project root",
        "direct Python import",
        "branches/",
    ):
        assert phrase in text, f"bootstrap doc missing: {phrase!r}"
    assert "curl" in lower
    assert "raw" in lower


def test_bootstrap_doc_forbids_general_gate_weakening():
    text = _normalize(DOC.read_text(encoding="utf-8")).lower()
    assert "never weakens normal" in text or "does not weaken normal" in text
    assert "general bypass" in text or "general gate" in text


def test_bootstrap_doc_post_land_restart_and_verify():
    text = _normalize(DOC.read_text(encoding="utf-8"))
    for phrase in (
        "Restart MCP daemons",
        "canonical tools",
        "gitea_whoami",
    ):
        assert phrase in text, f"post-bootstrap guidance missing: {phrase!r}"


def test_runbook_links_bootstrap_path():
    text = _normalize(RUNBOOK.read_text(encoding="utf-8"))
    assert "Bootstrap Review Path for self-hosted MCP fixes (#557)" in text
    assert "bootstrap-review-path.md" in text
    assert "BOOTSTRAP REVIEW AUTHORIZATION (#557)" in text


def test_skill_links_bootstrap_path():
    text = _normalize(SKILL.read_text(encoding="utf-8"))
    assert "Bootstrap Review Path (#557)" in text
    assert "bootstrap-review-path.md" in text
    assert "BLOCKED + DIAGNOSE" in text or "BLOCKED" in text
