"""
stats_service.py — the numbers of the dashboards (client brief 2026-10-21, sheet 8): the recap by PRODUCT and the
statistics by CLASS, plus the end-of-operation PDF statement.

Only paid orders count (the caller passes them). Two rules come straight from the brief:

  * The recap by product is built from what the orders themselves say (`format_id` + the names stored on each line),
    so a product added, renamed, hidden or deleted later shows up — or stays — with no development, and the product
    lines always add up to the gross sales. The three fixed lines (paper / AI / digital) are gone: an AI photo is the
    same product at the same price.
  * Siblings. A family attached to two classes counts as a BUYER in each of them. A solo photo's revenue goes to the
    class of the child (`origin_class`, stored on the line when the order is made); the sibling photo, which belongs
    to no class, is split equally between the classes of the family. The rate of a class is the families that ordered
    divided by the cards created in it.
"""
import io
import json
import logging
from pathlib import Path
from typing import Optional

from PIL import Image, ImageDraw, ImageFont

from core import config
from services import format_service, shipping_service

log = logging.getLogger("meeconic.stats")

_FONTS = Path(__file__).resolve().parent.parent / "fonts"
_BUILTIN_NAMES = {b[0]: dict(zip(("fr", "en", "es"), b[4])) for b in format_service.BUILTINS}


def ht(ttc: float) -> float:
    """Amount without VAT from a TTC one: the families pay TTC, the school's share is a % of the HT (client 2026-11).
    HT = TTC / 1.20, NOT TTC - 20 % (that would be 1296 for 1620; 1296 x 1.20 is not 1620). Totals are computed from the
    total TTC, not summed from rounded rows, so a row may differ from the total by a cent."""
    return round(ttc / (1 + config.VAT_PCT / 100), 2)


def school_share(gross_ttc: float, share_pct: float) -> float:
    return round(ht(gross_ttc) * share_pct / 100, 2)


def _names(line: dict) -> dict:
    n = line.get("format_names")
    if n:
        return {lg: n.get(lg) or n.get("fr") or line.get("format_label", "") for lg in ("fr", "en", "es")}
    if line.get("format_id") in _BUILTIN_NAMES:
        return _BUILTIN_NAMES[line["format_id"]]
    label = line.get("format_label") or line.get("format_id", "")
    return {"fr": label, "en": label, "es": label}


def product_recap(rows) -> dict:
    """One row per product ever sold: quantity and sales. `gross` is what the paid orders add up to."""
    prods: dict[str, dict] = {}
    gross = 0.0
    for r in rows:                                          # oldest first: the latest name wins
        gross += shipping_service.goods_total(r)            # the delivery fee is no sale: outside the school's share
        for it in json.loads(r["items_json"] or "[]"):
            p = prods.setdefault(it["format_id"], {"format_id": it["format_id"], "quantity": 0, "sales": 0.0})
            p["quantity"] += it["quantity"]
            p["sales"] += it["unit_price"] * it["quantity"]
            for lg, name in _names(it).items():
                p[f"name_{lg}"] = name
    out = sorted(prods.values(), key=lambda p: (-p["sales"], p["format_id"]))
    for p in out:
        p["sales"] = round(p["sales"], 2)
        p["sales_ht"] = ht(p["sales"])
    return {"products": out, "gross": round(gross, 2), "gross_ht": ht(gross)}


def class_stats(conn, sid: str, rows) -> dict[str, dict]:
    """{class name: {cards, buyers, orders, sales, prints}} for the school's real classes (not the Siblings folder)."""
    sib = {r["name"] for r in conn.execute("SELECT name FROM school_classes WHERE school_id=? AND kind='siblings'", (sid,))}
    names = [r["name"] for r in conn.execute("SELECT name FROM school_classes WHERE school_id=? AND kind != 'siblings'", (sid,))]
    out = {n: {"cards": 0, "buyers": set(), "orders": 0, "sales": 0.0, "prints": 0} for n in names}
    fam_classes: dict[str, list[str]] = {}
    for r in conn.execute("SELECT s.family_code, s.class_name FROM students s JOIN families f ON f.code=s.family_code "
                          "WHERE f.school_id=? ORDER BY s.id", (sid,)):
        if r["class_name"] in out:
            fam_classes.setdefault(r["family_code"], []).append(r["class_name"])
    # Cards created = one per photo in the class (its folders); a class with no folder yet (cards typed by hand)
    # counts its families.
    folders = {r["class_name"]: r["n"] for r in conn.execute(
        "SELECT class_name, COUNT(*) AS n FROM child_folders WHERE school_id=? GROUP BY class_name", (sid,))}
    attached: dict[str, int] = {}
    for classes in fam_classes.values():
        for c in classes:
            attached[c] = attached.get(c, 0) + 1
    for n in names:
        out[n]["cards"] = folders.get(n) or attached.get(n, 0)

    for r in rows:
        family = fam_classes.get(r["family_code"], [])
        chosen = r["class_name"] if r["class_name"] in out else None
        targets = family or ([chosen] if chosen else [])
        receiving: set[str] = set()
        for it in json.loads(r["items_json"] or "[]"):
            amount = it["unit_price"] * it["quantity"]
            # A pack hands out what is in it (its prints), like the order's "to print" (order_service.print_units).
            comps = it.get("components") or []
            printed = (it["quantity"] * sum(c["qty"] for c in comps if c.get("physical", True)) if comps
                       else it["quantity"] if it.get("physical", not it.get("digital", False)) else 0)
            origin = it.get("origin_class")
            if origin in out and not it.get("origin_sibling"):
                dest = [origin]                                  # a solo photo: the child's class
            elif not it.get("origin_class") and chosen:
                dest = [chosen]                                  # an older line: the class picked at checkout
            else:
                dest = targets                                   # the sibling photo: split between the classes
            for c in dest:
                out[c]["sales"] += amount / len(dest)
                receiving.add(c)
            if dest:
                out[dest[0]]["prints"] += printed
        for c in receiving | set(targets):                       # a family of two classes is a buyer in each
            out[c]["buyers"].add(r["family_code"])
            out[c]["orders"] += 1
    for c in out.values():
        c["buyers"] = len(c["buyers"])
        c["sales"] = round(c["sales"], 2)
        c["sales_ht"] = ht(c["sales"])
        c["rate"] = round(100 * c["buyers"] / c["cards"]) if c["cards"] else 0
    return out


# ── End-of-operation statement (PDF) ────────────────────────────────────────────────────────────────

_TXT = {
    "fr": {"title": "Relevé de fin d'opération", "product": "Produit", "qty": "Qté", "sales": "Ventes", "gross": "Ventes totales TTC", "gross_ht": "Ventes totales HT", "sales_ht": "Ventes HT", "sales_ttc": "Ventes TTC",
           "share": "Part de l'école ({pct} % du HT)", "page": "Page {a}/{b}"},
    "en": {"title": "End-of-operation statement", "product": "Product", "qty": "Qty", "sales": "Sales", "gross": "Total sales incl. VAT", "gross_ht": "Total sales excl. VAT", "sales_ht": "Sales excl. VAT", "sales_ttc": "Sales incl. VAT",
           "share": "School share ({pct} % of excl. VAT)", "page": "Page {a}/{b}"},
    "es": {"title": "Resumen de fin de operación", "product": "Producto", "qty": "Cant.", "sales": "Ventas", "gross": "Ventas totales con IVA", "gross_ht": "Ventas totales sin IVA", "sales_ht": "Ventas sin IVA", "sales_ttc": "Ventas con IVA",
           "share": "Parte del colegio ({pct} % del importe sin IVA)", "page": "Página {a}/{b}"},
}
_W, _H = 1240, 1754
_ROWS = 24


def _font(kind: str, size: int):
    return ImageFont.truetype(str(_FONTS / {"regular": "Inter-Regular.ttf", "bold": "Inter-Bold.ttf",
                                            "semibold": "Inter-SemiBold.ttf"}[kind]), size)


def _eur(v: float) -> str:
    return f"{v:,.2f}".replace(",", " ").replace(".", ",") + " €"


def statement_pdf(school_name: str, recap: dict, share_pct: float, lang: str = "fr") -> bytes:
    """A4 PDF: the recap by product, the gross sales and the school's share."""
    t = _TXT.get(lang, _TXT["fr"])
    products = recap["products"]
    chunks = [products[i:i + _ROWS] for i in range(0, len(products), _ROWS)] or [[]]
    navy, grey, rule = (10, 31, 68), (91, 98, 114), (200, 204, 212)
    share = school_share(recap["gross"], share_pct)
    pages = []
    for pi, chunk in enumerate(chunks, start=1):
        img = Image.new("RGB", (_W, _H), "white")
        d = ImageDraw.Draw(img)
        d.text((70, 70), "MEECONIC", font=_font("bold", 30), fill=navy)
        d.text((70, 120), t["title"], font=_font("bold", 52), fill=navy)
        d.text((70, 200), school_name, font=_font("semibold", 32), fill=navy)
        y = 300
        for x, label in ((70, t["product"]), (640, t["qty"]), (770, t["sales_ttc"]), (990, t["sales_ht"])):
            d.text((x, y), label, font=_font("semibold", 26), fill=grey)
        d.line((70, y + 42, _W - 70, y + 42), fill=navy, width=3)
        y += 60
        body = _font("regular", 28)
        for p in chunk:
            name = p.get(f"name_{lang}") or p.get("name_fr") or p["format_id"]
            while name and d.textlength(name, font=body) > 540:
                name = name[:-2] + "…"
            d.text((70, y), name, font=body, fill=navy)
            d.text((640, y), str(p["quantity"]), font=body, fill=navy)
            d.text((770, y), _eur(p["sales"]), font=body, fill=navy)
            d.text((990, y), _eur(p["sales_ht"]), font=body, fill=navy)
            d.line((70, y + 46, _W - 70, y + 46), fill=rule, width=1)
            y += 58
        if pi == len(chunks):
            y += 30
            d.line((70, y, _W - 70, y), fill=navy, width=3)
            d.text((70, y + 20), t["gross"], font=_font("bold", 32), fill=navy)
            d.text((950, y + 20), _eur(recap["gross"]), font=_font("bold", 32), fill=navy)
            d.text((70, y + 70), t["gross_ht"], font=_font("bold", 32), fill=navy)
            d.text((950, y + 70), _eur(recap["gross_ht"]), font=_font("bold", 32), fill=navy)
            d.text((70, y + 120), t["share"].format(pct=f"{share_pct:g}"), font=_font("bold", 32), fill=navy)
            d.text((950, y + 120), _eur(share), font=_font("bold", 32), fill=navy)
        if len(chunks) > 1:
            d.text((_W - 260, _H - 90), t["page"].format(a=pi, b=len(chunks)), font=_font("regular", 24), fill=grey)
        pages.append(img)
    buf = io.BytesIO()
    pages[0].save(buf, "PDF", resolution=150, save_all=True, append_images=pages[1:], title=t["title"])
    return buf.getvalue()
