"""Draw the 1200x675 share card for the refused-edit demo from its results.

Every number and code on the card is read from the results dict run_demo.py builds.
"""

import os
from pathlib import Path

from PIL import Image, ImageDraw, ImageFont

SITE = Path(__file__).resolve().parents[3]
FONT = Path(os.environ.get("CARD_FONT") or SITE / "app" / "fonts" / "archivo-variable.woff2")

BG = "#050506"
PANEL = "#111113"
RULE = "#2a2a2d"
INK = "#eef1f5"
MUTED = "#9a9aa0"
FAIL = "#fb7185"
PASS = "#34d399"
SIZE = (1200, 675)


def font(size: int, weight: int = 500, width: int = 100) -> ImageFont.FreeTypeFont:
    f = ImageFont.truetype(str(FONT), size)
    f.set_variation_by_axes([weight, width])
    return f


def thousands(value: float) -> str:
    return f"{value:,.0f}"


def short(digest: str) -> str:
    return f"{digest[:10]}...{digest[-6:]}"


def a1(address: str, sheet_ids: dict[str, str]) -> str:
    """sheet:#2/cell:B7 -> Summary!B7; other addresses stay as they are."""
    sheet, _, rest = address.partition("/cell:")
    return f"{sheet_ids[sheet]}!{rest}" if rest and sheet in sheet_ids else address


def summary(verdict: dict, sheet_ids: dict[str, str]) -> str:
    kind = verdict["kind"]
    violations = verdict.get("violations", [])
    if kind == "only-changes":
        return f"{len(violations)} changes outside the declared cells"
    if kind == "no-new-errors":
        return "new error at " + ", ".join(a1(v, sheet_ids) for v in violations)
    return verdict.get("detail", "")


def draw(results: dict, out: Path) -> None:
    img = Image.new("RGB", SIZE, BG)
    d = ImageDraw.Draw(img)
    bad, fixed, lib = results["bad"], results["fixed"], results["openpyxl"]
    sheet_ids = results["fixture"]["sheet_ids"]
    margin = 64

    d.text((margin, 52), "WOLFSDK  /  EXAMPLES  /  REFUSED EDIT", font=font(17, 600, 112), fill=MUTED)
    d.text((margin, 92), "Ask Wolf for a broken edit.", font=font(54, 800, 100), fill=INK)
    d.text((margin, 156), f"Get exit {bad['exit_code']} and an unchanged file.", font=font(54, 800, 100), fill=INK)

    # Terminal panel: the refused request, its verdicts, the digests, the repaired request.
    left, top, right, bottom = margin, 252, 772, 600
    d.rounded_rectangle((left, top, right, bottom), radius=14, fill=PANEL, outline=RULE, width=2)
    mono = font(20, 500, 90)
    bold = font(20, 700, 90)
    x, y, step = left + 28, top + 24, 34
    d.text((x, y), f"$ wolf transact --request {bad['request']}", font=mono, fill=MUTED)
    y += step
    d.text((x, y), f"exit {bad['exit_code']}   {bad['error_codes'][0]}   committed: false", font=bold, fill=FAIL)
    y += step
    for verdict in bad["verdicts"]:
        if verdict.get("kind") in {"address-resolution", "parts-preserved"}:
            continue
        failed = verdict["verdict"] == "failed"
        d.text((x, y), "FAIL" if failed else "PASS", font=bold, fill=FAIL if failed else PASS)
        d.text((x + 70, y), verdict["id"], font=mono, fill=INK)
        d.text((x + 190, y), summary(verdict, sheet_ids), font=mono, fill=MUTED)
        y += step
    y += 6
    d.text((x, y), "sha256 before", font=mono, fill=MUTED)
    d.text((x + 190, y), short(bad["input_sha256_before"]), font=mono, fill=INK)
    y += step
    d.text((x, y), "sha256 after", font=mono, fill=MUTED)
    d.text((x + 190, y), short(bad["input_sha256_after"]), font=mono, fill=INK)
    d.text((x + 470, y), "unchanged" if bad["input_unchanged"] else "CHANGED", font=bold, fill=PASS)
    y += step + 6
    passed = sum(1 for v in fixed["verdicts"] if v["verdict"] == "passed")
    d.text((x, y), f"$ wolf transact --request {fixed['request']}", font=mono, fill=MUTED)
    y += step
    d.text(
        (x, y),
        f"exit {fixed['exit_code']}   committed: true   {passed} of {len(fixed['verdicts'])} checks passed",
        font=bold,
        fill=PASS,
    )

    # Contrast panel: the same faulty edit saved by openpyxl, then recalculated by LibreOffice.
    cl, ct, cr, cb = 804, 252, SIZE[0] - margin, 600
    d.rounded_rectangle((cl, ct, cr, cb), radius=14, fill=BG, outline=RULE, width=2)
    cx, cy = cl + 26, ct + 24
    d.text((cx, cy), "Same edit, openpyxl", font=font(22, 700, 100), fill=INK)
    cy += 38
    d.text((cx, cy), f"Saved. Exit {lib['exit_code']}, {len(lib['warnings'])} warnings.", font=font(19, 500, 100), fill=MUTED)
    cy += 46
    after = lib["values_after_recalc"]
    q2_before = results["fixture"]["values"]["regions_q2_total"]["number"]
    rows = [
        ("Q3 total against ledger", f"{thousands(after['regions_q3_total'])} / {thousands(after['ledger_control'])}"),
        ("Variance cell", str(after["summary_variance"])),
        ("Q2 total", f"{thousands(q2_before)} to {thousands(after['regions_q2_total'])}"),
    ]
    for label, value in rows:
        d.text((cx, cy), label, font=font(18, 500, 100), fill=MUTED)
        cy += 25
        d.text((cx, cy), value, font=font(27, 700, 100), fill=FAIL)
        cy += 46
    d.text((cx, cb - 36), "values after LibreOffice recalculation", font=font(15, 500, 100), fill=MUTED)

    d.text((margin, SIZE[1] - 52), "wolfsdk.com/examples/refused-edit", font=font(18, 600, 100), fill=MUTED)
    d.text(
        (SIZE[0] - margin, SIZE[1] - 52),
        f"{results['environment']['wolf_version'].split(' (')[0]}, synthetic data",
        font=font(16, 500, 100),
        fill=MUTED,
        anchor="ra",
    )
    img.save(out, optimize=True)
