"""Build the post's SVG charts from data/countries.csv. Standard library only.

    python3 blog/country-risk-lists/src/make_charts.py

The world map uses Natural Earth 1:110m admin-0 countries (public domain),
downloaded once into src/.cache/ (git-ignored) from a pinned release.
"""

import csv
import hashlib
import json
import urllib.request
from collections import Counter
from html import escape
from pathlib import Path

HERE = Path(__file__).resolve().parent
POST = HERE.parent
DATA = POST / "data"
CACHE = HERE / ".cache"

NE_VERSION = "v5.1.2"
NE_URL = (f"https://raw.githubusercontent.com/nvkelso/natural-earth-vector/{NE_VERSION}"
          "/geojson/ne_110m_admin_0_countries.geojson")

FONT = "font-family='Inter, -apple-system, Segoe UI, Helvetica, Arial, sans-serif'"
INK, MUTED, GRID = "#1f2937", "#6b7280", "#e5e7eb"

# OECD categories 0-7: light to dark (higher = riskier).
CAT_COLOUR = {
    "0": "#fff7ed", "1": "#ffedd5", "2": "#fed7aa", "3": "#fdba74",
    "4": "#fb923c", "5": "#f97316", "6": "#ea580c", "7": "#9a3412",
}
NOT_CLASSIFIED = "#94a3b8"   # high-income OECD / euro area / euro micro-states
NOT_REVIEWED = "#cbd5e1"     # listed, "currently not reviewed or classified"
NOT_COVERED = "#eef2f6"      # territories the OECD does not cover
FLAG = "#1d4ed8"             # on a FATF or EU list


def read_csv(name):
    with open(DATA / name, encoding="utf-8") as f:
        return list(csv.DictReader(f))


def svg(width, height, body, title):
    return (f"<svg xmlns='http://www.w3.org/2000/svg' width='{width}' height='{height}' "
            f"viewBox='0 0 {width} {height}' role='img' aria-label='{escape(title, quote=True)}' {FONT}>"
            f"<title>{escape(title)}</title><rect width='100%' height='100%' fill='#ffffff'/>"
            f"{body}</svg>\n")


def text(x, y, s, size=13, fill=INK, anchor="start", weight="normal"):
    return (f"<text x='{x:.1f}' y='{y:.1f}' font-size='{size}' fill='{fill}' "
            f"text-anchor='{anchor}' font-weight='{weight}'>{escape(str(s))}</text>")


def swatch(x, y, colour, label, size=13):
    return (f"<rect x='{x}' y='{y - 11}' width='12' height='12' rx='2' fill='{colour}' stroke='#cbd5e1' stroke-width='0.5'/>"
            + text(x + 18, y, label, size))


SHORT_NAMES = {
    "PRK": "North Korea (DPRK)", "COD": "DR Congo", "LAO": "Laos", "SYR": "Syria",
    "VNM": "Vietnam", "BIH": "Bosnia and Herzegovina", "VGB": "British Virgin Islands",
}


def is_flagged(r):
    return r["fatf_list"] in ("call for action", "increased monitoring") or r["eu_high_risk"] == "yes"


# --- 1. OECD categories, with countries on a FATF or EU list highlighted ----

def categories_bar(rows):
    groups = [(c, f"{c}") for c in "01234567"] + [("nc", "high income"), ("nr", "not reviewed"), ("nv", "not covered")]
    colour = {"nc": NOT_CLASSIFIED, "nr": NOT_REVIEWED, "nv": NOT_COVERED}

    def key(r):
        if r["oecd_risk_category"]:
            return r["oecd_risk_category"]
        if r["oecd_status"].startswith("not classified"):
            return "nc"
        return "nr" if r["oecd_status"].startswith("not reviewed") else "nv"

    total = Counter(key(r) for r in rows)
    flagged = Counter(key(r) for r in rows if is_flagged(r))
    W, H, X0, Y0, PH = 960, 380, 60, 60, 240
    peak = max(total.values())
    bw = (W - X0 - 20) / len(groups)
    body = text(16, 24, "Countries by OECD country risk category (0 = lowest risk, 7 = highest)", 15, weight="600")
    body += text(16, 44, "Blue: also on the FATF black or grey list or the EU high-risk list", 12, MUTED)
    for v in range(0, peak + 1, 20):
        y = Y0 + PH - PH * v / peak
        body += f"<line x1='{X0}' x2='{W - 20}' y1='{y:.1f}' y2='{y:.1f}' stroke='{GRID}'/>" + text(X0 - 8, y + 4, v, 11, MUTED, "end")
    for j, (k, lab) in enumerate(groups):
        n, f = total.get(k, 0), flagged.get(k, 0)
        x = X0 + j * bw + 8
        w = bw - 16
        col = CAT_COLOUR.get(k, colour.get(k))
        h = PH * n / peak
        hf = PH * f / peak
        body += f"<rect x='{x:.1f}' y='{Y0 + PH - h:.1f}' width='{w:.1f}' height='{h:.1f}' fill='{col}' stroke='#cbd5e1' stroke-width='0.5'/>"
        if f:
            body += f"<rect x='{x:.1f}' y='{Y0 + PH - hf:.1f}' width='{w:.1f}' height='{hf:.1f}' fill='{FLAG}'/>"
        body += text(x + w / 2, Y0 + PH - h - 6, n, 13, INK, "middle", "700")
        body += text(x + w / 2, Y0 + PH + 18, lab, 12 if len(lab) < 3 else 11, MUTED, "middle")
    body += text(X0, H - 16, "OECD risk category; the last three bars are listed without a category or not covered", 12, MUTED)
    title = ("Bar chart of 250 countries by OECD country risk category: "
             + ", ".join(f"{lab}: {total.get(k, 0)} ({flagged.get(k, 0)} on a FATF or EU list)" for k, lab in groups) + ".")
    return svg(W, H, body, title)


# --- 2. World map of OECD categories ----------------------------------------

def natural_earth():
    CACHE.mkdir(exist_ok=True)
    path = CACHE / f"ne_110m_admin_0_countries_{NE_VERSION}.geojson"
    if not path.exists():
        req = urllib.request.Request(NE_URL, headers={"User-Agent": "datahub-blog-charts/0.1"})
        with urllib.request.urlopen(req, timeout=120) as r:
            path.write_bytes(r.read())
    print("natural earth sha256", hashlib.sha256(path.read_bytes()).hexdigest())
    return json.loads(path.read_text())


def ring_path(ring, w, h):
    return "M" + "L".join(f"{(lon + 180) / 360 * w:.1f},{(90 - lat) / 180 * h:.1f}" for lon, lat in ring) + "Z"


def world_map(rows):
    by = {r["iso3"]: r for r in rows}
    geo = natural_earth()
    W, H, TOP, MAP_H = 960, 430, 20, 480
    shapes = []
    for feat in geo["features"]:
        p = feat["properties"]
        if p.get("ADMIN") == "Antarctica":
            continue
        iso = p.get("ISO_A3_EH") if p.get("ISO_A3_EH") not in (None, "-99") else p.get("ADM0_A3")
        r = by.get(iso)
        if r is None:
            fill = NOT_COVERED
        elif r["oecd_risk_category"]:
            fill = CAT_COLOUR[r["oecd_risk_category"]]
        elif r["oecd_status"].startswith("not classified"):
            fill = NOT_CLASSIFIED
        elif r["oecd_status"].startswith("not reviewed"):
            fill = NOT_REVIEWED
        else:
            fill = NOT_COVERED
        g = feat["geometry"]
        polys = g["coordinates"] if g["type"] == "MultiPolygon" else [g["coordinates"]]
        d = "".join(ring_path(ring, W, MAP_H) for poly in polys for ring in poly)
        outline = f" stroke='{FLAG}' stroke-width='1.6'" if r is not None and is_flagged(r) else " stroke='#ffffff' stroke-width='0.5'"
        shapes.append(f"<path d='{d}' fill='{fill}'{outline}><title>{escape(p.get('NAME', ''))}</title></path>")
    # draw flagged outlines last so they sit on top
    shapes.sort(key=lambda s: FLAG in s)
    body = f"<g transform='translate(0,{TOP})'>{''.join(shapes)}</g>"
    y = H + 8
    x = 16
    for c in "01234567":
        body += f"<rect x='{x}' y='{y - 11}' width='22' height='12' fill='{CAT_COLOUR[c]}' stroke='#cbd5e1' stroke-width='0.5'/>" + text(x + 11, y + 16, c, 11, MUTED, "middle")
        x += 24
    body += text(16, y - 16, "OECD risk category", 12, MUTED)
    body += swatch(230, y, NOT_CLASSIFIED, "high income, not classified", 12)
    body += swatch(420, y, NOT_REVIEWED, "not reviewed", 12)
    body += swatch(525, y, NOT_COVERED, "not covered", 12)
    body += (f"<rect x='630' y='{y - 11}' width='12' height='12' fill='none' stroke='{FLAG}' stroke-width='2'/>"
             + text(648, y, "on a FATF or EU list (blue outline)", 12))
    title = ("World map of OECD country risk categories, darker for higher risk, with countries on the FATF black or grey list "
             "or the EU high-risk list outlined in blue. High-income OECD and euro-area countries are grey (not classified).")
    return svg(W, H + 36, body, title)


# --- 3. The 30 countries on a FATF or EU list --------------------------------

def overlap_matrix(rows):
    flagged = sorted((r for r in rows if is_flagged(r)), key=lambda r: SHORT_NAMES.get(r["iso3"], r["country"]))
    cols = [("FATF black list", lambda r: r["fatf_list"] == "call for action"),
            ("FATF grey list", lambda r: r["fatf_list"] == "increased monitoring"),
            ("EU high-risk list", lambda r: r["eu_high_risk"] == "yes")]
    W, X0, Y0, RH = 960, 250, 70, 22
    CW = 120
    H = Y0 + RH * len(flagged) + 40
    body = text(16, 24, f"The {len(flagged)} countries on a FATF list or the EU high-risk list", 15, weight="600")
    body += text(16, 44, "with their OECD risk category and World Bank income group", 12, MUTED)
    heads = [c for c, _ in cols] + ["OECD category", "World Bank income group"]
    for j, h in enumerate(heads):
        body += text(X0 + j * CW + (CW / 2 if j < 4 else 0), Y0 - 10, h, 11, MUTED, "middle" if j < 4 else "start", "600")
    for i, r in enumerate(flagged):
        y = Y0 + i * RH
        if i % 2 == 0:
            body += f"<rect x='16' y='{y}' width='{W - 32}' height='{RH}' fill='#f8fafc'/>"
        name = SHORT_NAMES.get(r["iso3"], r["country"])
        body += text(X0 - 12, y + 15, name, 12, INK, "end")
        for j, (_, test) in enumerate(cols):
            cx = X0 + j * CW + CW / 2
            if test(r):
                body += f"<circle cx='{cx}' cy='{y + 11}' r='6' fill='{FLAG}'/>"
            elif j < 2 and r["fatf_list"] == "removed October 2026" and j == 1:
                body += f"<circle cx='{cx}' cy='{y + 11}' r='5.5' fill='none' stroke='{FLAG}' stroke-width='1.5'/>"
        cat = r["oecd_risk_category"]
        cx = X0 + 3 * CW + CW / 2
        if cat:
            body += f"<rect x='{cx - 16}' y='{y + 3}' width='32' height='16' rx='3' fill='{CAT_COLOUR[cat]}'/>"
            body += text(cx, y + 15, cat, 12, "#ffffff" if int(cat) >= 5 else INK, "middle", "700")
        else:
            body += text(cx, y + 15, "–", 12, MUTED, "middle")
        body += text(X0 + 4 * CW, y + 15, r["world_bank_income"] or "–", 12, INK)
    body += text(16, H - 12, "Open circle: removed from the FATF grey list on 30 October 2026, still on the EU list. "
                 "– : no OECD category (high income or not covered).", 11, MUTED)
    title = "Matrix of the countries on the FATF black or grey list or the EU high-risk list. " + "; ".join(
        f"{r['country']}: " + ", ".join(c for c, t in cols if t(r)) + f", OECD {r['oecd_risk_category'] or 'none'}, {r['world_bank_income'] or 'no income group'}"
        for r in flagged)
    return svg(W, H, body, title)


def main():
    rows = read_csv("countries.csv")
    out = {
        "oecd-categories.svg": categories_bar(rows),
        "oecd-map.svg": world_map(rows),
        "lists-overlap.svg": overlap_matrix(rows),
    }
    for name, content in out.items():
        (POST / name).write_text(content, encoding="utf-8")
        print(name, len(content.encode()), "bytes")


if __name__ == "__main__":
    main()
