#!/usr/bin/env python3
"""P25 (SPEC §7, §21, D135; Yo t113u): the city-limits data invariants, checked when the data is built.

The same rules, thresholds and point algorithm as AppCoreTests' `DataInvariantTests` (Tests/AppCoreTests), so the build
and the tests agree:
  (a) every outline id in city-bounds.bin is a city in places.json (not an alias, not missing); every hole ring of an
      outline has a city: its interior point (below) lies inside an outline (another city's, or the city's own other
      part) -- a ring with no inside at any level (a zero-area sliver) is degenerate and skipped -- except the holes listed in holes-without-city.tsv (the baseline: the holes that still have no city, the
      open tiling question, Yo t115u). No hole outside the baseline may lack a city, and the baseline never grows.
  (b) every city with an outline can be selected inside it: one of its candidate interior points (below) lies inside
      the outline and in no other outline;
  (c) or, when every candidate is also inside another outline (the city lies fully over or inside another), the city is
      the innermost (smallest km², then the lower id, D131) containing outline at one of them. A city that fails both
      is listed in unselectable-cities.tsv (the baseline, also a ratchet). The app test runs the real resolver
      (`CityHitIndex`, the function a tap and a press use) at those points.

Interior points (deterministic, exact in integer coordinates, identical in Swift): the bin stores vertices as integers
(degrees x 100,000). A horizontal line at y = floor(minY + (maxY - minY) * n / d) + 0.5 (never through a vertex) for
the levels n/d = 1/2, 1/4, 3/4, 1/8, 3/8, 5/8, 7/8 of the ring's (or polygon's outer ring's) box crosses the rings at
x = x1 + (y - y1) * (x2 - x1) / (y2 - y1) for every edge (x1, y1) -> (x2, y2) with (y1 > y) != (y2 > y); sorted, the
crossings pair up into inside intervals (even-odd). A hole's point: the middle of the widest interval of the hole ring
alone at the first level that has one (ties: the leftmost). A city's candidates: for each of its first 4 polygons (in
file order), each level, the middles of the 2 widest intervals of the polygon (outer ring and holes). Containment is
the app's ray cast (`ShapeHitTester.ringContains`) on degrees = integer / 100,000.

Usage:
  invariants.py --bounds App/Resources/city-bounds.bin --places App/Resources/places.json \
      [--baseline-dir data-tools/city-bounds] [--write-baselines] [--allow-growth]
Exit 1 when an invariant fails (a hole or city outside its baseline, or a baseline that grew). `--write-baselines`
rewrites holes-without-city.tsv and unselectable-cities.tsv from this data (refused when a count grows, unless
`--allow-growth`, which needs Yo's approval: the counts are a ratchet). Standard library only.
"""
import argparse
import json
import os
import struct
import sys
from collections import defaultdict

SCALE = 100_000
LEVELS = [(1, 2), (1, 4), (3, 4), (1, 8), (3, 8), (5, 8), (7, 8)]
MAX_POLYGONS = 4
PER_LEVEL = 2
HOLES_BASELINE = "holes-without-city.tsv"
CITIES_BASELINE = "unselectable-cities.tsv"


class Outline:
    __slots__ = ("id", "box", "area", "polygons", "rings_int")

    def __init__(self, gid, box, area, rings_int):
        self.id = gid
        self.box = box                    # (min lon, min lat, max lon, max lat) in degrees, as the index stores them
        self.area = area                  # Float32 km2, as stored
        self.rings_int = rings_int        # [polygon][ring] -> [(x, y)] integers, not closed
        self.polygons = [[[c / SCALE for xy in ring for c in xy] for ring in polygon] for polygon in rings_int]

    def contains(self, lat, lon):
        minx, miny, maxx, maxy = self.box
        if not (miny <= lat <= maxy and minx <= lon <= maxx):
            return False
        return any(polygon_contains(p, lat, lon) for p in self.polygons)


def ring_contains(ring, y, x):
    """`ShapeHitTester.ringContains` on a flat, not closed [lon, lat, ...] ring (the closing edge included)."""
    n = len(ring) // 2
    if n < 3:
        return False
    inside = False
    j = n - 1
    for i in range(n):
        xi, yi, xj, yj = ring[2 * i], ring[2 * i + 1], ring[2 * j], ring[2 * j + 1]
        if (yi > y) != (yj > y) and x < (xj - xi) * (y - yi) / (yj - yi) + xi:
            inside = not inside
        j = i
    return inside


def polygon_contains(polygon, lat, lon):
    return ring_contains(polygon[0], lat, lon) and not any(ring_contains(h, lat, lon) for h in polygon[1:])


def read_bounds(path):
    """Every outline of city-bounds.bin (format in README.md), integers kept."""
    data = open(path, "rb").read()
    assert data[:4] == b"PCB1", "not a PCB1 file"
    count = struct.unpack_from("<I", data, 4)[0]
    base = 12 + 32 * count
    result = []
    for k in range(count):
        gid, minx, miny, maxx, maxy, offset, _length, area = struct.unpack_from("<IiiiiIIf", data, 12 + 32 * k)
        p = base + offset
        polygons = []
        (npoly,) = struct.unpack_from("<H", data, p); p += 2
        for _ in range(npoly):
            (nring,) = struct.unpack_from("<H", data, p); p += 2
            rings = []
            for _ in range(nring):
                (nv,) = struct.unpack_from("<I", data, p); p += 4
                x, y = struct.unpack_from("<ii", data, p); p += 8
                ring = [(x, y)]
                for _ in range(nv - 1):
                    for axis in range(2):
                        r = s = 0
                        while True:
                            b = data[p]; p += 1
                            r |= (b & 0x7F) << s; s += 7
                            if b < 0x80:
                                break
                        d = (r >> 1) ^ -(r & 1)
                        if axis == 0:
                            x += d
                        else:
                            y += d
                    ring.append((x, y))
                rings.append(ring)
            polygons.append(rings)
        result.append(Outline(gid, (minx / SCALE, miny / SCALE, maxx / SCALE, maxy / SCALE), float(area), polygons))
    return result


def intervals(rings, y):
    """Inside intervals of integer rings on the line at y (even-odd)."""
    xs = []
    for ring in rings:
        n = len(ring)
        for i in range(n):
            x1, y1 = ring[i - 1]
            x2, y2 = ring[i]
            if (y1 > y) != (y2 > y):
                xs.append(x1 + (y - y1) * (x2 - x1) / (y2 - y1))
    xs.sort()
    return [(xs[k], xs[k + 1]) for k in range(0, len(xs) - 1, 2)]


def level_y(ring, n, d):
    ys = [p[1] for p in ring]
    lo, hi = min(ys), max(ys)
    return lo + (hi - lo) * n // d + 0.5


def hole_point(ring):
    """A hole ring's interior point (lat, lon), or None (a degenerate ring)."""
    for n, d in LEVELS:
        y = level_y(ring, n, d)
        best = None
        for a, b in intervals([ring], y):
            if b > a and (best is None or b - a > best[1] - best[0]):
                best = (a, b)
        if best:
            return y / SCALE, (best[0] + best[1]) / 2 / SCALE
    return None


def city_points(outline):
    """A city's candidate interior points (lat, lon), in order."""
    points = []
    for polygon in outline.rings_int[:MAX_POLYGONS]:
        for n, d in LEVELS:
            y = level_y(polygon[0], n, d)
            found = [(a, b) for a, b in intervals(polygon, y) if b > a]
            found.sort(key=lambda ab: (-(ab[1] - ab[0]), ab[0]))
            for a, b in found[:PER_LEVEL]:
                points.append((y / SCALE, (a + b) / 2 / SCALE))
    return points


class Grid:
    """1-degree cells of the outlines' boxes (as CityBoundsFile)."""

    def __init__(self, outlines):
        import math
        self.cells = defaultdict(list)
        for o in outlines:
            minx, miny, maxx, maxy = o.box
            for la in range(math.floor(miny), math.floor(maxy) + 1):
                for lo in range(math.floor(minx), math.floor(maxx) + 1):
                    self.cells[(la, lo)].append(o)

    def containing(self, lat, lon):
        import math
        return [o for o in self.cells.get((math.floor(lat), math.floor(lon)), ()) if o.contains(lat, lon)]


def check(outlines, city_ids):
    """(a)-(c) on the data. Returns (ids not in places, holes without a city, unselectable cities, stats)."""
    grid = Grid(outlines)
    missing = sorted(o.id for o in outlines if o.id not in city_ids)
    holes = []
    hole_count = degenerate = 0
    for o in outlines:
        for pi, polygon in enumerate(o.rings_int):
            for hi, ring in enumerate(polygon[1:]):
                hole_count += 1
                point = hole_point(ring)
                if point is None:
                    degenerate += 1  # no inside at any level (a zero-area sliver): no tap lands in it
                elif not grid.containing(*point):
                    holes.append((o.id, pi, hi, point, hole_area_km2(ring)))
    unselectable = []
    covered_only = 0
    for o in outlines:
        free = innermost = False
        for lat, lon in city_points(o):
            if not o.contains(lat, lon):
                continue
            inside = grid.containing(lat, lon)
            others = [c for c in inside if c.id != o.id]
            if not others:
                free = True
                break
            best = min(inside, key=lambda c: (c.area, c.id))
            if best.id == o.id:
                innermost = True
        if not free:
            covered_only += 1
            if not innermost:
                unselectable.append(o.id)
    stats = {"outlines": len(outlines), "holes": hole_count, "degenerate_holes": degenerate, "holes_without_city": len(holes),
             "cities_covered_by_others": covered_only, "unselectable": len(unselectable)}
    return missing, holes, unselectable, stats


def hole_area_km2(ring):
    import math
    lat0 = sum(p[1] for p in ring) / len(ring) / SCALE
    s = 0
    for i in range(len(ring)):
        x1, y1 = ring[i - 1]
        x2, y2 = ring[i]
        s += x1 * y2 - x2 * y1
    return abs(s) / 2 / SCALE ** 2 * 111.32 * 110.574 * math.cos(math.radians(lat0))


def read_baseline(path, width):
    if not os.path.exists(path):
        return None
    keys = set()
    with open(path, encoding="utf-8") as handle:
        for line in handle:
            if line.startswith("#") or not line.strip():
                continue
            parts = line.rstrip("\n").split("\t")
            if parts[0] in ("city", "id"):
                continue
            keys.add(tuple(int(v) for v in parts[:width]))
    return keys


def write_baselines(directory, holes, unselectable, names):
    with open(os.path.join(directory, HOLES_BASELINE), "w", encoding="utf-8") as handle:
        handle.write("# P25 (SPEC §7, D135): holes in a city outline that still have no city (no outline covers the hole's\n")
        handle.write("# interior point). Baseline and ratchet for DataInvariantTests and invariants.py; never grows. Generated by\n")
        handle.write("# data-tools/city-bounds/invariants.py --write-baselines. Derived from city-bounds.bin (ODbL 1.0).\n")
        handle.write("city\tpoly\thole\tlat\tlon\tkm2\tname\n")
        for gid, pi, hi, (lat, lon), km2 in sorted(holes, key=lambda h: h[:3]):
            handle.write(f"{gid}\t{pi}\t{hi}\t{lat}\t{lon}\t{km2:.3f}\t{names.get(gid, '')}\n")
    with open(os.path.join(directory, CITIES_BASELINE), "w", encoding="utf-8") as handle:
        handle.write("# P25 (SPEC §21, D135): cities with an outline that no interior point selects (fully under a smaller\n")
        handle.write("# outline). Baseline and ratchet for DataInvariantTests and invariants.py; never grows.\n")
        handle.write("id\tname\n")
        for gid in sorted(unselectable):
            handle.write(f"{gid}\t{names.get(gid, '')}\n")


def run(bounds, places, baseline_dir, write=False, allow_growth=False, outlines=None):
    """Checks (a)-(c) against the baselines. Returns the exit code."""
    rows = json.load(open(places, encoding="utf-8"))["cities"]
    city_ids = {row[0] for row in rows}
    names = {row[0]: row[1] for row in rows}
    outlines = outlines if outlines is not None else read_bounds(bounds)
    missing, holes, unselectable, stats = check(outlines, city_ids)
    print("invariants:", json.dumps(stats))
    failed = False
    if missing:
        print(f"FAIL (a): {len(missing)} outline ids are not cities in places.json: {missing[:20]}")
        failed = True
    hole_keys = {h[:3] for h in holes}
    old_holes = read_baseline(os.path.join(baseline_dir, HOLES_BASELINE), 3)
    old_cities = read_baseline(os.path.join(baseline_dir, CITIES_BASELINE), 1)
    if write:
        grew = [(n, len(new), len(old)) for n, new, old in
                ((HOLES_BASELINE, hole_keys, old_holes), (CITIES_BASELINE, unselectable, old_cities))
                if old is not None and len(new) > len(old)]
        if grew and not allow_growth:
            print(f"FAIL: a baseline would grow (ratchet, needs Yo): {grew}")
            return 1
        write_baselines(baseline_dir, holes, unselectable, names)
        print(f"wrote baselines: {len(holes)} holes without a city, {len(unselectable)} unselectable cities")
        return 1 if failed else 0
    if old_holes is None or old_cities is None:
        print("FAIL: no baseline (run with --write-baselines once)")
        return 1
    new_holes = sorted(hole_keys - old_holes)
    if new_holes:
        print(f"FAIL (a): {len(new_holes)} holes without a city are not in {HOLES_BASELINE}: {new_holes[:20]}")
        failed = True
    new_cities = sorted(set(unselectable) - {k[0] for k in old_cities})
    if new_cities:
        print(f"FAIL (b/c): {len(new_cities)} cities can't be selected and aren't in {CITIES_BASELINE}: {new_cities[:20]}")
        failed = True
    print(f"holes without a city: {len(holes)} (baseline {len(old_holes)}); unselectable cities: {len(unselectable)} "
          f"(baseline {len(old_cities)})")
    if len(old_holes) > len(hole_keys) or len(old_cities) > len(unselectable):
        print("note: fewer than the baseline; run --write-baselines to lower it (the ratchet)")
    return 1 if failed else 0


def main():
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    here = os.path.dirname(os.path.abspath(__file__))
    parser.add_argument("--bounds", required=True)
    parser.add_argument("--places", required=True)
    parser.add_argument("--baseline-dir", default=here)
    parser.add_argument("--write-baselines", action="store_true")
    parser.add_argument("--allow-growth", action="store_true")
    args = parser.parse_args()
    return run(args.bounds, args.places, args.baseline_dir, args.write_baselines, args.allow_growth)


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