"""Build docs/Neuro_Frontend_API_Guide.pdf from the live API (real examples, real roles).

    DATABASE_URL=postgresql+asyncpg://u:p@localhost/neuro_scratch python -m scripts.build_frontend_pdf

The database must be migrated and seeded and is WIPED (it runs POST /demo/reset): use a scratch
one. The screen order follows the UX designs: the screens in the mockups come first.
"""
import asyncio
import json
import re
from datetime import datetime
from pathlib import Path

from reportlab.lib import colors
from reportlab.lib.enums import TA_CENTER
from reportlab.lib.pagesizes import A4
from reportlab.lib.styles import ParagraphStyle
from reportlab.lib.units import mm
from reportlab.platypus import (
    BaseDocTemplate, CondPageBreak, Frame, KeepTogether, PageBreak, PageTemplate, Paragraph,
    Preformatted, Spacer, Table, TableStyle,
)
from reportlab.platypus.tableofcontents import TableOfContents

from app.main import app
from scripts.api_examples import capture

OUT = Path(__file__).resolve().parents[2] / "docs" / "Neuro_Frontend_API_Guide.pdf"
GREEN, INK, GREY, PALE = colors.HexColor("#1f6f50"), colors.HexColor("#1b1f23"), \
    colors.HexColor("#5b6670"), colors.HexColor("#eef3f0")
METHOD_COLORS = {"GET": "#2563eb", "POST": "#16803c", "PUT": "#b45309", "PATCH": "#b45309",
                 "DELETE": "#b91c1c"}

S = {
    "body": ParagraphStyle("body", fontName="Helvetica", fontSize=9.2, leading=12.6, textColor=INK,
                           spaceAfter=4),
    "small": ParagraphStyle("small", fontName="Helvetica", fontSize=8, leading=10.5,
                            textColor=GREY),
    "h1": ParagraphStyle("h1", fontName="Helvetica-Bold", fontSize=17, leading=21, textColor=GREEN,
                         spaceBefore=4, spaceAfter=8),
    "h2": ParagraphStyle("h2", fontName="Helvetica-Bold", fontSize=11.5, leading=15, textColor=INK,
                         spaceBefore=10, spaceAfter=4),
    "part": ParagraphStyle("part", fontName="Helvetica-Bold", fontSize=26, leading=30,
                           textColor=GREEN, spaceAfter=10),
    "cell": ParagraphStyle("cell", fontName="Helvetica", fontSize=8, leading=10, textColor=INK),
    "cellb": ParagraphStyle("cellb", fontName="Helvetica-Bold", fontSize=8, leading=10,
                            textColor=INK),
    "code": ParagraphStyle("code", fontName="Courier", fontSize=6.6, leading=8.1, textColor=INK),
    "bullet": ParagraphStyle("bullet", fontName="Helvetica", fontSize=9.2, leading=12.4,
                             textColor=INK, leftIndent=11, bulletIndent=1, spaceAfter=2),
    "tocL0": ParagraphStyle("tocL0", fontName="Helvetica-Bold", fontSize=9, leading=11,
                            textColor=INK, spaceBefore=2),
    "tocL1": ParagraphStyle("tocL1", fontName="Helvetica", fontSize=8, leading=9.5,
                            leftIndent=14, textColor=GREY),
    "cover": ParagraphStyle("cover", fontName="Helvetica-Bold", fontSize=26, leading=30,
                            textColor=GREEN, spaceAfter=10),
    "title": ParagraphStyle("title", fontName="Helvetica-Bold", fontSize=17, leading=21,
                            textColor=GREEN, spaceAfter=8),
}


def esc(text) -> str:
    return str(text).replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")


def rich(text: str) -> str:
    """`code` becomes Courier, **bold** stays bold; everything else is escaped."""
    out = esc(text)
    out = re.sub(r"`([^`]+)`", r'<font name="Courier" size="8.3">\1</font>', out)
    return re.sub(r"\*\*([^*]+)\*\*", r"<b>\1</b>", out)


PART_TITLES = {"Part A": "Part A: Screens from the UX designs", "Part B": "Part B: Other screens",
               "Part C": "Part C: Reference"}


class Guide(BaseDocTemplate):
    def __init__(self, path, **kw):
        super().__init__(str(path), pagesize=A4, leftMargin=16 * mm, rightMargin=16 * mm,
                         topMargin=16 * mm, bottomMargin=17 * mm,
                         title="Neuro API: Frontend Guide", author="Neuro backend", **kw)
        frame = Frame(self.leftMargin, self.bottomMargin, self.width, self.height, id="f")
        self.addPageTemplates([PageTemplate(id="main", frames=[frame], onPage=self.chrome)])

    def chrome(self, canvas, doc):
        canvas.saveState()
        canvas.setFont("Helvetica", 7.5)
        canvas.setFillColor(GREY)
        canvas.drawString(self.leftMargin, 9 * mm, "Neuro API - Frontend Guide")
        canvas.drawRightString(A4[0] - self.rightMargin, 9 * mm, f"Page {doc.page}")
        canvas.restoreState()

    def afterFlowable(self, flowable):
        if isinstance(flowable, Paragraph) and flowable.style.name in ("h1", "h2", "part"):
            level = 1 if flowable.style.name == "h2" else 0
            if flowable.style.name == "h1":
                self._chapter = flowable.getPlainText()
            elif not getattr(self, "_chapter", "").startswith(("A4", "A6")):
                return  # sub-steps are listed only for the two multi-step flows
            key = f"k{self.seq.nextf('toc')}"
            self.canv.bookmarkPage(key)
            text = PART_TITLES.get(flowable.getPlainText(), flowable.getPlainText())
            self.notify("TOCEntry", (level, text, self.page, key))


# ------------------------------------------------------------------ flowable helpers
def h1(text):
    return [CondPageBreak(60 * mm), Paragraph(esc(text), S["h1"])]


def h2(text):
    return [CondPageBreak(35 * mm), Paragraph(esc(text), S["h2"])]


def p(text):
    return [Paragraph(rich(text), S["body"])]


def bullets(items):
    return [Paragraph(rich(i), S["bullet"], bulletText="•") for i in items]


def note(text, fill="#fff7e0", edge="#e0b64a"):
    t = Table([[Paragraph(rich(text), S["body"])]], colWidths=[178 * mm])
    t.setStyle(TableStyle([("BACKGROUND", (0, 0), (-1, -1), colors.HexColor(fill)),
                           ("BOX", (0, 0), (-1, -1), 0.6, colors.HexColor(edge)),
                           ("LEFTPADDING", (0, 0), (-1, -1), 7), ("TOPPADDING", (0, 0), (-1, -1), 5),
                           ("BOTTOMPADDING", (0, 0), (-1, -1), 3)]))
    return [t, Spacer(1, 5)]


def tip(text):
    return note(text, fill="#eaf6ef", edge="#1f6f50")


def table(header, rows, widths, method_col=None):
    data = [[Paragraph(esc(h), S["cellb"]) for h in header]]
    for row in rows:
        cells = []
        for i, c in enumerate(row):
            if i == method_col:
                cells.append(Paragraph(f'<font color="{METHOD_COLORS.get(c, "#444")}"><b>{esc(c)}'
                                       "</b></font>", S["cell"]))
            else:
                cells.append(Paragraph(rich(c), S["cell"]))
        data.append(cells)
    t = Table(data, colWidths=[w * mm for w in widths], repeatRows=1)
    t.setStyle(TableStyle([
        ("BACKGROUND", (0, 0), (-1, 0), PALE), ("LINEBELOW", (0, 0), (-1, 0), 0.8, GREEN),
        ("LINEBELOW", (0, 1), (-1, -1), 0.25, colors.HexColor("#d5dcd8")),
        ("VALIGN", (0, 0), (-1, -1), "TOP"), ("LEFTPADDING", (0, 0), (-1, -1), 4),
        ("RIGHTPADDING", (0, 0), (-1, -1), 4), ("TOPPADDING", (0, 0), (-1, -1), 3),
        ("BOTTOMPADDING", (0, 0), (-1, -1), 3)]))
    return [t, Spacer(1, 6)]


def shorten(obj, max_list=2, max_len=88):
    if isinstance(obj, dict):
        return {k: shorten(v, max_list, max_len) for k, v in obj.items()}
    if isinstance(obj, list):
        kept = [shorten(v, max_list, max_len) for v in obj[:max_list]]
        return kept + ([f"... {len(obj) - max_list} more"] if len(obj) > max_list else [])
    if isinstance(obj, str) and len(obj) > max_len:
        return obj[:max_len - 3] + "..."
    return obj


def fmt(obj, indent=0, width=104):
    """JSON with small objects and lists kept on one line, so examples stay short."""
    one = json.dumps(obj, ensure_ascii=False)
    if len(one) + indent <= width or not isinstance(obj, (dict, list)):
        return one
    pad = " " * indent
    if isinstance(obj, dict):
        inner = [f"{pad}  {json.dumps(k)}: {fmt(v, indent + 2, width)}" for k, v in obj.items()]
        return "{\n" + ",\n".join(inner) + f"\n{pad}}}"
    inner = [f"{pad}  {fmt(v, indent + 2, width)}" for v in obj]
    return "[\n" + ",\n".join(inner) + f"\n{pad}]"


def code_box(text, chunk=40):
    """Shaded box(es) of code; long text is split so it can flow over page breaks."""
    lines = text.splitlines()
    boxes = []
    for i in range(0, len(lines), chunk):
        pre = Preformatted(chr(10).join(lines[i:i + chunk]), S["code"])
        t = Table([[pre]], colWidths=[178 * mm])
        t.setStyle(TableStyle([("BACKGROUND", (0, 0), (-1, -1), colors.HexColor("#f6f8f7")),
                               ("BOX", (0, 0), (-1, -1), 0.4, colors.HexColor("#cfd8d3")),
                               ("LEFTPADDING", (0, 0), (-1, -1), 6),
                               ("TOPPADDING", (0, 0), (-1, -1), 4),
                               ("BOTTOMPADDING", (0, 0), (-1, -1), 4)]))
        boxes.append(t)
    return boxes


class Examples:
    def __init__(self, ex):
        self.ex = ex

    def show(self, label, *, title=None, request=True, response=True, max_list=2, only=None):
        """Request and response of one captured call, as two code boxes."""
        e = self.ex.get(label)
        if e is None:
            return []
        head = f'<font color="{METHOD_COLORS.get(e["method"], "#444")}"><b>{e["method"]}</b></font>' \
               f' <font name="Courier" size="8.5">/api/v1{esc(e["path"])}</font>'
        if e.get("params"):
            qs = "&amp;".join(f"{esc(k)}={esc(v)}" for k, v in e["params"].items())
            head += f' <font name="Courier" size="8" color="#5b6670">?{qs}</font>'
        head += f'   <font size="8" color="#5b6670">-&gt; {e["status"]}</font>'
        out = [Spacer(1, 3)]
        if title:
            out.append(Paragraph(f"<b>{esc(title)}</b>", S["body"]))
        head_par = Paragraph(head, S["body"])
        has_request = bool(request and e.get("body"))
        has_response = bool(response and e.get("response") is not None)
        if has_request:
            boxes = code_box(fmt(e["body"]))
            out.append(KeepTogether([head_par, Paragraph("Request body", S["small"]), boxes[0]]))
            out += boxes[1:]
        if has_response:
            resp = e["response"]
            if only and isinstance(resp, dict):
                resp = {k: resp[k] for k in only if k in resp}
            boxes = code_box(fmt(shorten(resp, max_list)))
            first = [Paragraph("Response", S["small"]), boxes[0]]
            out.append(KeepTogether(first if has_request else [head_par] + first))
            out += boxes[1:]
        if not has_request and not has_response:
            out.append(head_par)
        out.append(Spacer(1, 6))
        return out


# ------------------------------------------------------------------ endpoint index (from the app)
def endpoint_index():
    from tests.test_api_auth import ALL_ROLES, ROLE_MATRIX

    spec = app.openapi()
    entries = []
    for path, item in spec["paths"].items():
        for method, op in item.items():
            entries.append((method.upper(), path.removeprefix("/api/v1"), op.get("summary", "")))

    def roles_for(method, path):
        pattern = re.compile("^" + re.sub(r"\{[^}]+\}", r"[^/]+", re.escape(path)
                                          .replace(r"\{", "{").replace(r"\}", "}")) + "$")
        for m, mpath, allowed in ROLE_MATRIX:
            if m == method and pattern.match(mpath.split("?")[0].removeprefix("/api/v1")):
                return "any logged-in role" if set(allowed) == set(ALL_ROLES) else \
                    ", ".join(sorted(allowed))
        if path.startswith("/connect/webhook") or path.startswith("/connect/rest"):
            return "POS/ERP system (secret / token)"
        if path == "/auth/login":
            return "anyone"
        return "-"

    return [(m, f"`{pth}`", roles_for(m, pth), esc(summary))
            for m, pth, summary in sorted(entries, key=lambda e: (e[1], e[0]))]


# ------------------------------------------------------------------ the guide
def build_story(ex_data):
    x = Examples(ex_data)
    meta = ex_data["_meta"]
    st = []
    # ---------------------------------------------------------------- cover
    st += [Spacer(1, 55 * mm), Paragraph("Neuro API", S["cover"]),
           Paragraph("Frontend Guide", ParagraphStyle("t2", parent=S["h1"], fontSize=20)),
           Spacer(1, 6 * mm),
           *p("Everything a frontend developer needs to build the Neuro web and scanner screens "
             "against the backend: which call each screen makes, what to send, what comes back, "
             "who may call it, and what to show when it goes wrong."),
           Spacer(1, 4 * mm),
           *p("**Screens from the UX designs come first** (Part A: login and home, product "
             "list and add, delivery receiving with sampling, crates and labels, upload PO, "
             "dispatch, scanner). Other screens follow (Part B). Reference tables are at the end "
             "(Part C)."),
           Spacer(1, 4 * mm),
           *p("Every example in this guide is a **real response** captured by running the actual "
             "flows against the backend (receive, dispatch, scan, recommendations, reports)."),
           Spacer(1, 30 * mm),
           Paragraph(f"Generated {datetime.now():%d %B %Y}. Spec: <font name='Courier'>openapi.json</font>"
                     " in the repo, Swagger UI at <font name='Courier'>/docs</font>.", S["small"]),
           PageBreak()]
    toc = TableOfContents()
    toc.levelStyles = [S["tocL0"], S["tocL1"]]
    st += [Paragraph("Contents", S["title"]), toc, PageBreak()]

    # ---------------------------------------------------------------- 1 getting started
    st += h1("1. Getting started")
    st += table(["What", "Value"], [
        ["Base URL (local)", "`http://localhost:8000`, every API path below is under `/api/v1` "
                             "(except `/health`)"],
        ["Interactive docs", "`/docs` (Swagger UI) and `/openapi.json`; also `openapi.json` in the repo. "
                             "Import it into Postman or Insomnia, or generate a typed client."],
        ["Credentials", "**No API key.** Log in with an email and a password; send the token as "
                        "`Authorization: Bearer <access_token>`."],
        ["CORS", "The server allows browser calls from the origins in its `CORS_ORIGINS` setting. "
                 "Tell the backend your dev origin (e.g. `http://localhost:3000`)."],
        ["Content type", "JSON in, JSON out (CSV uploads use `text/csv`, labels come back as a PDF)."],
    ], [38, 140])
    st += h2("Log in")
    st += x.show("login", title="POST /auth/login", max_list=2)
    st += bullets([
        "Everyone starts on the default password **123456** and `must_change_password: true`. "
        "Send those users to a change-password screen first (Part B, Account).",
        "Use `role` and `site_id` from the response to decide which screens and buttons to show. "
        "`GET /auth/me` restores the same facts after a page reload.",
        "Five wrong passwords lock the account for 15 minutes. The `detail` of the 401 is safe to "
        "show on the login form.",
        "Tokens last 12 hours. A 401 on any later call means the session ended (password changed "
        "or reset, account disabled, role changed): go back to login.",
    ])
    st += h2("Demo accounts (all start with password 123456)")
    st += table(["Email", "Role", "Site"], [
        ["`dc_staff@neuro.local`", "DC_STAFF", "Dhaka DC"],
        ["`dc_manager@neuro.local`", "DC_MANAGER", "Dhaka DC"],
        ["`outlet_staff@neuro.local`", "OUTLET_STAFF", "Dhanmondi outlet (`OUT-DHN`)"],
        ["`outlet_manager@neuro.local`", "OUTLET_MANAGER", "Dhanmondi outlet"],
        ["`head_office@neuro.local`", "HEAD_OFFICE", "none (sees everything)"],
    ], [60, 40, 78])
    st += tip("**Quick way to try everything:** log in as `head_office`, call `POST /demo/reset` "
              "with `{\"confirm\": true}` for a clean seeded demo, then use `POST /demo/clock` to "
              "move time forward (stock ages, risk runs and recommendations refresh).")

    # ---------------------------------------------------------------- 2 rules
    st += h1("2. Rules that apply to every call")
    st += h2("Errors")
    st += p("Every error has the same shape. Switch on `error`, show `detail` to the user.")
    st += code_box('{"error": "QTY_EXCEEDS_STOCK", "detail": "Tomato: asked for 90, can allocate '
                       '24.5 (loose produce is picked in whole crates)"}')
    st += [Spacer(1, 6)]
    st += table(["error", "HTTP", "What the UI should do"], [
        ["`UNAUTHENTICATED`", "401", "Wrong login (show `detail`), or no / expired / ended token: go to login"],
        ["`FORBIDDEN`", "403", "Wrong role for this action. Hide the button, but still handle it"],
        ["`FORBIDDEN_SITE`", "403", "Right role, wrong site (another outlet's data)"],
        ["`VALIDATION_FAILED`", "422", "Bad input; `detail` says which field and why"],
        ["`UNKNOWN_CODE`", "404", "Scanned code or id not found"],
        ["`INVALID_STATE`", "409", "Not allowed right now (already confirmed, already decided, lapsed...)"],
        ["`TOO_FEW_SAMPLES`", "422", "Sample at least 10% of cartons (minimum 1)"],
        ["`SPLIT_COUNTS_MISMATCH`", "422", "Month carton counts do not add up to the line's cartons"],
        ["`NO_ACTIVE_PARAM_SET`", "422", "Undated / loose product whose category has no shelf-life parameters"],
        ["`IMPLAUSIBLE_DATE`", "422", "Printed date in the past or over 365 days ahead; resend with `override_reason`"],
        ["`BATCH_EXPIRED`", "422", "That batch / crate is expired"],
        ["`QTY_EXCEEDS_STOCK`", "422", "Not enough stock to allocate, move or write off"],
        ["`CRATE_NOT_ON_PICKLIST`", "422", "Scanned crate is not on this transfer (or needs `override_reason`)"],
        ["`UNMAPPED_EXTERNAL_ID`", "422", "(POS/ERP imports only) an outlet / item id has no mapping"],
    ], [46, 14, 118])
    st += h2("Numbers, dates and the clock")
    st += bullets([
        "**Quantities and money are strings** (`\"12.500\"`, `\"105.00\"`) so nothing is rounded. "
        "Parse them with a decimal-safe type. You may send numbers or strings.",
        "**Timestamps** are ISO-8601 with a timezone offset. Send them with an offset too (a "
        "timestamp without one is rejected). **Show times in Asia/Dhaka (UTC+6).**",
        "**Dates** (`printed_date`, `expected_date`) are plain `YYYY-MM-DD`.",
        "**The clock is simulated in the demo.** Never use the browser's time for business logic: "
        "read `now` from `GET /system/status` or the timestamps in responses.",
    ])
    st += h2("Truth layers: how far to trust a number")
    st += p("Numbers about stock, dates and temperature say where they come from. They appear as "
            "`layers`, `layer` or `expiry_layer` fields. **Never show an ESTIMATED or INFERRED value "
            "as a fact.**")
    st += table(["Layer", "Meaning", "Show it as"], [
        ["`PHYSICAL`", "Weighed, counted or scanned", "a fact"],
        ["`CAPTURED`", "A date read off the pack", "a fact (the printed date)"],
        ["`OBSERVED`", "A person or system reported it (a receipt, a POS sale)", "a fact, with its source"],
        ["`INFERRED`", "Worked out, e.g. a sale matched to a batch by FEFO", "approximate"],
        ["`ESTIMATED`", "Model output, e.g. heat-adjusted expiry", "approximate: \"Est. expiry\", the EST mark"],
    ], [28, 92, 58])
    st += h2("Who can call what")
    st += p("Each screen section says who may use it. A wrong role gets 403 `FORBIDDEN`; the right "
            "role at another site gets 403 `FORBIDDEN_SITE`. The full table is in Part C.")

    # ================================================================ PART A
    st += [PageBreak(), Spacer(1, 50 * mm), Paragraph("Part A", S["part"]),
           Paragraph("Screens from the UX designs", ParagraphStyle("pa", parent=S["h1"], fontSize=18)),
           *p("The screens in the mockups, in the order a user meets them: login and home, product "
             "listing and add, delivery receiving (with date sampling, crate weights and the "
             "label modal), upload PO, dispatch, and the scanner app."),
           PageBreak()]

    # ---------------------------------------------------------------- A1
    st += h1("A1. Login and web home")
    st += table(["UI element", "Call"], [
        ["Email + password form, Log in", "`POST /auth/login`"],
        ["Keep the user logged in after a reload", "`GET /auth/me` (with the stored token)"],
        ["Home tiles (Product Listing, Delivery, Outlet Today, Impact Dashboard, Inventory)",
         "no call: choose tiles from `role` (table below)"],
        ["Scan box in the top bar (hardware scanner or typed code)", "`GET /scan/{code}` (see A7)"],
        ["Status chip", "`GET /system/status` (see B7)"],
    ], [92, 86])
    st += h2("Which tiles each role sees")
    st += table(["Role", "Tiles"], [
        ["DC_STAFF", "Delivery (receiving, dispatch), Product Listing (read), Inventory (batches), scan box"],
        ["DC_MANAGER", "the above, plus add / edit products, delivery exceptions, dispatch sign-off"],
        ["OUTLET_STAFF", "receive trucks (scan in), Inventory, scan box, write off stock"],
        ["OUTLET_MANAGER", "Outlet Today (recommendations), receive trucks, Inventory, write off"],
        ["HEAD_OFFICE", "Product Listing, Upload PO, Impact Dashboard, reports, users, integrations, demo controls"],
    ], [34, 144])
    st += note("The \"Demand Forecasting\" tile in the design has no endpoint yet (forecasts are used "
               "inside the risk engine only).")

    # ---------------------------------------------------------------- A2
    st += h1("A2. Product Listing")
    st += p("Everyone can read the list. The search box, category filter and kind filter map to query "
            "parameters; page with `limit` and `offset`.")
    st += table(["UI element", "Call"], [
        ["Table rows", "`GET /products?search=&category_id=&kind=&limit=50&offset=0`"],
        ["Category filter dropdown", "`GET /product-categories`"],
        ["Kind filter (Packaged / Loose)", "`kind=PACKAGED` or `kind=LOOSE` on the list call"],
    ], [92, 86])
    st += x.show("products", title="Search for a product", max_list=1)
    st += p("Row fields: `id, sku, name, category, kind (PACKAGED|LOOSE), uom (UNIT|KG), mrp, "
            "list_price, unit_cost, barcode`. `mrp` is null for loose products.")
    st += x.show("categories", title="Category dropdown", max_list=2, request=False)

    # ---------------------------------------------------------------- A3
    st += h1("A3. Add New Product")
    st += p("Only DC_MANAGER and HEAD_OFFICE see the Add / Edit buttons.")
    st += table(["UI element", "Call"], [
        ["Add New Product form, Save", "`POST /products`"],
        ["Edit product", "`PATCH /products/{id}` (send only the changed fields)"],
        ["Category dropdown", "`GET /product-categories`"],
        ["Bulk upload", "`POST /connect/csv/product?source_system=erp` (see B8)"],
    ], [92, 86])
    st += x.show("product_create", title="Create a product")
    st += p("**Form rules to mirror** (the server enforces them and answers 422 `VALIDATION_FAILED` "
            "with the reason in `detail`):")
    st += bullets([
        "**Loose** products are sold by weight: `uom` must be `KG`, and `mrp` can be left empty.",
        "**Packaged** products are counted in units: `uom` must be `UNIT`, and an `mrp` is required.",
        "`list_price` cannot be above `mrp`.",
        "SKU and barcode must be unique. A repeated one is rejected with a message naming it.",
        "The SKU cannot change later, and `uom` / `kind` are locked once the product has batches.",
    ])

    # ---------------------------------------------------------------- A4
    st += h1("A4. Delivery Receiving")
    st += p("The longest flow, for DC_STAFF. A truck arrives, staff add what is on it, sample the "
            "printed dates on packaged cartons, weigh loose crates, choose a storage place, confirm, "
            "and print crate labels. Dropdown data first:")
    st += table(["UI element", "Call"], [
        ["Supplier dropdown", "`GET /suppliers`"],
        ["Product dropdown (`kind` tells you Cartons vs Crates)", "`GET /products`"],
        ["Storage place per line (CHILLED / AMBIENT)", "`GET /locations` (defaults to your own site)"],
        ["Incoming PO list (optional)", "`GET /expected-deliveries?status=OPEN`"],
    ], [92, 86])
    st += x.show("suppliers", title="Suppliers", request=False, max_list=2)
    st += x.show("locations", title="Storage places", request=False, max_list=2)
    st += h2("Step 1: log the truck's arrival")
    st += p("`truck_arrived_at` defaults to now (can be backdated up to 12 hours, never the future). "
            "Pass `expected_delivery_id` if staff picked an incoming PO: Neuro then cross-checks what "
            "arrives against it. Keep the returned receipt `id`.")
    st += x.show("receipt_create")
    st += h2("Step 2: add each line")
    st += p("Packaged: send `cartons` (required). Loose: no cartons. `kind` is decided by the "
            "product, never sent. UNIT products need a whole-number `qty`.")
    st += x.show("line_packaged", title="Packaged line (cartons)")
    st += x.show("line_loose", title="Loose line (no cartons)")
    st += h2("Step 3: sample the printed dates (packaged lines)")
    st += p("Once per sampled carton. Sample at least 10% of the cartons (minimum 1), never more than "
            "`cartons`. A past date or one over 365 days ahead is rejected with `IMPLAUSIBLE_DATE`; "
            "to accept it anyway, resend with `\"override_reason\": \"...\"`.")
    st += x.show("sample_1", title="First sampled carton")
    st += x.show("sample_2", title="Second sampled carton (a different month)", response=False)
    st += tip("**\"Month groups found\"** in the design: group the dates you typed by year-month. "
              "One month: nothing extra to send. Two or more months: show carton-count inputs per "
              "month, and send them as `month_splits` at confirm (they must add up to the line's "
              "cartons), or send `cannot_sort_reason` instead.")
    st += h2("Step 4: confirm (one all-or-nothing call)")
    st += bullets([
        "**One entry per line**, every line must appear, each with its storage `location_id`.",
        "Packaged, dates in **one month**: nothing extra. In **2+ months**: `month_splits`, or "
        "`cannot_sort_reason` (one batch with the earliest date, the reason is logged).",
        "Packaged with **no** samples: treated as undated and estimated (only works if the category "
        "has shelf-life parameters, else `NO_ACTIVE_PARAM_SET`).",
        "Loose: `crates` is required, one weight per crate. **Each crate becomes its own batch.** "
        "Weights must add up to the line's `qty` (within 1%).",
    ])
    st += x.show("receipt_confirm", title="Confirm the receipt", max_list=2)
    st += p("Render the **Batches Created** table from `batches` (`code, product_name, "
            "expiry_source, effective_expiry / printed_expiry, crates, qty`). Show `warnings` as "
            "non-blocking notices (`BELOW_MIN_SHELF_LIFE: ...`, `DELIVERY_DISCREPANCY: ...`). "
            "`receipt.match_status` is `MATCHED`, `DISCREPANCY`, `UNEXPECTED` or `NO_LIST`. Estimated "
            "batches get the **EST** mark (`expiry_source: ESTIMATED`).")
    st += h2("Step 5: print the crate labels (modal)")
    st += x.show("labels", title="Labels", request=False)
    st += bullets([
        "The answer is a **PDF** (`application/pdf`), one **QR label** per crate: the QR code, the batch "
        "code, product name, expiry month in large print and an EST mark on estimated batches.",
        "Fetch it **with the Authorization header as a blob** and open or print it: a plain link or "
        "`<a href>` will not carry the token. `per_row` sets labels per row (default 4).",
        "Only works after confirm (409 `INVALID_STATE` before).",
        "**The design shows a barcode and batch codes like `B-2026...`; the real labels use a QR code and "
        "codes like `MLK1L-261007-01`.**",
    ])

    # ---------------------------------------------------------------- A5
    st += h1("A5. Upload PO (Delivery menu)")
    st += p("Incoming purchase orders, so receiving can be cross-checked. HEAD_OFFICE creates them; "
            "DC staff and managers read them.")
    st += table(["UI element", "Call"], [
        ["Create PO form", "`POST /expected-deliveries` (HEAD_OFFICE)"],
        ["Upload a PO file", "`POST /connect/csv/expected_delivery?source_system=erp` (HEAD_OFFICE, raw `text/csv`)"],
        ["Incoming list at the DC", "`GET /expected-deliveries?status=OPEN&status=PARTIAL`"],
    ], [92, 86])
    st += x.show("expected_create", title="Create a PO")
    st += x.show("expected_list", title="List open POs", request=False, max_list=1)
    st += p("CSV columns: `po_ref, supplier_ext_id, site_ext_id, expected_date, sku_ext_id, "
            "expected_qty`, one row per product line. The result is `{rows_ok, rows_failed, duplicates, "
            "errors[]}`: list `errors` row by row. Re-uploading the same file is safe.")

    # ---------------------------------------------------------------- A6
    st += h1("A6. Dispatch Delivery")
    st += p("DC_STAFF sends stock to an outlet. Neuro picks crates FEFO (earliest removal first); loose "
            "produce is picked in whole crates and never over the requested quantity.")
    st += table(["UI element", "Call"], [
        ["To Outlet dropdown", "`GET /sites?type=OUTLET`"],
        ["Product picker", "`GET /products`"],
        ["\"Suggested batches... Assigned X of N\" while typing", "`POST /transfers/dispatch/preview`"],
        ["Submit / Request dispatch", "`POST /transfers/dispatch`"],
        ["Scan crates onto the truck", "`POST /transfers/{id}/load`"],
        ["Vehicle chips OPEN / INSULATED / REFRIGERATED, Depart", "`POST /transfers/{id}/depart`"],
        ["Manager sign-off badge", "`POST /transfers/{id}/approve` (DC_MANAGER)"],
        ["Re-open a dispatch", "`GET /transfers/{id}` and `GET /transfers?status=READY&type=DISPATCH`"],
    ], [92, 86])
    st += x.show("sites", title="Outlets for the dropdown", request=False, max_list=2)
    st += h2("Live preview: \"Assigned X of N\"")
    st += p("Same body as the real request, but **nothing is reserved**. Call it as quantities are "
            "typed (debounce it), show `assigned` of `total`, and disable Submit unless `can_dispatch` "
            "is true. The real request stays the authority: stock can change in between.")
    st += x.show("dispatch_preview")
    st += h2("Request the dispatch (the FEFO pick list)")
    st += x.show("dispatch_create", max_list=1, request=False)
    st += p("`QTY_EXCEEDS_STOCK` means it cannot be met; nothing is reserved. Show the pick list from "
            "`moves[].lines[]` (`batch_code`, `crate_barcode`, `qty`, `removal_date`).")
    st += h2("Scan crates onto the truck, then depart")
    st += p("A scanned crate on the list flips `scanned: true`. A **different** crate of the same product "
            "needs `override_reason` (it swaps the pick and is logged); otherwise "
            "`CRATE_NOT_ON_PICKLIST`. A rejected scan rolls the whole request back. Depart needs at "
            "least one scanned crate; unscanned lines are released automatically.")
    st += x.show("dispatch_load", max_list=1, only=["id", "status"])
    st += x.show("dispatch_depart", max_list=1, only=["id", "status", "vehicle_type", "dispatched_at"])
    st += x.show("dispatch_approve", max_list=1,
                 only=["id", "status", "dc_manager_approved_by", "dc_manager_approved_at"],
                 title="Manager sign-off (a recorded sign-off; loading and departure do not wait for it)")

    # ---------------------------------------------------------------- A7
    st += h1("A7. Scanner app and the scan box")
    st += p("The Flutter scanner app and the web scan box use the **same** calls. The scan box accepts "
            "hardware-scanner text, typed text or a camera QR value.")
    st += table(["Task", "Call", "Who"], [
        ["Look something up", "`GET /scan/{code}`", "DC and outlet roles"],
        ["Load crates on the truck", "`POST /transfers/{id}/load`", "DC_STAFF"],
        ["Confirm the truck left", "`POST /transfers/{id}/depart`", "DC_STAFF"],
        ["See trucks heading to my outlet", "`GET /transfers?status=IN_TRANSIT`", "outlet roles"],
        ["Scan crates in at the outlet", "`POST /transfers/{id}/arrive`", "OUTLET_STAFF, OUTLET_MANAGER"],
        ["Resolve a missing crate later", "`POST /transfers/{id}/arrive` again", "outlet roles"],
    ], [60, 74, 44])
    st += h2("What a scan returns")
    st += bullets([
        "A crate QR (`C000001001`) returns `kind: CRATE` with batch, product, `weight_kg`, expiry and "
        "`locations[]` (where it is and how much).",
        "A batch code (`TOM-261007-01`) returns `kind: BATCH`.",
        "A product barcode returns `kind: PRODUCT`.",
        "Anything else is 404 `UNKNOWN_CODE`.",
        "`layers` says how far to trust each number (weights and quantities are PHYSICAL; the expiry is "
        "CAPTURED or ESTIMATED).",
    ])
    st += x.show("scan_crate", title="Scan a crate QR", request=False)
    st += x.show("scan_product", title="Scan a product barcode", request=False, max_list=1)
    st += h2("Receiving a truck at the outlet")
    st += p("Scan every crate unloaded. **Crates not scanned come back as MISSING** (`missing_crates` "
            "counts them) and stay in transit; scan them later with another `arrive` call to resolve "
            "them (`INVALID_STATE` if already received). The response also shows each estimated batch's "
            "expiry **before and after the trip** in `recalculated[]`: a good \"heat cost X hours of "
            "life\" message.")
    st += x.show("arrive", max_list=2, request=False,
                 only=["id", "status", "arrived_at", "missing_crates", "recalculated"])
    st += x.show("transfers_in_transit", title="Transfer list", request=False, max_list=1,
                 only=None)

    # ---------------------------------------------------------------- A8
    st += h1("A8. Batch detail and the Batches (Inventory) tab")
    st += table(["UI element", "Call"], [
        ["Batches tab (list with search)", "`GET /batches?search=&product_id=&status=&expiring_within_days=&limit=&offset=`"],
        ["Batch detail page", "`GET /batches/{id}`"],
        ["Timeline on the detail page", "`GET /batches/{id}/history`"],
        ["Write off stock", "`POST /batches/{id}/write-off` (see B2)"],
    ], [78, 100])
    st += x.show("batches_list", title="Batches tab", request=False, max_list=2)
    st += p("Without `status` it lists batches that still have stock at the caller's site (head office "
            "sees all sites, or one via `site_id`), earliest removal first. `expiry_layer` says whether "
            "the date is CAPTURED (printed) or ESTIMATED.")
    st += x.show("batch_detail", title="Batch detail", request=False)
    st += x.show("batch_history", title="Timeline, oldest first", request=False, max_list=3)
    st += p("Events: `RECEIVED, EXPOSURE, EXPIRY_RECALCULATED, DISPATCHED, ARRIVED, MISSING_AT_ARRIVAL, "
            "FEFO_OVERRIDE, SOLD, WRITTEN_OFF`. Each has a `layer`: style estimated events differently from physical "
            "ones.")

    # ================================================================ PART B
    st += [PageBreak(), Spacer(1, 50 * mm), Paragraph("Part B", S["part"]),
           Paragraph("Other screens", ParagraphStyle("pb", parent=S["h1"], fontSize=18)),
           *p("Outlet Today (recommendations), writing off stock, outlet-to-outlet transfers, the Impact "
             "Dashboard and waste report, delivery exceptions, passwords and user administration, demo "
             "controls and the status chip, and the POS/ERP import screens."),
           PageBreak()]

    st += h1("B1. Outlet Today (OUTLET_MANAGER)")
    st += p("Recommendations for the manager: what to do about batches at risk of not selling. Advice "
            "comes from the decision agent, or from built-in rules when the agent is not connected, slow or "
            "down (`created_by: AGENT` or `RULES`; both are valid).")
    st += table(["UI element", "Call"], [
        ["Today list (pending items, most expensive risk first)", "`GET /today?site_id=`"],
        ["Follow / Dismiss", "`POST /recommendations/{id}/decide`"],
        ["History (any status)", "`GET /recommendations?site_id=&status=&limit=`"],
        ["One item", "`GET /recommendations/{id}`"],
    ], [92, 86])
    st += x.show("today", title="Today list", request=False)
    st += bullets([
        "`reason` is plain language. `evidence` holds the engine's real numbers (the source of truth: "
        "show them in a \"why\" panel).",
        "`candidates` is every valid action; `chosen_candidate_id` is the recommended one; `alternatives` "
        "are the ids of the others.",
        "`action_type`: **FRONT_OF_SHELF** (placement task), **CONSIDER_SALE** (a *suggested* discount %: the "
        "manager types the real price), **TRANSFER** (move to `target_site_id`), **WRITE_OFF** (remove the "
        "batch; `overdue: true` when it is 4 hours past removal and still not done).",
        "Show `expiry_layer: ESTIMATED` dates as approximate.",
        "The list refreshes after a truck arrives, after sales are ingested, every 15 minutes and when "
        "the demo clock moves. There is no push: refetch on screen focus.",
    ])
    st += h2("Follow or dismiss")
    st += x.show("decide_dismissed", title="Dismiss (reason required)")
    st += x.show("decide_followed", title="Follow a sale suggestion (applied_price is optional)")
    st += bullets([
        "`applied_price` is **only for CONSIDER_SALE** (422 for other actions) and just records what the "
        "manager chose. Neuro never sets or pushes a price anywhere.",
        "Dismiss needs `dismiss_reason` (offer \"Not needed\", \"Numbers look wrong\", or free text).",
        "Following a **TRANSFER** also creates the outlet transfer (`transfer_id`); if the stock has gone "
        "meanwhile: 422 `QTY_EXCEEDS_STOCK` and the item stays pending.",
        "Errors: 404 `UNKNOWN_CODE`, 403 `FORBIDDEN_SITE`, 409 `INVALID_STATE` (already decided, or "
        "**lapsed**: advice expires at the batch's removal date and is replaced whenever a new risk run "
        "changes the picture; refresh the list).",
        "Only the manager of that outlet can decide. Head office can view (`GET /recommendations`) but not decide.",
    ])
    st += x.show("recommendations_history", title="History", request=False, max_list=1)

    st += h1("B2. Writing off stock")
    st += p("DC and outlet staff and managers, at their own site. This is how a WRITE_OFF recommendation "
            "is carried out, and it feeds the waste report. `qty` is optional: omit it to write off "
            "everything unreserved at your site. Stock reserved on a transfer cannot be written off.")
    st += x.show("write_off")

    st += h1("B3. Outlet to outlet transfers")
    st += p("When a manager follows a TRANSFER recommendation, a READY transfer of type "
            "`OUTLET_TRANSFER` is created. It uses the **same endpoints** as a DC dispatch: the sending "
            "outlet's staff call `load` and `depart`, the receiving outlet's staff call `arrive` "
            "(missing crates and expiry recalculation included). List them with "
            "`GET /transfers?type=OUTLET_TRANSFER&status=READY`. DC staff cannot move an outlet's stock "
            "(403 `FORBIDDEN`).")

    st += h1("B4. Impact Dashboard and waste (HEAD_OFFICE)")
    st += table(["UI element", "Call"], [
        ["Run simulation button", "`POST /sim/run` `{seed, scenario}`"],
        ["Three-arm comparison (FIFO / plain FEFO / Neuro)", "`GET /reports/impact?scenario=main`"],
        ["Waste table and chart", "`GET /reports/waste?start=&end=&group_by=&site_id=`"],
        ["ERP vs Neuro stock", "`GET /reports/reconciliation`"],
    ], [92, 86])
    st += x.show("sim_run", title="Run a simulation (a fraction of a second, never touches real stock)",
                 max_list=3)
    st += x.show("impact", title="Impact report", request=False, max_list=3)
    st += bullets([
        "**These numbers are modelled, not measured:** label them \"simulated\". If `param_set_status` is "
        "`DRAFT`, label them **PROVISIONAL**.",
        "`runs: 0` with a `note` means nobody has run a simulation yet: show a \"Run simulation\" button. Run "
        "several seeds (1 to 5) for a meaningful average; the report uses the latest run per seed.",
        "Scenarios: `main` and `manager_sensitivity` (managers follow fewer calls).",
    ])
    st += x.show("waste", title="Waste report", request=False)
    st += p("Value is at cost; `waste_rate = total_value / received_value` (perishable stock received in "
            "the same window). Defaults: last 28 days, weekly (weeks start Monday, days are Dhaka days).")
    st += x.show("reconciliation", title="ERP vs Neuro stock", request=False)

    st += h1("B5. Delivery exceptions (DC_MANAGER)")
    st += table(["UI element", "Call"], [
        ["Exceptions list", "`GET /reports/delivery-exceptions?start=&end=&include_no_list=`"],
        ["Acknowledge", "`POST /delivery-discrepancies/{id}/acknowledge` `{\"note\": \"credit note requested\"}`"],
    ], [92, 86])
    st += x.show("exceptions", request=False)
    st += p("Rows have `match_status`, `expected_qty`, `received_qty`, `status` (`OPEN` or `ACKNOWLEDGED`) and "
            "`discrepancy_id`. Acknowledging twice answers 409.")

    st += h1("B6. Account: password and user administration")
    st += h2("Every user")
    st += table(["UI element", "Call"], [
        ["Change password screen (forced when `must_change_password` is true)", "`POST /auth/change-password`"],
        ["Who am I (profile, reload)", "`GET /auth/me`"],
    ], [92, 86])
    st += x.show("me", request=False)
    st += p("`POST /auth/change-password` takes `{current_password, new_password}` and returns the same body as "
            "login with a **fresh token**: use it from then on (the old one stops working). The new password "
            "needs 8 or more characters, must differ from the current one and cannot be `123456`; a weak one "
            "is 422 with the reason in `detail`. A wrong current password is 401. There is no self-service "
            "email reset: a head office user resets it.")
    st += h2("User administration (HEAD_OFFICE)")
    st += table(["UI element", "Call"], [
        ["Users table", "`GET /users?role=&site_id=&active=`"],
        ["Add user", "`POST /users`"],
        ["Edit, disable / enable", "`PATCH /users/{id}` (`name, email, role, site_id, is_active`)"],
        ["Reset password / unlock", "`POST /users/{id}/reset-password` `{}`"],
    ], [92, 86])
    st += x.show("users", title="Users table", request=False, max_list=2)
    st += x.show("user_create", title="Add a user")
    st += bullets([
        "Roles must fit the site: DC roles need a DC site, outlet roles an outlet (use `GET /sites`), "
        "HEAD_OFFICE has no site. Email and name must be unused. Both come back as 422 with the reason.",
        "The password defaults to 123456 and the user must change it at first login.",
        "Changing role, site or active status, resetting a password, or disabling an account **signs that "
        "user out immediately**.",
        "You cannot change your own role, site or active status. Show a lock icon when `locked_until` is "
        "set (five wrong passwords); a reset unlocks it.",
    ])

    st += h1("B7. Demo controls and the status chip")
    st += table(["UI element", "Call", "Who"], [
        ["Advance time", "`POST /demo/clock` `{\"hours\": 24}`", "HEAD_OFFICE"],
        ["Reset the demo (confirm dialog)", "`POST /demo/reset` `{\"confirm\": true}`", "HEAD_OFFICE"],
        ["Status chip / popover", "`GET /system/status`", "any logged-in role"],
    ], [60, 80, 38])
    st += x.show("clock_advance", title="Advance the demo clock")
    st += p("Advancing time also **re-ages stock and re-runs risk and recommendations** (crossing 00:30 Dhaka "
            "runs the nightly jobs): this is how to demo stock ageing on the shelf.")
    st += note("`POST /demo/reset` **wipes every table** and reloads the demo data, with the clock back at today "
               "08:00 Dhaka and the demo accounts back on password 123456. It only works on the demo clock "
               "(409 `INVALID_STATE` otherwise). Use a confirmation dialog.")
    st += x.show("status", title="Status chip", request=False, max_list=3)
    st += p("`fallbacks_active` is a list of plain sentences (\"Decision agent not connected: simple rules choose "
            "recommendations\", \"2 POS/ERP event(s) need a person to clear them\"). Show them in a small popover so "
            "people can see when the system runs in a reduced mode.")

    st += h1("B8. POS / ERP imports (HEAD_OFFICE)")
    st += p("For an admin screen that connects a POS or ERP by CSV (including Odoo exports). Three steps per source "
            "system (`pos`, `erp`, `odoo`, any name), in this order:")
    st += table(["Step", "Calls"], [
        ["1. ID mappings: which of our outlets, products and suppliers the source's ids mean",
         "`PUT /connect/id-mappings/{source}/{entity}` `{external_id, internal_ref}`; `GET` lists, `DELETE ...?external_id=` removes; "
         "bulk: `POST /connect/id-mappings/{source}/{entity}/csv` (columns `external_id,internal_ref`). `entity` is "
         "`site`, `product` or `supplier`."],
        ["2. Column mapping and read options",
         "`PUT /connect/csv-mappings/{source}/{entity}` `{columns, options}`; `GET` prefills the screen; `DELETE` forgets. "
         "`options`: `fill_down`, `number_lines`, `assume_timezone`."],
        ["3. Upload", "`POST /connect/csv/{entity}?source_system=odoo` with the raw CSV; result `{rows_ok, rows_failed, "
                      "duplicates, errors[]}`; re-uploading is safe."],
    ], [60, 118])
    st += bullets([
        "Unmapped ids fail that row and are never guessed. Good rows still go in; list `errors` row by row.",
        "Timestamps with no timezone are read as Dhaka time unless the mapping says otherwise; the mapping response's "
        "`timezone_in_effect` shows what will be used (show it beside the file picker).",
        "`GET /connect/events?status=FAILED` or `DEAD_LETTER` lists inbound POS/ERP messages that failed: useful for an "
        "integration-health panel.",
        "`/connect/webhook/{source}` and `/connect/rest/{source}/{entity}` are for the POS/ERP systems, **not for the browser**.",
    ])

    # ================================================================ PART C
    st += [PageBreak(), Spacer(1, 50 * mm), Paragraph("Part C", S["part"]),
           Paragraph("Reference", ParagraphStyle("pc", parent=S["h1"], fontSize=18)),
           *p("Every endpoint with the roles allowed to call it, then the known gaps."), PageBreak()]
    st += h1("C1. All endpoints and who can call them")
    rows = endpoint_index()
    st += table(["Method", "Path (under /api/v1)", "Who", "What"], rows, [15, 66, 46, 51], method_col=0)
    st += h1("C2. Known gaps and notes")
    st += bullets([
        "**Offline replay is not built yet.** There is no `Idempotency-Key` support and scans carry server time, "
        "not device time. Until then, do not blindly auto-retry a failed write: check the state first.",
        "**No SSO and no emailed password reset.** A head office user resets passwords.",
        "The \"Demand Forecasting\" tile has no endpoint.",
        "The design's \"Cartons: 20 / 4\" month counts are **cartons** and must add up to the line's cartons.",
        "The science behind shelf-life estimates and the simulation uses placeholder numbers until the team supplies "
        "sourced values: results are PROVISIONAL.",
    ])
    return st


def main() -> None:
    examples = asyncio.run(capture())
    story = build_story(examples)
    doc = Guide(OUT)
    doc.multiBuild(story)
    print(f"wrote {OUT} ({OUT.stat().st_size // 1024} KB)")


if __name__ == "__main__":
    main()
