"""The review process document, read at runtime rather than restated (Stream K10.2).

`docs/REVIEW-PROCESS.md` is the authority for what a rule may do without asking a person, and its
version line is a rules version: changing it is a deploy and, when the boundary moves, a rederive.
The first tab of `/review` shows it to a person who is not going to read the repository, so the
server reads the file and hands over its sections. A second copy of a rule in the page would go
stale the first time the doc changed, which is the failure the boundary exists to stop.

What it cost before this was tested: the document's grouping defaults are a table, and the
markdown renderer had no table support, so section 2 -- the block a person opens the tab to read --
rendered as one unreadable run-on paragraph.

Pure logic: no network, no database for the reader itself.
"""
from __future__ import annotations

import pathlib

from app.services import process_doc
from app.services.markdown import render_markdown

DOC = pathlib.Path(__file__).resolve().parents[1] / "docs" / "REVIEW-PROCESS.md"


class TestTheDocumentIsFound:
    def test_the_checkout_copy_is_found_and_is_the_real_file(self):
        assert process_doc.path() == DOC

    def test_the_image_path_is_tried_first_so_the_container_reads_its_own_copy(self):
        """The runtime stage copies this one doc (`Dockerfile`); nothing else from `docs/` ships."""
        assert process_doc._CANDIDATES[0] == pathlib.Path("/srv/app/docs/REVIEW-PROCESS.md")
        dockerfile = (pathlib.Path(__file__).resolve().parents[1] / "Dockerfile").read_text()
        assert "COPY docs/REVIEW-PROCESS.md ./docs/REVIEW-PROCESS.md" in dockerfile

    def test_a_missing_document_says_so_rather_than_inventing_content(self, monkeypatch):
        monkeypatch.setattr(process_doc, "_CANDIDATES", (pathlib.Path("/nowhere/REVIEW-PROCESS.md"),))
        out = process_doc.read()
        assert out["missing"] is True and out["sections"] == [] and out["version"] is None


class TestWhatTheTabShows:
    def test_the_version_line_is_the_document_s_own(self):
        out = process_doc.read()
        assert out["version"] and out["dated"] and out["version_line"].startswith("**Version ")
        assert f"**Version {out['version']}, {out['dated']}**" in DOC.read_text()

    def test_every_section_of_the_document_arrives_with_its_number_and_title(self):
        out = process_doc.read()
        numbered = [s for s in out["sections"] if s["number"]]
        assert [s["number"] for s in numbered] == [str(n) for n in range(1, len(numbered) + 1)]
        titles = {s["number"]: s["title"] for s in numbered}
        assert "certain boundary" in titles["1"]
        assert titles["2"].startswith("Grouping defaults")
        assert "spot-check" in titles["4"]
        assert out["sections"][0]["number"] is None, "the standing rules lead, before section 1"

    def test_the_standing_rules_carry_the_two_a_machine_never_breaks(self):
        standing = process_doc.read()["sections"][0]["html"]
        assert "machine never applies a proposal" in standing and "machine never undoes a decision" in standing

    def test_the_boundary_and_the_thresholds_arrive_as_the_document_wrote_them(self):
        by_number = {s["number"]: s["html"] for s in process_doc.read()["sections"]}
        assert "The brand, matched to its row" in by_number["1"]
        assert "lowest" in by_number["4"] and "0.7" in by_number["4"]

    def test_the_grouping_defaults_are_a_table_and_render_as_one(self):
        """Section 2 is the block rian opens this tab for; as a paragraph it is unreadable."""
        html = next(s["html"] for s in process_doc.read()["sections"] if s["number"] == "2")
        assert "<table>" in html and html.count("<tr>") > 8
        assert "<th>Vertical and case</th>" in html
        assert "|---|" not in html


class TestTheTableRenderer:
    def test_a_pipe_table_becomes_a_table(self):
        html = render_markdown("| A | B |\n|---|---|\n| one | two |")
        assert html == ("<table><thead><tr><th>A</th><th>B</th></tr></thead>"
                        "<tbody><tr><td>one</td><td>two</td></tr></tbody></table>")

    def test_a_short_row_is_padded_and_a_long_one_trimmed_rather_than_shifting_the_columns(self):
        html = render_markdown("| A | B |\n|---|---|\n| one |\n| x | y | z |")
        assert "<tr><td>one</td><td></td></tr>" in html and "<tr><td>x</td><td>y</td></tr>" in html

    def test_a_line_with_a_pipe_that_is_not_a_table_is_still_a_paragraph(self):
        assert render_markdown("a | b and nothing else").startswith("<p>")
        assert "<table>" not in render_markdown("| A | B |\nplain text")

    def test_inline_markup_inside_a_cell_is_rendered_and_html_is_escaped(self):
        html = render_markdown("| A | B |\n|---|---|\n| **bold** | `<script>` |")
        assert "<strong>bold</strong>" in html and "&lt;script&gt;" in html and "<script>" not in html
