"""The guidelines a review pass follows, read from `docs/AI-REVIEW-GUIDELINES.md`.

Sources of truth: this module, that document (the authority), `routers/review.py`
(`GET /api/review/guidelines`), `tests/test_guidelines.py`.

The document is a living list: one `## Headline` per guideline and a short body under it. This
parses that shape and nothing else, so adding a guideline is adding a heading and the page has it
at the next deploy. It is READ, never restated: a second copy in TypeScript goes stale the first
time a precedent changes.

A pass reads the same document as context before it proposes, which is why the file carries no
version line, no dates and no session names. What to DO belongs here; why, and what it cost, lives
in `docs/REVIEW-PROCESS.md`.
"""

from __future__ import annotations

import pathlib
import re
from typing import Any

from app.services.markdown import heading_id, render_markdown

_CANDIDATES = (
    pathlib.Path("/srv/app/docs/AI-REVIEW-GUIDELINES.md"),
    pathlib.Path(__file__).resolve().parents[2] / "docs" / "AI-REVIEW-GUIDELINES.md",
)
_HEADING = re.compile(r"^##\s+(.+?)\s*$")


def path() -> pathlib.Path | None:
    return next((p for p in _CANDIDATES if p.is_file()), None)


def read() -> dict[str, Any]:
    """Every guideline as a headline and its detail. Writes nothing and reads no database."""
    found = path()
    if found is None:
        return {"missing": True, "path": None, "guidelines": [], "attention": []}
    out: list[dict[str, Any]] = []
    body: list[str] = []
    for line in found.read_text(encoding="utf-8").splitlines():
        match = _HEADING.match(line)
        if match:
            out.append({"headline": match.group(1), "anchor": heading_id(match.group(1)), "lines": []})
            body = out[-1]["lines"]
            continue
        if out and not line.startswith("<!--"):
            body.append(line)
    from app.services import attention

    return {
        "missing": False,
        "path": "docs/AI-REVIEW-GUIDELINES.md",
        "attention": attention.describe(),
        "guidelines": [{"headline": g["headline"], "anchor": g["anchor"],
                        "html": render_markdown("\n".join(g["lines"]).strip())}
                       for g in out if "\n".join(g["lines"]).strip()],
    }
