"""`docs/FEATURED.md` and `services/featured.py` say one thing (Stream AW2, D8 and D9).

The doc is what Adam and Mark read at `/how-we-choose`; the code is what runs. They are tied
both ways: every name in `featured.DOC_CONSTANTS` appears in the doc as `` `NAME = value` `` with
the code's value, every such line in the doc names a constant the code has, and the doc's
version line equals `featured.VERSION`. What drift would cost: a public page promising a rule
the site does not run, which is the failure the methodology page exists to prevent. House style
is checked here too: no em dash, never "cheap" or "free" as a price word ("duty free" names the
channel), never a bare "product" (product line, product variant, brand). No network, no database.
"""

from __future__ import annotations

import ast
import pathlib
import re

from app.services import featured, process_doc

DOC = pathlib.Path(__file__).resolve().parents[1] / "docs" / "FEATURED.md"
_CONSTANT = re.compile(r"`([A-Z][A-Z0-9_]+) = ([^`]+)`")


def source() -> str:
    return DOC.read_text(encoding="utf-8")


class TestTheConstantsBothWays:
    def test_every_doc_constant_is_in_the_doc_with_the_code_s_value(self):
        found = {name: ast.literal_eval(value) for name, value in _CONSTANT.findall(source())}
        missing = [name for name in featured.DOC_CONSTANTS if name not in found]
        assert not missing, f"named in DOC_CONSTANTS but not written in FEATURED.md: {missing}"
        wrong = {name: (found[name], getattr(featured, name)) for name in featured.DOC_CONSTANTS
                 if found[name] != getattr(featured, name)}
        assert not wrong, f"the doc's value differs from the code's: {wrong}"

    def test_every_constant_the_doc_writes_is_one_the_code_names(self):
        written = {name for name, _ in _CONSTANT.findall(source())}
        unknown = written - set(featured.DOC_CONSTANTS)
        assert not unknown, f"written in FEATURED.md but not in DOC_CONSTANTS: {unknown}"
        assert len(featured.DOC_CONSTANTS) == 23 and len(set(featured.DOC_CONSTANTS)) == 23

    def test_the_factors_table_carries_one_row_per_constant(self):
        table = next(s for s in process_doc.read_doc("FEATURED")["sections"] if s["title"].startswith("The factors"))["html"]
        assert table.count("<tr>") == len(featured.DOC_CONSTANTS) + 1  # the header row
        for name in featured.DOC_CONSTANTS:
            assert f"<code>{name} = " in table, name


class TestTheVersion:
    def test_the_doc_s_version_line_equals_the_code_s_version(self):
        out = process_doc.read_doc("FEATURED")
        assert out["version"] == str(featured.VERSION)
        assert re.search(r"^\*\*Version %d, \d{4}-\d{2}-\d{2}\*\*$" % featured.VERSION, source(), re.M)


class TestTheShape:
    def test_eight_sections_in_the_decided_order_under_the_title(self):
        out = process_doc.read_doc("FEATURED")
        assert out["title"] == "How we choose what is featured"
        titles = [s["title"] for s in out["sections"][1:]]
        assert len(titles) == 8
        assert titles[0] == 'What "featured" means' and titles[1] == "What a comparison is"
        assert titles[3].startswith("The factors") and titles[5] == "The guards"
        assert titles[6] == "What an admin's pick does" and titles[7] == "What is never done"
        assert all(s["html"].strip() for s in out["sections"]), "every section carries a body"

    def test_the_lede_is_one_paragraph_and_the_version_line_is_not_in_it(self):
        lead = process_doc.read_doc("FEATURED")["sections"][0]["html"]
        assert lead.count("<p>") == 1 and "Version" not in lead


class TestHouseStyle:
    def test_no_em_dash_anywhere_the_reader_sees(self):
        assert "\u2014" not in source()

    def test_never_cheap_or_free_as_a_price_word(self):
        words = re.findall(r"[a-z]+", source().lower().replace("duty free", "").replace("duty-free", ""))
        assert "cheap" not in words and "free" not in words

    def test_never_a_bare_product(self):
        """product line, product variant, brand: never "product" alone (VOCABULARY.md)."""
        bare = re.findall(r"\bproducts?\b(?!\s+(?:lines?|variants?)\b)", source(), re.I)
        assert not bare, f"bare product in FEATURED.md: {len(bare)} times"
