"""`GET /api/featured/method` (Stream AW2, D8): the doc's sections, or a 404 when the doc is no
authority.

The SPA page reads this and restates nothing; the served body reads the same dict. Pinned: the
shape (title, version, dated, version line, sections with title, anchor and html; the lede first
as "In short"); `DOC_MISSING` for an absent doc and for one without a version line; the route in
`PUBLIC_WHEN_OPEN` (a storefront read, public when the site is). No database.
"""

from __future__ import annotations

import pathlib

from fastapi import FastAPI
from fastapi.testclient import TestClient

from app.routers import featured as featured_router
from app.services import access, featured, process_doc


def client() -> TestClient:
    app = FastAPI()
    app.include_router(featured_router.router)
    return TestClient(app)


class TestTheShape:
    def test_the_doc_arrives_section_by_section_with_its_version(self):
        r = client().get("/api/featured/method")
        assert r.status_code == 200
        body = r.json()
        assert body["title"] == "How we choose what is featured"
        assert body["version"] == str(featured.VERSION) and body["version_line"] == f"**Version {featured.VERSION}, {body['dated']}**"
        assert set(body) == {"title", "version", "dated", "version_line", "sections"}
        assert set(body["sections"][0]) == {"title", "anchor", "html"}
        assert body["sections"][0]["title"] == "In short" and len(body["sections"]) == 9
        assert any(s["anchor"] == "the-guards" for s in body["sections"])
        factors = next(s for s in body["sections"] if s["anchor"] == "the-factors-in-order")
        assert "<table>" in factors["html"] and "<code>FIRST = 8</code>" in factors["html"]

    def test_the_route_is_a_storefront_read(self):
        assert "GET /api/featured/method" in access.PUBLIC_WHEN_OPEN
        assert "GET /how-we-choose" in access.PUBLIC_WHEN_OPEN and "GET /how-we-choose" in access.HTML_KEYS
        assert "/how-we-choose" in access.SPA_PUBLIC_WHEN_OPEN


class TestNoAuthority:
    def test_an_absent_doc_is_doc_missing(self, monkeypatch):
        monkeypatch.setitem(process_doc._DOCS["FEATURED"], "candidates", (pathlib.Path("/nowhere/FEATURED.md"),))
        r = client().get("/api/featured/method")
        assert r.status_code == 404 and r.json()["detail"]["error_code"] == "DOC_MISSING"

    def test_a_doc_without_a_version_line_is_doc_missing_too(self, monkeypatch, tmp_path):
        unversioned = tmp_path / "FEATURED.md"
        unversioned.write_text("# How we choose what is featured\n\nA lede.\n\n## One\n\nBody.\n")
        monkeypatch.setitem(process_doc._DOCS["FEATURED"], "candidates", (unversioned,))
        r = client().get("/api/featured/method")
        assert r.status_code == 404 and r.json()["detail"]["error_code"] == "DOC_MISSING"
