#!/usr/bin/env python3
"""P25 (SPEC §7, D135): the GeoNames places that are the "hole" in a kept city's outline (Marina del Rey in Los Angeles).

A city outline (city-bounds.bin, D113) can have holes: enclaves that are another place (Beverly Hills in Los Angeles,
D131). A tap in a hole is never the surrounding city's (D131). When the hole's own place is not a city in places.json
(Marina del Rey, an unincorporated CDP that GeoNames codes PPLX, so D96 made it an alias of Los Angeles), a tap there
selects nothing (Yo t111u). This script lists those places; Scripts/build-places.py reads the list (offline) and adds them
as cities, and build_city_bounds.py then gives them their own outline (the `own` Wikidata candidate).

Rule (D135; thresholds as the bot's P25 audit, box-data/fillers.py):
  1. a hole ring of a kept city's outline that other outlines cover < 90 % of (a covered hole already has a city);
  2. its best "filler": an Overture division_area (land) that is not a county, fills >= 50 % of the hole and lies >= 80 %
     inside it (the most of the hole first);
  3. the filler is a `locality` or `localadmin`; a `neighborhood`, `macrohood`, `microhood` or `borough` only when its
     Wikidata item is a populated place, strictly: an instance-of statement with no end time whose class is a subclass of
     census-designated place (Q498162), unincorporated community (Q17343829), village (Q532), town (Q3957) or city (Q515),
     and not of neighbourhood (Q123705), suburb (Q188509) or quarter (Q2983893) (a city section is not a city);
  4. the filler's Wikidata item carries GeoNames ids (P1566, wikidata-gn.tsv); none of them is already a city in
     places.json (then the hole already has its city, just not covering 90 %: reason `already-a-city`, not written as an
     addition). Scripts/build-places.py picks the id (a populated place, P class, not historical/abandoned/destroyed) and
     adds it as a city;
  5. fillers with no GeoNames id are never given an invented one: they are counted (`no-geonames`) and stay holes
     without a city (holes-without-city.tsv, D135).

Output: data-tools/places/hole-places.tsv, one row per (hole, filler): geonames (comma list, P1566), wikidata, name (the
division's), subtype, host (GeoNames id of the outline's city), host_name, poly, hole, km2, frac_of_hole, frac_of_div,
reason (`add` or `already-a-city`). Only GeoNames ids and Wikidata ids reach places.json (through build-places.py); no
geometry does. The list is derived from Overture divisions (ODbL) and Wikidata (CC0); see README.md.

Usage (on the box, with the Overture divisions and the Wikidata TSVs of build_city_bounds.py):
  hole_places.py --bounds App/Resources/city-bounds.bin --places App/Resources/places.json \
      --overture DIR_WITH_division_AND_division_area --wikidata DIR_WITH_TSVs --out data-tools/places/hole-places.tsv
Seed (offline, from the bot's audit; same filter):
  hole_places.py --fillers box-data/hole-fillers.tsv --holes box-data/holes-before.tsv --places App/Resources/places.json \
      --out data-tools/places/hole-places.tsv
Requires (full run): python3.11+, duckdb>=1.2, shapely>=2. The seed needs neither. Both ask Wikidata (QLever) for the
P31 of the neighbourhood-type fillers only.
"""
import argparse
import collections
import csv
import json
import math
import struct
import sys
import urllib.parse
import urllib.request

COVERED = 0.9            # a hole other outlines cover this much already has a city
FILL_HOLE = 0.5          # the filler covers at least this much of the hole
FILL_INSIDE = 0.8        # and lies at least this much inside it
PLACE_SUBTYPES = {"locality", "localadmin"}
HOOD_SUBTYPES = {"neighborhood", "macrohood", "microhood", "borough"}
POPULATED = ["Q498162", "Q17343829", "Q532", "Q3957", "Q515"]
SECTION = ["Q123705", "Q188509", "Q2983893"]
ENDPOINT = "https://qlever.dev/api/wikidata"
HEADER = ["geonames", "wikidata", "name", "subtype", "host", "host_name", "poly", "hole", "km2", "frac_of_hole",
          "frac_of_div", "reason"]


def populated_items(items):
    """The Wikidata items (of `items`) that are populated places by rule 3 (QLever, CC0)."""
    items = sorted({q for q in items if q and q.startswith("Q")})
    if not items:
        return set()
    query = (
        "PREFIX wd: <http://www.wikidata.org/entity/>\nPREFIX wdt: <http://www.wikidata.org/prop/direct/>\n"
        "PREFIX p: <http://www.wikidata.org/prop/>\nPREFIX ps: <http://www.wikidata.org/prop/statement/>\n"
        "PREFIX pq: <http://www.wikidata.org/prop/qualifier/>\n"
        "SELECT DISTINCT ?item WHERE { VALUES ?item { " + " ".join("wd:" + q for q in items) + " }\n"
        "  ?item p:P31 ?st . ?st ps:P31 ?cls . FILTER NOT EXISTS { ?st pq:P582 ?end }\n"
        "  VALUES ?ok { " + " ".join("wd:" + q for q in POPULATED) + " } ?cls wdt:P279* ?ok .\n"
        "  FILTER NOT EXISTS { VALUES ?bad { " + " ".join("wd:" + q for q in SECTION) + " } ?cls wdt:P279* ?bad } }")
    body = urllib.parse.urlencode({"query": query}).encode()
    request = urllib.request.Request(ENDPOINT, data=body, headers={
        "Accept": "text/tab-separated-values", "Content-Type": "application/x-www-form-urlencoded",
        "User-Agent": "passportone-hole-places/1.0"})
    text = urllib.request.urlopen(request, timeout=300).read().decode()
    return {line.rsplit("/", 1)[-1].strip("<>") for line in text.splitlines()[1:] if line}


def places_ids(path):
    places = json.load(open(path, encoding="utf-8"))
    return {row[0] for row in places["cities"]}, {row[0]: row[1] for row in places["cities"]}


def wikidata_geonames(path):
    """Wikidata item -> [GeoNames id] from wikidata-gn.tsv (P1566), as box-data/fillers.py reads it."""
    result = collections.defaultdict(list)
    with open(path, encoding="utf-8") as handle:
        for line in handle:
            parts = line.rstrip("\n").split("\t")
            if len(parts) < 2 or parts[0].startswith("?"):
                continue
            gn = parts[0].strip('"')
            item = parts[1].rsplit("/", 1)[-1].strip("<>")
            if gn.isdigit():
                result[item].append(int(gn))
    return result


def previous_rows(path):
    """The `add` rows of an earlier hole-places.tsv: kept on a rerun (D135: the list only grows). After the rebuild a hole
    place's own outline covers its hole, so the audit no longer finds that hole; its row must stay or the city would go."""
    try:
        with open(path, encoding="utf-8") as handle:
            rows = [line.rstrip("\n").split("\t") for line in handle if line.strip() and not line.startswith("#")]
    except FileNotFoundError:
        return []
    return [row for row in rows[1:] if row[-1] == "add"]


def select(fillers, city_ids, names, previous=()):
    """Rules 3-5 on the fillers ((host, poly, hole, km2, subtype, name, wikidata, [gn], frac_hole, frac_div) per hole).
    Returns the rows to write and the counts. An id an earlier run added (`previous`) stays `add`."""
    previous_ids = {int(g) for row in previous for g in row[0].split(",") if g}
    hoods = populated_items(f[6] for f in fillers if f[4] in HOOD_SUBTYPES)
    rows, stats = [], collections.Counter()
    for host, poly, hole, km2, subtype, name, item, gns, frac_hole, frac_div in fillers:
        if subtype in HOOD_SUBTYPES and item not in hoods:
            stats[f"{subtype}: not a populated place in Wikidata (a section)"] += 1
            continue
        if subtype not in PLACE_SUBTYPES | HOOD_SUBTYPES:
            stats[f"{subtype}: not a place subtype"] += 1
            continue
        gns = [g for g in gns if g != host]
        if not gns:
            stats[f"{subtype}: no GeoNames id (no-geonames, stays a hole)"] += 1
            continue
        if any(g in previous_ids for g in gns):
            reason = "add"
        else:
            reason = "already-a-city" if any(g in city_ids for g in gns) else "add"
        stats[f"{subtype}: {reason}"] += 1
        rows.append([",".join(str(g) for g in gns), item, name, subtype, host, names.get(host, ""), poly, hole,
                     round(km2, 3), round(frac_hole, 3), round(frac_div, 3), reason])
    found = {int(g) for row in rows for g in row[0].split(",") if g}
    for row in previous:
        if not any(int(g) in found for g in row[0].split(",") if g):
            stats["kept from the earlier list (its hole now has the city's outline)"] += 1
            rows.append(row)
    return rows, stats


def from_fillers(path, holes_path=None):
    """The bot's audit output (box-data/hole-fillers.tsv: already rules 1-2); the polygon index from its
    holes-before.tsv (same city, hole and centroid) when given."""
    poly_of = {}
    if holes_path:
        with open(holes_path, encoding="utf-8") as handle:
            for row in csv.DictReader(handle, delimiter="\t"):
                poly_of[(row["city"], row["hole"], row["lon"], row["lat"])] = int(row["poly"])
    fillers = []
    with open(path, encoding="utf-8") as handle:
        for row in csv.DictReader(handle, delimiter="\t"):
            gns = [int(g) for g in row["geonames"].split(",") if g.strip()]
            item = row["wikidata"] if row["wikidata"] not in ("", "None") else ""
            poly = poly_of.get((row["city"], row["hole"], row["lon"], row["lat"]), "")
            fillers.append((int(row["city"]), poly, int(row["hole"]), float(row["km2"]), row["subtype"], row["name"], item,
                            gns, float(row["frac_of_hole"]), float(row["frac_of_div"])))
    return fillers


def from_overture(bounds, places, overture, wikidata):
    """Rules 1-2 from city-bounds.bin and the Overture divisions (box-data/holes_audit.py + fillers.py, one script)."""
    import duckdb
    import shapely
    from shapely import STRtree, wkb
    from shapely.geometry import Polygon

    import invariants  # same folder: the bin reader
    outlines = invariants.read_bounds(bounds)
    city_ids, _ = places_ids(places)
    outer, holes = {}, []
    for entry in outlines:
        parts = []
        for pi, rings in enumerate(entry.polygons):
            coords = [[(ring[2 * i], ring[2 * i + 1]) for i in range(len(ring) // 2)] for ring in rings]
            parts.append(Polygon(coords[0], coords[1:]))
            for hi, ring in enumerate(coords[1:]):
                holes.append((entry.id, pi, hi, shapely.make_valid(Polygon(ring))))
        outer[entry.id] = shapely.make_valid(shapely.MultiPolygon(parts) if len(parts) > 1 else parts[0])
    ids = list(outer)
    geoms = [outer[i] for i in ids]
    tree = STRtree(geoms)
    need = []
    for host, pi, hi, ring in holes:
        area = ring.area
        if area <= 0:
            continue
        covered = sum(geoms[j].intersection(ring).area for j in tree.query(ring, predicate="intersects") if ids[j] != host)
        if covered / area < COVERED:
            need.append((host, pi, hi, ring))
    print(f"outlines {len(ids)}, holes {len(holes)}, covered < {COVERED:.0%}: {len(need)}", file=sys.stderr)
    con = duckdb.connect()
    con.execute("SET memory_limit='5GB'")
    con.execute("CREATE TABLE hb(k INT, xmin DOUBLE, xmax DOUBLE, ymin DOUBLE, ymax DOUBLE)")
    con.executemany("INSERT INTO hb VALUES (?,?,?,?,?)",
                    [(k, r[3].bounds[0], r[3].bounds[2], r[3].bounds[1], r[3].bounds[3]) for k, r in enumerate(need)])
    pairs = con.sql(f"""SELECT hb.k, a.id FROM read_parquet('{overture}/division_area/*.parquet') a JOIN hb
        ON a.bbox.xmin <= hb.xmax AND a.bbox.xmax >= hb.xmin AND a.bbox.ymin <= hb.ymax AND a.bbox.ymax >= hb.ymin
        WHERE a.class = 'land' AND a.subtype IN ('locality','localadmin','neighborhood','macrohood','microhood','borough')
        """).fetchall()
    con.execute("CREATE TABLE want(id VARCHAR)")
    con.executemany("INSERT INTO want VALUES (?)", [(a,) for a in sorted({a for _, a in pairs})])
    meta = {}
    for aid, subtype, name, geometry, item in con.sql(f"""SELECT a.id, a.subtype, a.names.primary, ST_AsWKB(a.geometry),
            d.wikidata FROM read_parquet('{overture}/division_area/*.parquet') a JOIN want w ON w.id = a.id
            LEFT JOIN read_parquet('{overture}/division/*.parquet') d ON d.id = a.division_id""").fetchall():
        meta[aid] = (subtype, name, item, shapely.make_valid(wkb.loads(bytes(geometry)).simplify(0.0002)))
    best = {}
    for k, aid in pairs:
        subtype, name, item, geometry = meta[aid]
        ring = need[k][3]
        try:
            inter = geometry.intersection(ring).area
        except Exception:  # noqa: BLE001 (a broken geometry is no filler)
            continue
        if inter <= 0 or geometry.area <= 0:
            continue
        frac_hole, frac_div = inter / ring.area, inter / geometry.area
        if frac_hole >= FILL_HOLE and frac_div >= FILL_INSIDE and (k not in best or frac_hole > best[k][1]):
            best[k] = (aid, frac_hole, frac_div)
    gn_of = wikidata_geonames(wikidata)
    fillers = []
    for k, (aid, frac_hole, frac_div) in sorted(best.items()):
        host, pi, hi, ring = need[k]
        subtype, name, item, _ = meta[aid]
        lat = ring.centroid.y
        km2 = ring.area * 111.32 ** 2 * abs(math.cos(math.radians(lat)))
        fillers.append((host, pi, hi, km2, subtype, name, item or "", gn_of.get(item, []) if item else [], frac_hole,
                        frac_div))
    print(f"holes with a non-county filler: {len(fillers)}", file=sys.stderr)
    return fillers


def main():
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument("--places", required=True)
    parser.add_argument("--out", required=True)
    parser.add_argument("--fillers", help="seed: the bot's box-data/hole-fillers.tsv")
    parser.add_argument("--holes", help="seed: the bot's box-data/holes-before.tsv (for the polygon index)")
    parser.add_argument("--fresh", action="store_true", help="ignore the rows of an existing --out (the list only grows)")
    parser.add_argument("--bounds", help="city-bounds.bin (full run)")
    parser.add_argument("--overture", help="Overture divisions dir (full run)")
    parser.add_argument("--wikidata", help="dir with wikidata-gn.tsv (full run)")
    args = parser.parse_args()
    city_ids, names = places_ids(args.places)
    if args.fillers:
        fillers = from_fillers(args.fillers, args.holes)
    else:
        if not (args.bounds and args.overture and args.wikidata):
            parser.error("--bounds, --overture and --wikidata, or --fillers")
        sys.path.insert(0, __import__("os").path.dirname(__import__("os").path.abspath(__file__)))
        fillers = from_overture(args.bounds, args.places, args.overture, args.wikidata + "/wikidata-gn.tsv")
    previous = [] if args.fresh else previous_rows(args.out)
    rows, stats = select(fillers, city_ids, names, previous)
    rows.sort(key=lambda r: (int(r[4]), str(r[6]), int(r[7]), r[0]))
    with open(args.out, "w", encoding="utf-8", newline="") as handle:
        handle.write("# P25 (SPEC §7, D135): GeoNames places that fill a hole in a kept city's outline; reason `add` = added as a\n")
        handle.write("# city by Scripts/build-places.py. Generated by data-tools/city-bounds/hole_places.py (never edit by hand).\n")
        handle.write("# Derived from Overture Maps divisions (© OpenStreetMap contributors, ODbL 1.0) and Wikidata (CC0); only the\n")
        handle.write("# GeoNames ids are read into places.json, no geometry.\n")
        writer = csv.writer(handle, delimiter="\t", lineterminator="\n")
        writer.writerow(HEADER)
        writer.writerows(rows)
    for key, count in sorted(stats.items(), key=lambda kv: (-kv[1], kv[0])):
        print(f"{count:6d}  {key}")
    print(f"wrote {args.out}: {len(rows)} rows, {sum(1 for r in rows if r[-1] == 'add')} to add")
    return 0


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