"""The three chart specifications and the geometric defect checker.

Specifications (declared in DESIGN-r1.md before any chart was scored; plain first drafts, library defaults throughout:
default figure size and resolution, default fonts, no layout call, no label rotation, no manual limits):
  bar    cross-section at the latest period: ax.bar(category names, values); title = table title;
         x label = the category dimension's name; y label = the unit.
  line   one series (the first category with enough periods) over its periods, dates parsed: ax.plot(dates, values);
         title = table title; x label "Reference period"; y label = the unit.
  lines  up to 5 series, one line each with its category name as the legend label, ax.legend() at its default place;
         same title and labels as line.

Defects (the truth; computed from the renderer's own text boxes, never from a person's reading):
  overlap  two visible text boxes intersect by at least MIN_PX pixels in width AND in height, measured inside the
           image. "Clear" when the intersection covers at least CLEAR_FRAC of the smaller box.
  clipped  a visible text box extends past the image edge by at least MIN_PX pixels on any side. "Clear" when at
           least CLEAR_FRAC of the box's area lies outside the image.
  ink      secondary measure, for each overlapping pair: the number of pixels where both texts' glyphs are drawn
           (alpha above INK_ALPHA when each text is drawn alone).
Visible text = title, axis labels, the tick labels matplotlib draws, offset text, legend entries and legend title,
each only when non-empty.
"""
import datetime
import hashlib
import io
import itertools

import matplotlib

matplotlib.use("Agg")
matplotlib.rcdefaults()
import numpy as np  # noqa: E402
from matplotlib.backends.backend_agg import FigureCanvasAgg  # noqa: E402
from matplotlib.figure import Figure  # noqa: E402

MIN_PX = 2.0
CLEAR_FRAC = 0.20
INK_ALPHA = 40
SPECS = ("bar", "line", "lines")


def _date(s):
    return datetime.date.fromisoformat(s[:10])


def build(spec, ext):
    """Return a matplotlib Figure for one chart spec drawn from one table extract."""
    assert spec in SPECS
    fig = Figure()
    FigureCanvasAgg(fig)
    ax = fig.subplots()
    if spec == "bar":
        bars = ext["cross_section"]["bars"]
        ax.bar([b[0] for b in bars], [b[1] for b in bars])
        ax.set_xlabel(ext["category_dimension"])
        ax.set_ylabel(ext["cross_section"]["unit"])
    elif spec == "line":
        pts = ext["series"]["points"]
        ax.plot([_date(p[0]) for p in pts], [p[1] for p in pts])
        ax.set_xlabel("Reference period")
        ax.set_ylabel(ext["series"]["unit"])
    else:
        for ln in ext["multi"]["lines"]:
            ax.plot([_date(p[0]) for p in ln["points"]], [p[1] for p in ln["points"]], label=ln["member"])
        ax.legend()
        ax.set_xlabel("Reference period")
        ax.set_ylabel(ext["multi"]["unit"])
    ax.set_title(ext["title"])
    return fig


def visible_texts(fig):
    """Every visible text artist with its box in image pixels (origin bottom left), after a full draw."""
    fig.canvas.draw()
    r = fig.canvas.get_renderer()
    out = []

    def add(kind, t):
        if t is None or not t.get_visible() or not t.get_text().strip():
            return
        rot = t.get_rotation() % 360
        assert rot in (0, 90, 270), f"rotated text {rot} would need a polygon test"
        bb = t.get_window_extent(r)
        out.append({"kind": kind, "text": t.get_text(), "box": [float(bb.x0), float(bb.y0), float(bb.x1), float(bb.y1)], "_artist": t})

    for ax in fig.axes:
        for t in (ax.title, ax._left_title, ax._right_title):
            add("title", t)
        add("xlabel", ax.xaxis.label)
        add("ylabel", ax.yaxis.label)
        for axis, name in ((ax.xaxis, "xtick"), (ax.yaxis, "ytick")):
            for tick in axis._update_ticks():  # exactly the ticks matplotlib draws
                if tick.label1.get_visible():
                    add(name, tick.label1)
                if tick.label2.get_visible():
                    add(name, tick.label2)
            add("offset", axis.get_offset_text())
        leg = ax.get_legend()
        if leg is not None:
            for t in leg.get_texts():
                add("legend", t)
            add("legend_title", leg.get_title())
    return out


def _clip(box, w, h):
    return [max(box[0], 0), max(box[1], 0), min(box[2], w), min(box[3], h)]


def _area(b):
    return max(0.0, b[2] - b[0]) * max(0.0, b[3] - b[1])


def measure(texts, w, h):
    """Apply the declared defect definitions to a list of text boxes on a w x h image."""
    overlaps, clips = [], []
    for i, t in enumerate(texts):
        b = t["box"]
        out = float(max(-b[0], -b[1], b[2] - w, b[3] - h, 0.0))
        if out >= MIN_PX:
            a = _area(b)
            frac = float(1 - _area(_clip(b, w, h)) / a) if a else 1.0
            clips.append({"i": i, "past_edge_px": round(out, 2), "outside_frac": round(frac, 4),
                          "clear": bool(frac >= CLEAR_FRAC)})
    for i, j in itertools.combinations(range(len(texts)), 2):
        a, b = _clip(texts[i]["box"], w, h), _clip(texts[j]["box"], w, h)
        iw = float(min(a[2], b[2]) - max(a[0], b[0]))
        ih = float(min(a[3], b[3]) - max(a[1], b[1]))
        if iw >= MIN_PX and ih >= MIN_PX:
            small = min(_area(texts[i]["box"]), _area(texts[j]["box"]))
            frac = iw * ih / small if small else 1.0
            overlaps.append({"i": i, "j": j, "w_px": round(iw, 2), "h_px": round(ih, 2), "frac": round(frac, 4),
                             "clear": bool(frac >= CLEAR_FRAC)})
    return {"overlap": bool(overlaps), "clipped": bool(clips),
            "overlap_clear": any(o["clear"] for o in overlaps), "clipped_clear": any(c["clear"] for c in clips),
            "overlaps": overlaps, "clips": clips}


def ink_overlap(fig, ta, tb):
    """Pixels where both texts' glyphs are drawn, each text drawn alone on a cleared canvas."""
    r = fig.canvas.get_renderer()
    masks = []
    for t in (ta, tb):
        r.clear()
        t.draw(r)
        masks.append(np.asarray(r.buffer_rgba())[..., 3] > INK_ALPHA)
    return int(np.logical_and(masks[0], masks[1]).sum())


def render(spec, ext):
    """Build, measure and draw one chart. Returns (png bytes, geometry record)."""
    fig = build(spec, ext)
    w, h = fig.canvas.get_width_height()
    texts = visible_texts(fig)
    m = measure(texts, w, h)
    buf = io.BytesIO()
    fig.savefig(buf, format="png", metadata={"Software": None})
    png = buf.getvalue()
    for o in m["overlaps"]:
        o["ink_px"] = ink_overlap(fig, texts[o["i"]]["_artist"], texts[o["j"]]["_artist"])
    m["overlap_ink"] = any(o["ink_px"] > 0 for o in m["overlaps"])
    rec = {"spec": spec, "productId": ext["productId"], "width": w, "height": h,
           "png_sha256": hashlib.sha256(png).hexdigest(),
           "texts": [{"kind": t["kind"], "text": t["text"], "box": [round(v, 2) for v in t["box"]]} for t in texts],
           **m}
    return png, rec
