#!/usr/bin/env python3
"""Build App/Resources/city-bounds.bin: GeoNames city id -> simplified municipal outline.

Source: Overture Maps divisions (division + division_area), which are OpenStreetMap-derived and
licensed ODbL 1.0. Join to our GeoNames cities via Wikidata (P1566, P1376, P131), then a strict
name + point-in-polygon fallback. See README.md in this folder for the rules, the file format and
the licence obligations.

Usage:
  build_city_bounds.py --places App/Resources/places.json --regions App/Resources/regions-shapes.json \
      --overture DIR_WITH_division_AND_division_area --wikidata DIR_WITH_TSVs --release 2026-11-18.0 --out OUTDIR
Requires: python3.11+, duckdb>=1.2 (GEOMETRY), shapely>=2, numpy.
"""
import argparse, json, math, re, struct, sys, unicodedata, csv, time
from collections import defaultdict
from pathlib import Path

import duckdb
import numpy as np
import shapely
from shapely import wkb as shp_wkb
from shapely.geometry import Point, Polygon, MultiPolygon

TOLERANCE_DEG = 0.0009        # ~100 m in latitude
SCALE = 100_000               # coordinates stored as int32 * 1e-5 degrees (~1.1 m)
MAX_AREA_KM2 = 3000.0         # larger "cities" (Chongqing, Beijing municipality) keep the circle
MIN_DENSITY = 5.0             # people / km2; below this (and area > SMALL_AREA) the outline is not "the city"
SMALL_AREA_KM2 = 100.0
POINT_TOLERANCE_KM = 1.0      # GeoNames point must be inside the outline or within this distance
PART_MAX_KM = 100.0           # drop far-away parts (e.g. Tokyo's Ogasawara islands)
REGION_FRACTION = 0.8         # an outline this close to the admin-1 region's area is a parent region
WALK_SUBTYPES = {"locality", "localadmin"}
OWN_SUBTYPES = {"locality", "localadmin", "county", "region"}
SUBTYPE_RANK = {"locality": 0, "localadmin": 1, "county": 2, "region": 3}
ORIGIN_RANK = {"own": 0, "p1376": 1, "p131": 2, "name": 3}
# P25 (D135): the hole places (data-tools/places/hole-places.tsv, reason `add`) are cities because their own division fills
# a hole in a kept city's outline. Their `own` outline is kept even below MIN_DENSITY (a rural hole: Herlitzka, AR,
# 264 km2, 1,166 people) and may be a neighbourhood-type division when hole_places.py accepted it (a Wikidata populated
# place: Lincoln Acres CDP, Güneyce village). Nothing changes for the other cities.
HOOD_SUBTYPES = {"neighborhood", "macrohood", "microhood", "borough"}
HOLE_PLACES = Path(__file__).resolve().parent.parent / "places" / "hole-places.tsv"


def hole_places(path=HOLE_PLACES):
    """(GeoNames ids, Wikidata items) of the hole places to add (D135)."""
    ids, items = set(), set()
    if not Path(path).exists():
        return ids, items
    with open(path, encoding="utf-8") as f:
        rows = [line.rstrip("\n").split("\t") for line in f if line.strip() and not line.startswith("#")]
    header = rows[0]
    gi, wi, ri = header.index("geonames"), header.index("wikidata"), header.index("reason")
    for row in rows[1:]:
        if row[ri] == "add":
            ids.update(g for g in row[gi].split(",") if g)
            if row[wi]:
                items.add(row[wi])
    return ids, items


def fold(s):
    if not s:
        return ""
    s = unicodedata.normalize("NFKD", s)
    s = "".join(ch for ch in s if not unicodedata.combining(ch)).lower()
    s = re.sub(r"[\-‐–—'’`.,()]", " ", s)
    s = re.sub(r"\b(city of|ciudad de|ville de|municipio de|municipality of|town of|village of)\b", " ", s)
    s = re.sub(r"\b(city|town|village|municipality|shi|si|gun|ku|cho|machi)\b$", " ", s)
    return re.sub(r"\s+", " ", s).strip()


def qid(s):
    m = re.search(r"Q\d+", s or "")
    return m.group(0) if m else None


def read_tsv(path, want_gn):
    """Yield rows (as dict of header -> value) whose ?gn column is one of ours."""
    with open(path, encoding="utf-8") as f:
        header = [h.strip().lstrip("?") for h in f.readline().rstrip("\n").split("\t")]
        gi = header.index("gn")
        for line in f:
            parts = line.rstrip("\n").split("\t")
            gn = parts[gi].strip('"')
            if gn in want_gn:
                yield dict(zip(header, (p.strip('"') for p in parts)))


def local_xy(lon, lat, lat0):
    return (np.asarray(lon) * math.cos(math.radians(lat0)) * 111.320, np.asarray(lat) * 110.574)


def ring_area_km2(coords, lat0):
    x, y = local_xy(coords[:, 0], coords[:, 1], lat0)
    return abs(0.5 * np.sum(x[:-1] * y[1:] - x[1:] * y[:-1]))


def geom_area_km2(g, lat0):
    tot = 0.0
    for p in getattr(g, "geoms", [g]):
        tot += ring_area_km2(np.asarray(p.exterior.coords), lat0)
        for h in p.interiors:
            tot -= ring_area_km2(np.asarray(h.coords), lat0)
    return tot


def km_between(lon1, lat1, lon2, lat2):
    x1, y1 = local_xy(lon1, lat1, (lat1 + lat2) / 2)
    x2, y2 = local_xy(lon2, lat2, (lat1 + lat2) / 2)
    return float(math.hypot(x1 - x2, y1 - y2))


def dist_km(g, lon, lat):
    if g.contains(Point(lon, lat)):
        return 0.0
    p1, p2 = shapely.ops.nearest_points(g, Point(lon, lat)) if hasattr(shapely, "ops") else (None, None)
    return km_between(p1.x, p1.y, lon, lat)


def zigzag(n):
    return (n << 1) ^ (n >> 63)


def varint(n, out):
    while True:
        b = n & 0x7F
        n >>= 7
        if n:
            out.append(b | 0x80)
        else:
            out.append(b)
            return


def encode_geometry(g):
    out = bytearray()
    polys = list(getattr(g, "geoms", [g]))
    out += struct.pack("<H", len(polys))
    for p in polys:
        rings = [p.exterior] + list(p.interiors)
        out += struct.pack("<H", len(rings))
        for r in rings:
            c = np.asarray(r.coords)[:-1]  # implicit close
            q = np.round(c * SCALE).astype(np.int64)
            out += struct.pack("<I", len(q))
            out += struct.pack("<ii", int(q[0, 0]), int(q[0, 1]))
            prev = q[0]
            for v in q[1:]:
                varint(zigzag(int(v[0] - prev[0])), out)
                varint(zigzag(int(v[1] - prev[1])), out)
                prev = v
    return bytes(out)


def main():
    import shapely.ops  # noqa: F401  (nearest_points)
    ap = argparse.ArgumentParser()
    ap.add_argument("--places", required=True)
    ap.add_argument("--regions", required=True)
    ap.add_argument("--overture", required=True)
    ap.add_argument("--wikidata", required=True)
    ap.add_argument("--release", required=True)
    ap.add_argument("--out", required=True)
    ap.add_argument("--baseline-dir", default=str(Path(__file__).resolve().parent),
                    help="P25 (D135): holes-without-city.tsv and unselectable-cities.tsv for the invariant checks")
    ap.add_argument("--write-baselines", action="store_true",
                    help="P25: rewrite the baselines from the new file (refused when one grows: a ratchet)")
    ap.add_argument("--allow-growth", action="store_true", help="P25: with Yo's approval only")
    a = ap.parse_args()
    t0 = time.time()
    out = Path(a.out); out.mkdir(parents=True, exist_ok=True)
    log = lambda *x: print(f"[{time.time()-t0:6.0f}s]", *x, flush=True)

    places = json.load(open(a.places))
    cols = [c.rstrip("?") for c in places["columns"]["cities"]]
    raw = places["cities"]
    cities = []
    for row in raw:
        d = dict(zip(cols, row))
        names = {d.get("name"), d.get("asciiName")}
        ln = d.get("localizedNames") or {}
        if isinstance(ln, dict):
            names |= set(ln.values())
        cities.append({"id": str(d["id"]), "name": d["name"], "lat": float(d["latitude"]), "lon": float(d["longitude"]),
                       "cc": d["countryCode"], "a1": d.get("admin1") or "", "pop": int(d.get("population") or 0),
                       "folds": {fold(n) for n in names if n} - {""}})
    by_id = {c["id"]: c for c in cities}
    log("cities", len(cities))
    hole_ids, hole_items = hole_places()
    log("hole places (D135)", len(hole_ids & set(by_id)), "of", len(hole_ids))

    # ---- parent-region areas (Natural Earth admin-1, already in the app) ----
    regions = json.load(open(a.regions))["regions"]
    region_area = {}
    for key, polys in regions.items():
        tot = 0.0
        for poly in polys:
            for i, ring in enumerate(poly):
                arr = np.asarray(ring).reshape(-1, 2)
                arr = np.vstack([arr, arr[:1]])
                ar = ring_area_km2(arr, float(arr[:, 1].mean()))
                tot += ar if i == 0 else -ar
        region_area[key] = tot

    # ---- Wikidata candidates ----
    W = Path(a.wikidata)
    want = set(by_id)
    cand = defaultdict(list)  # gn -> [(qid, origin)]
    own_q = defaultdict(set)
    for r in read_tsv(W / "wikidata-gn.tsv", want):
        q = qid(r["item"]); cand[r["gn"]].append((q, "own")); own_q[r["gn"]].add(q)
    for fn, origin in (("wikidata-p1376.tsv", "p1376"), ("wikidata-p131.tsv", "p131")):
        for r in read_tsv(W / fn, want):
            cand[r["gn"]].append((qid(r["muni"]), origin))
    all_q = {q for v in cand.values() for q, _ in v if q}
    log("wikidata candidate items", len(all_q), "cities with any", len(cand))

    # ---- Overture: divisions with an area ----
    O = Path(a.overture)
    con = duckdb.connect()
    con.execute("SET memory_limit='5GB'")
    con.execute("CREATE TEMP TABLE holeq(q VARCHAR)")
    con.executemany("INSERT INTO holeq VALUES (?)", [(q,) for q in sorted(hole_items)])
    con.execute("CREATE TEMP TABLE wantq(q VARCHAR)")
    con.executemany("INSERT INTO wantq VALUES (?)", [(q,) for q in all_q])
    divs = con.execute(f"""
      WITH has_area AS (
        SELECT DISTINCT division_id FROM read_parquet('{O}/division_area/*.parquet')
        WHERE is_land AND subtype IN ('locality','localadmin','county','region','neighborhood','macrohood','microhood','borough'))
      SELECT d.id, d.subtype, d.wikidata, d.names."primary", map_values(d.names.common), d.country, d.sources[1].record_id
      FROM read_parquet('{O}/division/*.parquet') d JOIN has_area h ON h.division_id = d.id
      WHERE d.subtype IN ('locality','localadmin','county','region')
         OR (d.subtype IN ('neighborhood','macrohood','microhood','borough') AND d.wikidata IN (SELECT q FROM holeq))""").fetchall()
    log("divisions with a land area", len(divs))
    wanted_names = defaultdict(set)
    for c in cities:
        for f in c["folds"]:
            wanted_names[c["cc"]].add(f)
    by_q = defaultdict(list)
    name_pool = defaultdict(list)
    need = {}
    for (did, st, wd, nm, common, cc, rid) in divs:
        rec = {"did": did, "subtype": st, "q": wd, "name": nm, "common": list(common or []), "cc": cc, "rid": rid}
        used = False
        if wd and wd in all_q:
            by_q[wd].append(rec); used = True
        if st in WALK_SUBTYPES:
            hit = ({fold(nm)} | {fold(x) for x in rec["common"]}) & wanted_names.get(cc, set())
            for n in hit:
                name_pool[(cc, n)].append(rec); used = True
        if used:
            need[did] = rec
    del divs
    log("needed divisions", len(need), "by wikidata", sum(len(v) for v in by_q.values()), "name keys", len(name_pool))
    con.execute("CREATE TEMP TABLE needid(id VARCHAR)")
    con.executemany("INSERT INTO needid VALUES (?)", [(k,) for k in need])
    geoms = {}
    cur = con.execute(f"""
      SELECT a.division_id, any_value(ST_AsWKB(a.geometry))
      FROM read_parquet('{O}/division_area/*.parquet') a JOIN needid n ON n.id = a.division_id
      WHERE a.is_land GROUP BY a.division_id""")
    while True:
        chunk = cur.fetchmany(5000)
        if not chunk:
            break
        for did, wkb in chunk:
            g = shp_wkb.loads(bytes(wkb))
            if not g.is_valid:
                g = shapely.make_valid(g)
            g = shapely.simplify(g, 0.0002, preserve_topology=True)
            polys = [p for p in getattr(g, "geoms", [g]) if p.geom_type == "Polygon" and not p.is_empty]
            if polys:
                geoms[did] = polys[0] if len(polys) == 1 else MultiPolygon(polys)
    log("geometries loaded", len(geoms))

    def geom(rec):
        return geoms.get(rec["did"])

    def rec_names(rec):
        return {fold(rec["name"])} | {fold(x) for x in rec["common"]}

    stats = defaultdict(int)
    reject = defaultdict(int)
    picked = {}
    for c in cities:
        options = []
        for q, origin in cand.get(c["id"], []):
            for rec in by_q.get(q, []):
                allowed = OWN_SUBTYPES if origin == "own" else WALK_SUBTYPES
                if origin == "own" and c["id"] in hole_ids:
                    allowed = OWN_SUBTYPES | HOOD_SUBTYPES  # D135
                if rec["subtype"] not in allowed:
                    reject["subtype"] += 1; continue
                if origin != "own" and not (rec_names(rec) & c["folds"]):
                    reject["walk-name"] += 1; continue
                options.append((ORIGIN_RANK[origin], SUBTYPE_RANK.get(rec["subtype"], 4), origin, rec))
        for f in c["folds"]:
            for rec in name_pool.get((c["cc"], f), []):
                options.append((ORIGIN_RANK["name"], SUBTYPE_RANK[rec["subtype"]], "name", rec))
        options.sort(key=lambda o: (o[0], o[1]))
        seen = set()
        for _, _, origin, rec in options:
            if rec["did"] in seen:
                continue
            seen.add(rec["did"])
            g = geom(rec)
            if g is None:
                reject["no-geom"] += 1; continue
            # drop far-away parts
            parts = [p for p in getattr(g, "geoms", [g])
                     if km_between(p.representative_point().x, p.representative_point().y, c["lon"], c["lat"]) <= PART_MAX_KM
                     or p.contains(Point(c["lon"], c["lat"]))]
            if not parts:
                reject[f"{origin}:far"] += 1; continue
            g2 = parts[0] if len(parts) == 1 else MultiPolygon(parts)
            d = dist_km(g2, c["lon"], c["lat"])
            if d > (0.0 if origin == "name" else POINT_TOLERANCE_KM):
                reject[f"{origin}:point"] += 1; continue
            area = geom_area_km2(g2, c["lat"])
            if area > MAX_AREA_KM2:
                reject[f"{origin}:too-big"] += 1; continue
            if area > SMALL_AREA_KM2 and c["pop"] / max(area, 1e-9) < MIN_DENSITY and c["id"] not in hole_ids:
                reject[f"{origin}:density"] += 1; continue
            ra = region_area.get(f"{c['cc']}.{c['a1']}")
            city_state = False
            if ra and area >= REGION_FRACTION * ra:
                if origin != "own":
                    reject[f"{origin}:region-size"] += 1; continue
                city_state = True
            picked[c["id"]] = {"origin": origin, "rec": rec, "g": g2, "area": area, "city_state": city_state,
                               "name_match": bool(rec_names(rec) & c["folds"])}
            break
    log("picked before dedupe", len(picked), "rejects", dict(reject))

    # one outline -> one city: keep the name match with the best origin, then the biggest population
    by_div = defaultdict(list)
    for gid, p in picked.items():
        by_div[p["rec"]["did"]].append(gid)
    dropped_dupe = 0
    for did, gids in by_div.items():
        if len(gids) < 2:
            continue
        gids.sort(key=lambda g: (not picked[g]["name_match"], ORIGIN_RANK[picked[g]["origin"]], -by_id[g]["pop"]))
        for g in gids[1:]:
            del picked[g]; dropped_dupe += 1
    log("after dedupe", len(picked), "dropped", dropped_dupe)

    # ---- simplify + encode ----
    entries = []
    blob = bytearray()
    vertices = 0
    rows = []
    for gid in sorted(picked, key=lambda s: int(s)):
        p = picked[gid]
        c = by_id[gid]
        lat0 = c["lat"]
        s = shapely.simplify(p["g"], TOLERANCE_DEG, preserve_topology=True)
        if not s.is_valid:
            s = shapely.make_valid(s)
        polys = [q for q in getattr(s, "geoms", [s]) if q.geom_type == "Polygon" and geom_area_km2(q, lat0) >= 0.01]
        if not polys:
            continue
        s = polys[0] if len(polys) == 1 else MultiPolygon(polys)
        s = shapely.geometry.polygon.orient(s, 1.0) if s.geom_type == "Polygon" else MultiPolygon([shapely.geometry.polygon.orient(q, 1.0) for q in s.geoms])
        enc = encode_geometry(s)
        minx, miny, maxx, maxy = s.bounds
        nverts = sum(len(r.coords) - 1 for q in getattr(s, "geoms", [s]) for r in [q.exterior, *q.interiors])
        vertices += nverts
        area = geom_area_km2(s, lat0)
        entries.append((int(gid), round(minx * SCALE), round(miny * SCALE), round(maxx * SCALE), round(maxy * SCALE), len(blob), len(enc), area))
        blob += enc
        rec = p["rec"]
        rows.append({"id": gid, "name": c["name"], "cc": c["cc"], "pop": c["pop"], "origin": p["origin"],
                     "subtype": rec["subtype"], "wikidata": rec["q"] or "", "osm": rec["rid"] or "",
                     "overture_division": rec["did"], "overture_name": rec["name"], "area_km2": round(area, 3),
                     "vertices": nverts, "city_state": int(p["city_state"]),
                     "own_wikidata": ";".join(sorted(q for q in own_q.get(gid, set()) if q))})

    MAGIC = b"PCB1"
    header = MAGIC + struct.pack("<II", len(entries), 0)
    index = bytearray()
    for e in entries:
        index += struct.pack("<Iiiii" "IIf", *e)
    data = header + bytes(index) + bytes(blob)
    (out / "city-bounds.bin").write_bytes(data)

    with open(out / "city-bounds-index.csv", "w", newline="") as f:
        w = csv.DictWriter(f, fieldnames=list(rows[0].keys()))
        w.writeheader(); w.writerows(rows)

    # ---- match rates ----
    have = {r["id"] for r in rows}
    top = sorted(cities, key=lambda c: -c["pop"])[:1000]
    def rate(sub):
        return {"n": len(sub), "matched": sum(1 for c in sub if c["id"] in have),
                "pct": round(100 * sum(1 for c in sub if c["id"] in have) / max(1, len(sub)), 1)}
    rates = {"all": rate(cities), "top1000": rate(top)}
    for cc in ("ES", "US", "JP", "FR", "DE", "GB", "IT", "CN", "IN", "BR", "MX"):
        rates[cc] = rate([c for c in cities if c["cc"] == cc])
    origins = defaultdict(int)
    for r in rows:
        origins[r["origin"]] += 1
    meta = {
        "format": 1, "file": "city-bounds.bin", "generated": time.strftime("%Y-%m-%d"),
        "licence": "© OpenStreetMap contributors, available under the Open Database License (ODbL) 1.0; via Overture Maps Foundation divisions, release " + a.release,
        "sources": [{"name": "Overture Maps divisions (division, division_area)", "release": a.release,
                     "url": f"s3://overturemaps-us-west-2/release/{a.release}/theme=divisions/"},
                    {"name": "Wikidata P1566 / P1376 / P131 (CC0)", "url": "https://qlever.dev/api/wikidata"}],
        "tolerance_deg": TOLERANCE_DEG, "scale": SCALE,
        "count": len(entries), "vertices": vertices, "bytes": len(data),
        "rates": rates, "origins": dict(origins), "rejects": dict(reject), "dedupe_dropped": dropped_dupe,
        "city_states": [r["id"] for r in rows if r["city_state"]],
    }
    json.dump(meta, open(out / "city-bounds-meta.json", "w"), indent=1, ensure_ascii=False)
    log("wrote", len(entries), "polygons", vertices, "vertices", len(data), "bytes")
    log(json.dumps(rates))
    missed = sorted(hole_ids & set(by_id) - have)
    log("hole places (D135) with an outline", len(hole_ids & have), "without", len(missed), missed[:40])

    # P25 (D135, Yo t113u): the data invariants (a)-(c) against the baselines; a failure fails the build (exit 1).
    sys.path.insert(0, str(Path(__file__).resolve().parent))
    import invariants
    code = invariants.run(str(out / "city-bounds.bin"), a.places, a.baseline_dir, a.write_baselines, a.allow_growth)
    if code:
        log("FAIL: data invariants (see above)")
    return code


if __name__ == "__main__":
    sys.exit(main())
