"""
FR-068 / E5:S09:T04 — sidebar IA, landing wayfinding, README mapping.

S1–S5, S7: assertions in this module.

S6 (green production build): run `PORTAL_BUILD_STRICT=1` with
`tests/test_portal_fr065_identity.py::test_fr065_s9_portal_production_build`.
(`portal` uses `docusaurus build --no-minify` — see `portal/README.md` Build section.)
"""

from __future__ import annotations

import re
from pathlib import Path

import pytest

REPO_ROOT = Path(__file__).resolve().parent.parent
PORTAL_DIR = REPO_ROOT / "portal"
DOCS_ROOT = REPO_ROOT / "docs"
SIDEBARS_PATH = PORTAL_DIR / "sidebars.js"
INDEX_PATH = PORTAL_DIR / "src" / "pages" / "index.js"
CONFIG_PATH = PORTAL_DIR / "docusaurus.config.js"
README_PATH = PORTAL_DIR / "README.md"

_SINGLETON_AUTOGEN_PATTERN = re.compile(
    r"tutorialSidebar\s*:\s*\[\s*\{\s*type:\s*['\"]autogenerated['\"]\s*,\s*dirName:\s*['\"]\.['\"]\s*\}\s*\]\s*",
    re.MULTILINE,
)


@pytest.fixture
def sidebars_text() -> str:
    return SIDEBARS_PATH.read_text(encoding="utf-8")


@pytest.fixture
def index_text() -> str:
    return INDEX_PATH.read_text(encoding="utf-8")


@pytest.fixture
def readme_text() -> str:
    return README_PATH.read_text(encoding="utf-8")


@pytest.fixture
def config_text() -> str:
    return CONFIG_PATH.read_text(encoding="utf-8")


def _dir_names_from_sidebars(text: str) -> list[str]:
    return re.findall(r"dirName:\s*['\"]([^'\"]+)['\"]", text)


def test_fr068_s1_sidebar_not_plain_singleton_autogen(sidebars_text: str):
    """S1 — IA is not a single autogenerated '.' sidebar (FR-068)."""
    assert "docsSidebar" in sidebars_text
    assert not _SINGLETON_AUTOGEN_PATTERN.search(
        sidebars_text
    ), "S1: replace flat tutorial autogen with pillar categories"


def test_fr068_s1_ordering_comment(sidebars_text: str):
    """S1 / NF01 — ordering philosophy and README pointer."""
    head = sidebars_text[:2500].lower()
    assert "canonical" in head and "pillar" in head, "S1: comment should name canonical pillar ordering"
    assert "readme" in head, "S1: comment should point maintainers at portal README"


def test_fr068_s2_readme_mapping_table(readme_text: str):
    """S2 — FR-068 mapping table in portal README."""
    lower = readme_text.lower()
    assert "fr-068" in lower
    assert "sidebar" in lower and "mapping" in lower
    assert "|" in readme_text and "architecture/" in readme_text
    assert "no-minify" in lower or "--no-minify" in readme_text, (
        "S2: document production build workaround in README Build section"
    )


def test_fr068_s3_no_tutorial_cta(index_text: str):
    """S3 / AC2 — no template Docusaurus tutorial CTA."""
    assert "Docusaurus Tutorial" not in index_text
    assert "/docs/intro" not in index_text


def test_fr068_s3_primary_links_adk(index_text: str):
    """S3 — stable entry routes on the homepage."""
    for path in (
        "/docs/documentation/docusaurus-portal-index",
        "/docs/architecture/standards-and-adrs/dev-kit-versioning-policy",
    ):
        assert path in index_text, f"S3: missing homepage link {path}"


def test_fr068_s4_semantic_headings(index_text: str):
    """S4 / NF02 — hero heading + Start here section."""
    assert "as=\"h1\"" in index_text or 'as="h1"' in index_text
    assert "Start here" in index_text


def test_fr068_s5_sidebar_dirs_exist(sidebars_text: str):
    """S5 — each autogen dirName exists under docs/."""
    for d in _dir_names_from_sidebars(sidebars_text):
        path = DOCS_ROOT / d
        assert path.is_dir(), f"S5: docs/{d} is not a directory"


def test_fr068_s_navbar_sidebar_id_matches(sidebars_text: str, config_text: str):
    """S5 — navbar docSidebar targets docsSidebar."""
    assert "docsSidebar" in sidebars_text
    assert "sidebarId: 'docsSidebar'" in config_text or 'sidebarId: "docsSidebar"' in config_text


def test_fr068_s7_pillars_in_sidebar(sidebars_text: str):
    """S7 (surrogate) — six canonical pillar folders appear as dirName entries."""
    dirs = set(_dir_names_from_sidebars(sidebars_text))
    for pillar in (
        "architecture",
        "changelog-and-release-notes",
        "project-management",
        "guides",
        "documentation",
        "knowledge",
    ):
        assert pillar in dirs, f"S7: missing sidebar category for {pillar}"


def test_fr068_s7_homepage_covers_doc_and_architecture(index_text: str, readme_text: str):
    """S7 — homepage links into documentation/ and architecture/."""
    assert "/docs/documentation/" in index_text
    assert "/docs/architecture/" in index_text
    hf_path = PORTAL_DIR / "src" / "components" / "HomepageFeatures" / "index.js"
    hf = hf_path.read_text(encoding="utf-8")
    assert "/docs/documentation/" in hf
    assert "/docs/architecture/" in hf
    assert "/docs/project-management/" in hf
