#!/usr/bin/env python3
"""Derive every number the page states (compute -> data/*.json -> build).

Reads: data/scores-c[0-7].json (OSM scoring, method in scripts/score.py),
       data/scores-c?-geo.json (reference geometries),
       ../unde-i/public/assets/map.json (county polygons).
Writes: data/villages.json (page gazetteer, compact),
        data/web/villages.json (shipped copy),
        data/geo-refs.json (merged reference geometries),
        data/facts.json (derived numbers for FILL).
Prints every derived number (this output is the derivation record).
"""
import json
import math
import os
import re
import unicodedata

ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
BASE = os.path.dirname(ROOT)
DATA = os.path.join(ROOT, "data")


def fold(s):
    return "".join(
        c for c in unicodedata.normalize("NFD", s.lower())
        if unicodedata.category(c) != "Mn")


def load_scores():
    rows = []
    for c in range(8):
        rows += json.load(open(os.path.join(DATA, "scores-c%d.json" % c)))
    return rows


def load_counties():
    # Self-contained copy first (shipped in repro/), unde-i map as fallback.
    local = os.path.join(DATA, "county-polygons.json")
    src = local if os.path.exists(local) else os.path.join(
        BASE, "unde-i", "public", "assets", "map.json")
    m = json.load(open(src))
    pr = m["proj"]
    named = []
    for c in m["counties"]:
        for sub in re.findall(r"M([^M]+)", c["d"]):
            pts = [tuple(map(float, t.split()))
                   for t in re.findall(r"[-\d.]+ [-\d.]+", sub)]
            named.append((c["name"], pts))
    return pr, named


def inside(x, y, poly):
    c = False
    n = len(poly)
    for i in range(n):
        x1, y1 = poly[i]
        x2, y2 = poly[(i + 1) % n]
        if (y1 > y) != (y2 > y) and \
                x < (x2 - x1) * (y - y1) / (y2 - y1) + x1:
            c = not c
    return c


def county_of(lat, lon, pr, named):
    x = (lon - pr["lonMin"]) * pr["scale"] * pr["cosLat"]
    y = (pr["latMax"] - lat) * pr["scale"]
    return {n for n, poly in named if inside(x, y, poly)}


def nearest_county(lat, lon, pr, named):
    """Nearest county + distance in km (3 km outline tolerance, game rule)."""
    import math as _m
    x = (lon - pr["lonMin"]) * pr["scale"] * pr["cosLat"]
    y = (pr["latMax"] - lat) * pr["scale"]
    km_per_px = 111.19 / pr["scale"]
    best = (1e9, None)
    for n, poly in named:
        for i in range(len(poly)):
            ax, ay = poly[i]
            bx, by = poly[(i + 1) % len(poly)]
            dx, dy = bx - ax, by - ay
            dd = dx * dx + dy * dy
            t = 0 if dd == 0 else max(
                0, min(1, ((x - ax) * dx + (y - ay) * dy) / dd))
            d = _m.hypot(x - ax - t * dx, y - ay - t * dy)
            if d < best[0]:
                best = (d, n)
    return best[1], best[0] * km_per_px


def kasa(pts):
    """Algebraic circle fit -> (cx, cy, r)."""
    n = len(pts)
    sx = sum(p[0] for p in pts)
    sy = sum(p[1] for p in pts)
    mx, my = sx / n, sy / n
    sxx = syy = sxy = sxz = syz = 0.0
    for x, y in pts:
        dx, dy = x - mx, y - my
        z = dx * dx + dy * dy
        sxx += dx * dx
        syy += dy * dy
        sxy += dx * dy
        sxz += dx * z
        syz += dy * z
    det = 2 * (sxx * syy - sxy * sxy)
    if abs(det) < 1e-9:
        return mx, my, 0.0
    cx = mx + (sxz * syy - syz * sxy) / det
    cy = my + (sxx * syz - sxy * sxz) / det
    r = math.sqrt(sum((x - cx) ** 2 + (y - cy) ** 2 for x, y in pts) / n)
    return cx, cy, r


def main():
    rows = load_scores()
    print("scored nodes: %d" % len(rows))
    pr, named = load_counties()
    counties = sorted({n for n, _ in named})
    cidx = {n: i for i, n in enumerate(counties)}

    border = {}
    bp = os.path.join(DATA, "border-keep.json")
    if os.path.exists(bp):
        border = json.load(open(bp))
    dcomm = {}
    dp = os.path.join(DATA, "dup-communes.json")
    if os.path.exists(dp):
        dcomm = json.load(open(dp))

    kept, dropped = [], []
    for r in rows:
        bk = border.get("%.5f,%.5f" % (r["lat"], r["lon"]))
        if bk is not None and bk != "ro":
            dropped.append(r)
            continue
        hits = county_of(r["lat"], r["lon"], pr, named)
        if not hits:
            near, dist = nearest_county(r["lat"], r["lon"], pr, named)
            if dist <= 3.0:
                r["county"] = near
                r["county_hits"] = [near]
                r["border_tol_km"] = round(dist, 2)
                kept.append(r)
                continue
            dropped.append(r)
            continue
        r["county"] = sorted(hits)[0]
        r["county_hits"] = sorted(hits)
        kept.append(r)
    print("non-RO dropped: %d" % len(dropped))
    for r in sorted(dropped, key=lambda r: r["name"])[:12]:
        print("  drop: %s (%.3f,%.3f)" % (r["name"], r["lat"], r["lon"]))

    # duplicate name+county?
    seen = {}
    dups = 0
    for r in kept:
        k = (fold(r["name"]), r["county"])
        if k in seen:
            dups += 1
            print("  DUP: %s [%s] vs (%.4f,%.4f) and (%.4f,%.4f)" % (
                r["name"], r["county"], r["lat"], r["lon"],
                seen[k]["lat"], seen[k]["lon"]))
        else:
            seen[k] = r
    print("dup name+county pairs: %d" % dups)

    sc = [r for r in kept if r["scorable"]]
    un = [r for r in kept if not r["scorable"]]
    print("scorable: %d  unscorable: %d" % (len(sc), len(un)))

    by_ring = sorted(sc, key=lambda r: -r["ring"])
    by_grid = sorted(sc, key=lambda r: -r["grid"])
    # Shared (competition) ranks at stored 3-decimal precision + strict-below
    # percentiles: tied places share one rank and one percentile (2026-11-23).
    def _shared(rows, key):
        out = {}
        for i, r in enumerate(rows):
            out[id(r)] = out[id(rows[i - 1])] if i and r[key] == rows[i - 1][key] else i + 1
        return out
    rank_ring = _shared(by_ring, "ring")
    rank_grid = _shared(by_grid, "grid")
    n = len(sc)

    def pct_below(rows, key, r):
        # Floor, never round: "above X in 100" must not become 100 for a
        # place that still has higher scorers (Codex delta 2, 2026-11-23).
        return int(100 * sum(1 for x in rows if x[key] < r[key]) / max(n, 1))

    # reference rows
    def find(name, lat):
        c = [r for r in kept
             if r["name"] == name and abs(r["lat"] - lat) < 0.01]
        assert len(c) == 1, (name, len(c))
        return c[0]

    ch = find("Charlottenburg", 45.9786)
    ft = find("Fântânele", 46.1244)
    fr = find("Frumușeni", 46.1019)
    po = find("Poiana", 46.8056)
    go = find("Gottlob", 45.9360)
    bi = find("Biled", 45.8878)
    va = find("Variaș", 46.0118)
    cn = find("Corbu Nou", 45.4101)
    bu = find("Buzad", 45.9414)
    print("Charlottenburg ring=%.3f rank=%d grid=%.3f county=%s" % (
        ch["ring"], rank_ring[id(ch)], ch["grid"], ch["county"]))
    print("Fantanele grid=%.3f rank=%d ring=%.3f" % (
        ft["grid"], rank_grid[id(ft)], ft["ring"]))
    print("Frumuseni grid=%.3f rank=%d ring=%.3f" % (
        fr["grid"], rank_grid[id(fr)], fr["ring"]))
    print("Poiana ring=%.3f rank=%d" % (po["ring"], rank_ring[id(po)]))
    n_ge = sum(1 for r in sc if r["ring"] >= ch["ring"])
    n_higher = sum(1 for r in sc if round(r["ring"] * 1000) > round(ch["ring"] * 1000))
    n_tied = sum(1 for r in sc if r is not ch and round(r["ring"] * 1000) == round(ch["ring"] * 1000))
    print("villages scoring >= Charlottenburg ring: %d" % n_ge)

    # commune labels for duplicate name+county pairs (Nominatim cache)
    from collections import Counter
    keycount = Counter((fold(r["name"]), r["county"]) for r in kept)

    def commune_of(r):
        if keycount[(fold(r["name"]), r["county"])] <= 1:
            return ""
        return dcomm.get("%s|%.5f|%.5f" % (r["name"], r["lat"], r["lon"]), "")

    # gazetteer rows (compact arrays; trailing commune, "" when unique,
    # plus a stable per-place id so shared URLs never collide (2026-11-23))
    import hashlib
    def pid(r):
        return hashlib.md5(("%s|%.5f|%.5f" % (
            r["name"], r["lat"], r["lon"])).encode("utf-8")).hexdigest()[:6]
    S, U = [], []
    for r in kept:
        ci = cidx[r["county"]]
        if r["scorable"]:
            lp = r["loop"]
            S.append([r["name"], ci, int(round(r["ring"] * 1000)),
                      int(round(r["grid"] * 1000)),
                      pct_below(sc, "ring", r), pct_below(sc, "grid", r),
                      r["length_m"], r["ways"],
                      round(lp[1], 1) if lp else 0,
                      int(round(lp[0] * 1000)) if lp else 0,
                      r["rose"], commune_of(r), pid(r)])
        else:
            U.append([r["name"], ci, r["length_m"], r["ways"],
                      commune_of(r), pid(r)])
    S.sort(key=lambda row: (fold(row[0]), counties[row[1]]))
    U.sort(key=lambda row: (fold(row[0]), counties[row[1]]))
    gaz = {"extract": "Geofabrik romania-latest.osm.pbf 2026-10-12",
           "method": "R500/carry9/gate1000m6w/loop250-800/grid7deg",
           "counties": counties, "n_scorable": len(S),
           "s": S, "u": U}
    for p in (os.path.join(DATA, "villages.json"),
              os.path.join(DATA, "web", "villages.json")):
        os.makedirs(os.path.dirname(p), exist_ok=True)
        json.dump(gaz, open(p, "w"), ensure_ascii=False,
                  separators=(",", ":"))
        print("wrote %s (%d bytes)" % (p, os.path.getsize(p)))

    # geo refs
    geo = {}
    for c in range(8):
        p = os.path.join(DATA, "scores-c%d-geo.json" % c)
        if os.path.exists(p):
            geo.update(json.load(open(p)))
    json.dump(geo, open(os.path.join(DATA, "geo-refs.json"), "w"))
    web_geo = os.path.join(DATA, "web", "geo-refs.json")
    json.dump(geo, open(web_geo, "w"), separators=(",", ":"))
    print("geo refs: %s (%d bytes shipped)" %
          (sorted(geo), os.path.getsize(web_geo)))

    # ring diameter (Kasa on the winning loop vertices)
    loop = geo["Charlottenburg"]["loop"]
    cx, cy, rr = kasa(loop)
    rms = math.sqrt(sum((math.hypot(x - cx, y - cy) - rr) ** 2
                        for x, y in loop) / len(loop))
    print("Charlottenburg loop: %d pts, Kasa centre=(%.1f,%.1f) r=%.1f -> D=%.0f m rms=%.1f" % (
        len(loop), cx, cy, rr, 2 * rr, rms))

    facts = {
        "n_nodes": len(kept),
        "n_dropped_nonro": len(dropped),
        "n_scorable": len(S),
        "n_unscorable": len(U),
        "ch_ring": ch["ring"],
        "ch_ring_rank": rank_ring[id(ch)],
        "ch_ring_pct": pct_below(sc, "ring", ch),
        "ch_grid": ch["grid"],
        "ch_loop_len": round(ch["loop"][1], 0),
        "ch_loop_circ": ch["loop"][0],
        "ch_ring_d": round(2 * rr),
        "n_ge_charlottenburg": n_ge, "n_higher_charlottenburg": n_higher, "n_tied_charlottenburg": n_tied,
        "ft_grid": ft["grid"],
        "ft_ring": ft["ring"],
        "ft_weak_pct": round(ft["grid"] * 50, 1),
        "ft_grid_rank": rank_grid[id(ft)],
        "fr_ring": fr["ring"],
        "fr_grid": fr["grid"],
        "fr_grid_rank": rank_grid[id(fr)],
        "po_ring": po["ring"],
        "po_ring_rank": rank_ring[id(po)],
        "po_grid": po["grid"],
        "po_loop_len": round(po["loop"][1], 0),
        "po_loop_circ": po["loop"][0],
        "go_grid": go["grid"],
        "bi_grid": bi["grid"],
        "va_grid": va["grid"],
        "bu_ring": bu["ring"],
        "bu_grid": bu["grid"],
        "corbu_ring": cn["ring"],
        "corbu_circ": cn["loop"][0],
        "ch_klafter": int(round(round(2 * rr) / 1.896484)),
        "n_ring_zero": sum(1 for r in sc if r["ring"] == 0),
        "ring_zero_pct": round(100 * sum(1 for r in sc if r["ring"] == 0) / len(sc)),
        "ring_pts": len(loop),
        "ring_rms": round(rms, 1),
    }
    json.dump(facts, open(os.path.join(DATA, "facts.json"), "w"), indent=1)
    print(json.dumps(facts, indent=1))


if __name__ == "__main__":
    main()
