"""Tests validating dispatch test harness documentation accuracy.

Ensures docs/testing.md stays in sync with the actual test harness
implementation in dispatch/tests/conftest.py and dispatch/tests/test_harness.py.
"""
from __future__ import annotations

import re
from pathlib import Path

import pytest

PROJECT_ROOT = Path(__file__).resolve().parent.parent.parent
DOCS_PATH = PROJECT_ROOT / "docs" / "testing.md"
CONFTEST_PATH = PROJECT_ROOT / "dispatch" / "tests" / "conftest.py"
HARNESS_TEST_PATH = PROJECT_ROOT / "dispatch" / "tests" / "test_harness.py"
DAEMON_PATH = PROJECT_ROOT / "dispatch" / "daemon.py"
CONFIG_PATH = PROJECT_ROOT / "dispatch" / "config.py"


@pytest.fixture
def doc_content() -> str:
    """Load the testing documentation."""
    assert DOCS_PATH.exists(), f"Documentation file missing: {DOCS_PATH}"
    return DOCS_PATH.read_text()


@pytest.fixture
def conftest_source() -> str:
    """Load the dispatch conftest source code."""
    assert CONFTEST_PATH.exists(), f"Conftest missing: {CONFTEST_PATH}"
    return CONFTEST_PATH.read_text()


@pytest.fixture
def harness_test_source() -> str:
    """Load the harness verification test source code."""
    assert HARNESS_TEST_PATH.exists(), f"Harness test missing: {HARNESS_TEST_PATH}"
    return HARNESS_TEST_PATH.read_text()


@pytest.fixture
def daemon_source() -> str:
    """Load the dispatch daemon source code."""
    assert DAEMON_PATH.exists(), f"Daemon source missing: {DAEMON_PATH}"
    return DAEMON_PATH.read_text()


# ─── File Existence ─────────────────────────────────────────────


class TestFilesExist:
    """All documented source files exist on disk."""

    def test_docs_testing_md_exists(self):
        assert DOCS_PATH.exists()

    def test_dispatch_conftest_exists(self):
        assert CONFTEST_PATH.exists()

    def test_dispatch_test_harness_exists(self):
        assert HARNESS_TEST_PATH.exists()

    def test_dispatch_daemon_exists(self):
        assert DAEMON_PATH.exists()

    def test_dispatch_config_exists(self):
        assert CONFIG_PATH.exists()


# ─── Fixture Documentation ──────────────────────────────────────


class TestFixturesDocumented:
    """Documented fixtures match the actual conftest implementation."""

    def test_temp_greymatter_db_in_docs(self, doc_content: str):
        """The temp_greymatter_db fixture is documented."""
        assert "temp_greymatter_db" in doc_content

    def test_mock_coordinator_in_docs(self, doc_content: str):
        """The mock_coordinator fixture is documented."""
        assert "mock_coordinator" in doc_content

    def test_test_daemon_in_docs(self, doc_content: str):
        """The test_daemon fixture is documented."""
        assert "test_daemon" in doc_content

    def test_seed_work_items_in_docs(self, doc_content: str):
        """The seed_work_items helper is documented."""
        assert "seed_work_items" in doc_content

    def test_temp_greymatter_db_exists_in_conftest(self, conftest_source: str):
        """The fixture defined in conftest matches docs."""
        assert "def temp_greymatter_db(" in conftest_source

    def test_mock_coordinator_exists_in_conftest(self, conftest_source: str):
        """The fixture defined in conftest matches docs."""
        assert "def mock_coordinator(" in conftest_source

    def test_test_daemon_exists_in_conftest(self, conftest_source: str):
        """The fixture defined in conftest matches docs."""
        assert "def test_daemon(" in conftest_source

    def test_seed_work_items_exists_in_conftest(self, conftest_source: str):
        """The helper defined in conftest matches docs."""
        assert "def seed_work_items(" in conftest_source


# ─── Mock Coordinator Endpoints ─────────────────────────────────


class TestMockCoordinatorEndpointsDocumented:
    """All mock coordinator routes in conftest are documented in testing.md."""

    @pytest.mark.parametrize("route", [
        "/api/health",
        "/api/work",
        "/api/work/{id}/assign",
        "/api/work/{id}/complete",
        "/api/dispatch/config",
        "/api/dispatch/rate-limit",
        "/api/breakers/{project}",
        "/api/nodes",
        "/api/nodes/{id}/heartbeat",
    ])
    def test_route_documented(self, doc_content: str, route: str):
        """Each mock coordinator route appears in documentation."""
        assert route in doc_content, f"Route {route} not found in docs/testing.md"

    @pytest.mark.parametrize("route,method", [
        ("/api/health", "GET"),
        ("/api/work", "POST"),
        ("/api/dispatch/config", "GET"),
        ("/api/nodes", "POST"),
    ])
    def test_route_in_conftest(self, conftest_source: str, route: str, method: str):
        """Each documented route has a handler in conftest."""
        assert route in conftest_source, f"Route {route} not found in conftest"


# ─── Daemon Methods ─────────────────────────────────────────────


class TestDaemonMethodsDocumented:
    """Daemon methods exercised by the harness actually exist."""

    @pytest.mark.parametrize("method", [
        "poll_queue",
        "claim_work",
        "report_completion",
    ])
    def test_method_exists_in_daemon(self, daemon_source: str, method: str):
        """Each documented daemon method exists in daemon.py."""
        assert f"def {method}(" in daemon_source

    @pytest.mark.parametrize("method", [
        "poll_queue",
        "claim_work",
        "report_completion",
    ])
    def test_method_in_docs(self, doc_content: str, method: str):
        """Each exercised method appears in the testing docs."""
        assert method in doc_content


# ─── Test Harness Classes ───────────────────────────────────────


class TestHarnessClassesDocumented:
    """All test classes in test_harness.py are documented."""

    @pytest.mark.parametrize("class_name", [
        "TestTempGreymatterDb",
        "TestSeedWorkItems",
        "TestMockCoordinator",
        "TestTestDaemon",
    ])
    def test_class_in_docs(self, doc_content: str, class_name: str):
        """Each test class appears in testing.md."""
        assert class_name in doc_content

    @pytest.mark.parametrize("class_name", [
        "TestTempGreymatterDb",
        "TestSeedWorkItems",
        "TestMockCoordinator",
        "TestTestDaemon",
    ])
    def test_class_exists_in_source(self, harness_test_source: str, class_name: str):
        """Each documented class exists in test_harness.py."""
        assert f"class {class_name}" in harness_test_source


# ─── Design Decisions ───────────────────────────────────────────


class TestDesignDecisionsDocumented:
    """Key design decisions are reflected in both docs and code."""

    def test_dry_run_documented(self, doc_content: str):
        """dry_run=True is documented as a design decision."""
        assert "dry_run" in doc_content

    def test_dry_run_in_conftest(self, conftest_source: str):
        """dry_run=True is set in the test_daemon fixture."""
        assert "dry_run=True" in conftest_source

    def test_core_schema_documented(self, doc_content: str):
        """CORE_SCHEMA usage is documented."""
        assert "CORE_SCHEMA" in doc_content

    def test_core_schema_in_conftest(self, conftest_source: str):
        """CORE_SCHEMA is imported and used in conftest."""
        assert "CORE_SCHEMA" in conftest_source

    def test_mock_transport_documented(self, doc_content: str):
        """MockTransport is documented."""
        assert "MockTransport" in doc_content

    def test_mock_transport_in_conftest(self, conftest_source: str):
        """MockTransport is used in conftest."""
        assert "MockTransport" in conftest_source

    def test_coordinator_state_documented(self, doc_content: str):
        """_CoordinatorState is documented."""
        assert "_CoordinatorState" in doc_content

    def test_coordinator_state_in_conftest(self, conftest_source: str):
        """_CoordinatorState class exists in conftest."""
        assert "class _CoordinatorState" in conftest_source


# ─── Shared Fixtures Section ────────────────────────────────────


class TestSharedFixturesSection:
    """dispatch/tests/conftest.py is listed in the Shared Fixtures section."""

    def test_dispatch_conftest_in_shared_fixtures(self, doc_content: str):
        """dispatch/tests/conftest.py appears in the Shared Fixtures section."""
        # Find the Shared Fixtures section and verify dispatch conftest is there
        section_match = re.search(
            r"### Shared Fixtures.*?### ",
            doc_content,
            re.DOTALL,
        )
        assert section_match is not None, "Shared Fixtures section not found"
        section = section_match.group()
        assert "dispatch/tests/conftest.py" in section


# ─── Dispatch Tests Table ───────────────────────────────────────


class TestDispatchTestsTable:
    """test_harness.py appears in the Dispatch Tests table."""

    def test_harness_in_dispatch_table(self, doc_content: str):
        """test_harness.py is listed in the Dispatch Tests table."""
        # Find the Dispatch Tests section
        section_match = re.search(
            r"### Dispatch Tests.*?\*\*Dispatch subtotal",
            doc_content,
            re.DOTALL,
        )
        assert section_match is not None, "Dispatch Tests section not found"
        section = section_match.group()
        assert "test_harness.py" in section
