"""Run the real flows against the app (in process) and keep every request and response.

Used by build_frontend_pdf.py so the examples in the PDF are what the API really returns.
Needs a migrated, seeded database (DATABASE_URL), the demo (SIM) clock, and it WIPES that
database first (POST /demo/reset), so point it at a throwaway one.

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

os.environ.setdefault("PASSWORD_HASH_ITERATIONS", "1000")  # the examples do not need slow hashes

from httpx import ASGITransport, AsyncClient  # noqa: E402

from app.main import app  # noqa: E402

API = "/api/v1"


class Recorder:
    def __init__(self, client: AsyncClient) -> None:
        self.c = client
        self.ex: dict[str, dict] = {}

    async def call(self, label: str, method: str, path: str, *, token: str | None = None,
                   json: dict | None = None, params: dict | None = None, keep: bool = True,
                   content: bytes | None = None, ctype: str | None = None):
        headers = {"Authorization": f"Bearer {token}"} if token else {}
        if ctype:
            headers["content-type"] = ctype
        r = await self.c.request(method, f"{API}{path}", headers=headers, json=json,
                                 params=params, content=content)
        is_pdf = r.headers.get("content-type", "").startswith("application/pdf")
        body = ({"_binary": f"PDF, {len(r.content)} bytes"} if is_pdf else
                (r.json() if r.content else None))
        if keep:
            self.ex[label] = {"method": method, "path": path, "params": params, "body": json,
                              "status": r.status_code, "response": body}
        assert r.status_code < 400, (label, r.status_code, r.text)
        return body


async def login(rec: Recorder, who: str, label: str | None = None) -> dict:
    body = await rec.call(label or f"login_{who}", "POST", "/auth/login", json={
        "email": f"{who}@neuro.local", "password": "123456"}, keep=label is not None)
    return body


async def capture() -> dict[str, dict]:
    async with AsyncClient(transport=ASGITransport(app=app), base_url="http://t") as client:
        rec = Recorder(client)
        ho = await login(rec, "head_office", "login")
        await rec.call("reset", "POST", "/demo/reset", token=ho["access_token"],
                       json={"confirm": True}, keep=False)
        ho = await login(rec, "head_office")
        dcs, dcm = await login(rec, "dc_staff"), await login(rec, "dc_manager")
        osf, omg = await login(rec, "outlet_staff"), await login(rec, "outlet_manager")
        t_ho, t_dcs, t_dcm = ho["access_token"], dcs["access_token"], dcm["access_token"]
        t_osf, t_omg = osf["access_token"], omg["access_token"]

        await rec.call("me", "GET", "/auth/me", token=t_omg)
        # --- catalogue
        cats = await rec.call("categories", "GET", "/product-categories", token=t_dcs)
        products = await rec.call("products", "GET", "/products", token=t_dcs,
                                  params={"search": "tomato"})
        all_products = (await rec.call("products_all", "GET", "/products", token=t_dcs,
                                       params={"limit": 200}, keep=False))
        by_sku = {p["sku"]: p for p in all_products}
        dairy = next(c["id"] for c in cats if c["name"] == "Dairy")
        await rec.call("product_create", "POST", "/products", token=t_dcm, json={
            "sku": "KHR200", "barcode": "8941100000012", "name": "Khir 200g",
            "category_id": dairy, "uom": "UNIT", "kind": "PACKAGED", "mrp": "95.00",
            "list_price": "90.00", "unit_cost": "68.00"})
        suppliers = await rec.call("suppliers", "GET", "/suppliers", token=t_dcs)
        sites = await rec.call("sites", "GET", "/sites", token=t_dcs, params={"type": "OUTLET"})
        locs = await rec.call("locations", "GET", "/locations", token=t_dcs)
        chilled = next(x["id"] for x in locs if x["storage_type"] == "CHILLED")
        ambient = next(x["id"] for x in locs if x["storage_type"] == "AMBIENT")
        dc_site = next(x["site_id"] for x in locs)
        dhn = next(s for s in sites if s["code"] == "OUT-DHN")
        supplier = suppliers[0]["id"]
        milk, tom = by_sku["MLK1L"]["id"], by_sku["TOM"]["id"]

        # --- expected delivery (Upload PO)
        now = (await rec.call("clock_now", "GET", "/system/status", token=t_ho,
                              keep=False))["now"]
        today = now[:10]
        ed = await rec.call("expected_create", "POST", "/expected-deliveries", token=t_ho, json={
            "supplier_id": supplier, "site_id": dc_site, "expected_date": today,
            "po_ref": "PO-4471", "lines": [{"product_id": milk, "expected_qty": "24"},
                                           {"product_id": tom, "expected_qty": "18.5"}]})
        await rec.call("expected_list", "GET", "/expected-deliveries", token=t_dcs,
                       params={"status": "OPEN"})

        # --- Delivery Receiving
        receipt = await rec.call("receipt_create", "POST", "/receipts", token=t_dcs, json={
            "supplier_id": supplier, "po_ref": "PO-4471", "expected_delivery_id": ed["id"]})
        rid = receipt["id"]
        l_milk = await rec.call("line_packaged", "POST", f"/receipts/{rid}/lines", token=t_dcs,
                                json={"product_id": milk, "qty": "24", "cartons": 3})
        l_tom = await rec.call("line_loose", "POST", f"/receipts/{rid}/lines", token=t_dcs,
                               json={"product_id": tom, "qty": "18.5"})
        year, month = int(today[:4]), int(today[5:7])
        nxt = f"{year + (month == 12)}-{(month % 12) + 1:02d}"
        await rec.call("sample_1", "POST", f"/receipt-lines/{l_milk['id']}/date-samples",
                       token=t_dcs, json={"printed_date": f"{today[:7]}-28", "method": "TYPED"})
        await rec.call("sample_2", "POST", f"/receipt-lines/{l_milk['id']}/date-samples",
                       token=t_dcs, json={"printed_date": f"{nxt}-05", "method": "TYPED"})
        confirm = await rec.call("receipt_confirm", "POST", f"/receipts/{rid}/confirm",
                                 token=t_dcs, json={
            "confirmed_by": dcs["user_id"],
            "storage_locations": [
                {"line_id": l_milk["id"], "location_id": chilled, "month_splits": [
                    {"month": today[:7], "cartons": 2}, {"month": nxt, "cartons": 1}]},
                {"line_id": l_tom["id"], "location_id": ambient,
                 "crates": [{"weight_kg": "12.5"}, {"weight_kg": "6"}]}]})
        await rec.call("labels", "GET", f"/receipts/{rid}/labels", token=t_dcs,
                       params={"per_row": 4})
        batches = confirm["batches"]

        # --- Dispatch Delivery
        body = {"outlet_site_id": dhn["id"], "items": [
            {"product_id": tom, "qty": "18.5"}, {"product_id": milk, "qty": "24"}]}
        await rec.call("dispatch_preview", "POST", "/transfers/dispatch/preview", token=t_dcs,
                       json=body)
        tr = await rec.call("dispatch_create", "POST", "/transfers/dispatch", token=t_dcs,
                            json=body)
        codes = [ln["crate_barcode"] for m in tr["moves"] for ln in m["lines"]]
        await rec.call("dispatch_load", "POST", f"/transfers/{tr['id']}/load", token=t_dcs,
                       json={"scans": [{"code": c} for c in codes]})
        await rec.call("dispatch_depart", "POST", f"/transfers/{tr['id']}/depart", token=t_dcs,
                       json={"vehicle_type": "OPEN"})
        await rec.call("dispatch_approve", "POST", f"/transfers/{tr['id']}/approve",
                       token=t_dcm)
        await rec.call("clock_advance", "POST", "/demo/clock", token=t_ho, json={"hours": "5"})
        # leave one crate behind to show MISSING handling
        arrive_codes = codes[:-1] if len(codes) > 2 else codes
        await rec.call("arrive", "POST", f"/transfers/{tr['id']}/arrive", token=t_osf,
                       json={"scans": [{"code": c} for c in arrive_codes]})
        await rec.call("transfers_in_transit", "GET", "/transfers", token=t_osf,
                       params={"status": "DONE", "type": "DISPATCH"})

        # --- scan, batches
        await rec.call("scan_crate", "GET", f"/scan/{codes[0]}", token=t_osf)
        await rec.call("scan_product", "GET", f"/scan/{by_sku['MLK1L']['barcode']}", token=t_osf)
        first_batch = batches[0]["id"]
        await rec.call("batch_detail", "GET", f"/batches/{first_batch}", token=t_osf)
        await rec.call("batch_history", "GET", f"/batches/{first_batch}/history", token=t_osf)
        await rec.call("batches_list", "GET", "/batches", token=t_omg, params={"limit": 5})

        # --- outlet today, decide, write-off
        today_list = await rec.call("today", "GET", "/today", token=t_omg,
                                    params={"site_id": omg["site_id"]})
        recs = today_list["recommendations"]
        if recs:
            sale = next((r for r in recs if r["action_type"] == "CONSIDER_SALE"), None)
            if sale:
                await rec.call("decide_followed", "POST",
                               f"/recommendations/{sale['id']}/decide", token=t_omg,
                               json={"decision": "FOLLOWED", "applied_price": "64.00"})
            rest = [r for r in recs if not sale or r["id"] != sale["id"]]
            if rest:
                await rec.call("decide_dismissed", "POST",
                               f"/recommendations/{rest[0]['id']}/decide", token=t_omg,
                               json={"decision": "DISMISSED", "dismiss_reason": "Not needed"})
        await rec.call("recommendations_history", "GET", "/recommendations", token=t_omg,
                       params={"limit": 3})
        tom_batch = next(b for b in batches if b["product_name"] == "Tomato")
        await rec.call("write_off", "POST", f"/batches/{tom_batch['id']}/write-off", token=t_osf,
                       json={"reason": "Spoiled in the crate", "qty": "2"})

        # --- reports and head office
        for seed in (1, 2, 3):
            out = await rec.call("sim_run", "POST", "/sim/run", token=t_ho,
                                 json={"seed": seed, "scenario": "main"}, keep=seed == 1)
        await rec.call("impact", "GET", "/reports/impact", token=t_ho)
        await rec.call("waste", "GET", "/reports/waste", token=t_ho,
                       params={"group_by": "daily"})
        await rec.call("exceptions", "GET", "/reports/delivery-exceptions", token=t_dcm)
        await rec.call("reconciliation", "GET", "/reports/reconciliation", token=t_ho)
        await rec.call("status", "GET", "/system/status", token=t_ho)
        await rec.call("users", "GET", "/users", token=t_ho)
        await rec.call("user_create", "POST", "/users", token=t_ho, json={
            "name": "rahim_dc", "email": "rahim@yourcompany.com", "role": "DC_STAFF",
            "site_id": dc_site})
        ex = rec.ex
        ex["_meta"] = {"today": today, "milk_id": milk, "tomato_id": tom, "outlet": dhn,
                       "receipt_id": rid, "transfer_id": tr["id"], "crates": codes,
                       "sim_note": out["status"]}
        return ex
