"""Draw ../figs/angle.svg and ../figs/ranking.svg from the numbers embed_search.py computes.

    uv run --no-project python make_figs.py          rewrite both figures
    uv run --no-project python make_figs.py --check  exit 1 if a figure differs from what the code draws
"""
import math
import sys
from pathlib import Path

import embed_search as es

FIGS = Path(__file__).resolve().parent.parent / "figs"
INK, GREY, ORANGE, GREEN = "#0a1626", "#44566b", "#b36200", "#00855F"
OPEN = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {w} {h}" width="{w}" height="{h}" role="img" font-family="system-ui, sans-serif" font-size="22" fill="{grey}">'

QUESTION = es.QUERIES[-1]                         # "Can I pay for delivery?" lies in the money and delivery topics only
SHOWN = {0: "repay sentence", 7: "pay-extra sentence", 4: "parcel sentence"}   # sentence index -> the short name drawn next to its arrow
ROW_NAMES = ["repay in full", "refund reaches card", "forgot password", "back to login page", "parcel ships", "shop is open",
             "opening times", "pay extra, delivery", "error E4410, payment"]
assert len(ROW_NAMES) == len(es.DOCS)


def arrow(x0, y0, x1, y1, stroke, dash=""):
    """A line from (x0, y0) to (x1, y1) with a filled head."""
    angle = math.atan2(y1 - y0, x1 - x0)
    head = [(x1, y1), (x1 - 16 * math.cos(angle - 0.4), y1 - 16 * math.sin(angle - 0.4)), (x1 - 16 * math.cos(angle + 0.4), y1 - 16 * math.sin(angle + 0.4))]
    d = f' stroke-dasharray="{dash}"' if dash else ""
    pts = " ".join(f"{x:.1f},{y:.1f}" for x, y in head)
    return [f'  <line x1="{x0:.1f}" y1="{y0:.1f}" x2="{x1 - 8 * math.cos(angle):.1f}" y2="{y1 - 8 * math.sin(angle):.1f}" stroke="{stroke}" stroke-width="4"{d}/>',
            f'  <polygon points="{pts}" fill="{stroke}"/>']


def angle_svg():
    q = es.embed(QUESTION)
    vectors = [es.embed(d) for d in es.DOCS]
    scores = {i: es.cosine(q, vectors[i]) for i in SHOWN}
    best = max(scores, key=scores.get)
    ox, oy, unit = 70.0, 340.0, 290.0                      # origin, and the length of a list of length 1
    money, delivery = es.TOPICS.index("money"), es.TOPICS.index("delivery")
    left_out = max(math.sqrt(sum(v[t] ** 2 for t in range(len(es.TOPICS)) if t not in (money, delivery))) for v in [q] + [vectors[i] for i in SHOWN])
    lines = [OPEN.format(w=620, h=380, grey=GREY),
             f"  <title>Four lists of numbers drawn as arrows in the money and delivery topics</title>",
             f"  <desc>The question &quot;{QUESTION}&quot; is an arrow. The pay-extra sentence points nearly the same way (cosine {scores[7]:.3f}), the parcel sentence points up the delivery axis (cosine {scores[4]:.3f}) and the repay sentence points along the money axis (cosine {scores[0]:.3f}). The picture leaves out the other two topics, where no arrow has more than {left_out:.2f} of its length.</desc>",
             '  <rect width="100%" height="100%" fill="#ffffff"/>',
             f'  <line x1="{ox:.0f}" y1="{oy:.0f}" x2="{ox + unit + 20:.0f}" y2="{oy:.0f}" stroke="{GREY}" stroke-width="2"/>',
             f'  <line x1="{ox:.0f}" y1="{oy:.0f}" x2="{ox:.0f}" y2="{oy - unit - 20:.0f}" stroke="{GREY}" stroke-width="2"/>',
             f'  <text x="{ox:.0f}" y="372" text-anchor="start" fill="{INK}">money topic</text>',
             f'  <text x="14" y="26" text-anchor="start" fill="{INK}">delivery topic</text>']
    lines += arrow(ox, oy, ox + q[money] * unit, oy - q[delivery] * unit, INK)
    lines.append(f'  <text x="{ox + q[money] * unit + 12:.1f}" y="{oy - q[delivery] * unit + 6:.1f}" text-anchor="start" fill="{INK}">question</text>')
    for i, name in SHOWN.items():
        v = vectors[i]
        x, y = ox + v[money] * unit, oy - v[delivery] * unit
        colour, dash = (GREEN, "") if i == best else (ORANGE, "9 7")
        lines += arrow(ox, oy, x, y, colour, dash)
        dy = 6 if v[delivery] > 0.9 else 5 if v[delivery] > 0 else -10
        lines.append(f'  <text x="{x + 12:.1f}" y="{y + dy:.1f}" text-anchor="start" fill="{INK}">{name} {scores[i]:.3f}</text>')
    lines.append("</svg>")
    return "\n".join(lines) + "\n"


def ranking_svg():
    q = es.QUERIES[0]
    words = dict(es.rank_keywords(q))
    meaning = dict(es.rank_meaning(q))
    top_words, top_meaning = es.rank_keywords(q)[0][0], es.rank_meaning(q)[0][0]
    scale = max(words.values())
    lines = [OPEN.format(w=640, h=420, grey=GREY),
             f"  <title>The same question searched by words and by meaning</title>",
             f"  <desc>For the question &quot;{q}&quot;, one bar per sentence. By words the top sentence is &quot;{es.DOCS[top_words]}&quot; with {words[top_words]} shared words, and {sum(1 for s in words.values() if s == 0)} of {len(es.DOCS)} sentences share none. By meaning the top sentence is &quot;{es.DOCS[top_meaning]}&quot; with a cosine of {meaning[top_meaning]:.3f}.</desc>",
             '  <rect width="100%" height="100%" fill="#ffffff"/>',
             f'  <text x="250" y="30" text-anchor="start" fill="{INK}">shared words</text>',
             f'  <text x="410" y="30" text-anchor="start" fill="{INK}">cosine</text>']
    for i, name in enumerate(ROW_NAMES):
        y = 52 + i * 36
        lines.append(f'  <text x="16" y="{y + 20}" text-anchor="start" fill="{INK}">{name}</text>')
        for x0, value, full, top, label in ((250, words[i], scale, top_words, str(words[i])), (410, meaning[i], 1.0, top_meaning, f"{meaning[i]:.3f}")):
            width = 110.0 * value / full
            colour = GREEN if i == top else INK
            if width > 0:
                lines.append(f'  <rect x="{x0}" y="{y}" width="{width:.1f}" height="26" fill="{colour}" stroke="{INK}" stroke-width="2"/>')
            lines.append(f'  <text x="{x0 + width + 10:.1f}" y="{y + 20}" text-anchor="start" fill="{INK}">{label}</text>')
    lines += [f'  <rect x="16" y="{52 + 9 * 36 + 4}" width="24" height="24" fill="{GREEN}" stroke="{INK}" stroke-width="2"/>',
              f'  <text x="50" y="{52 + 9 * 36 + 24}" text-anchor="start" fill="{INK}">top match of each search (first row of the ranking)</text>',
              "</svg>"]
    return "\n".join(lines) + "\n"


FILES = {"angle.svg": angle_svg, "ranking.svg": ranking_svg}


if __name__ == "__main__":
    drawn = {name: draw() for name, draw in FILES.items()}
    if "--check" in sys.argv:
        sys.exit(0 if all((FIGS / n).exists() and (FIGS / n).read_text(encoding="utf-8") == s for n, s in drawn.items()) else 1)
    FIGS.mkdir(exist_ok=True)
    for name, svg in drawn.items():
        (FIGS / name).write_text(svg, encoding="utf-8")
        print("wrote", FIGS / name)
