"""Bulk ring-vs-grid scorer for all Romanian OSM place nodes.

Reads (SSD temp): places.geojsonseq, highways.geojsonseq
Writes: scores.json (per-place results)

Method (v3, as shipped 2026-11-23):
- Original street segments are clipped to R = 500 m around the OSM place node;
  carried highway classes are selected in the prepared highways input.
- GRID = twice the smaller length share within +/-7 deg of the best
  perpendicular pair (5-deg steps).
- RING = circularity of the most circular 250-800 m closed loop found by the
  shortest-return search and enclosing the pin (else street centroid),
  multiplied by that loop's share of retained street length.
- Gate: >= 1,000 m of retained street and >= 6 ways, else scorable=false.
"""
import json, math, sys
import numpy as np

R = 500.0
TOL = 15.0
RMIN, RMAX = 40.0, 250.0
CMAX = 300.0
WIN = 7.0
MIN_LEN = 1000.0
MIN_WAYS = 6

RANK = {'city': 0, 'town': 1, 'village': 2, 'hamlet': 3, 'municipality': 4}


def feats(path):
    with open(path) as f:
        for line in f:
            line = line.lstrip('\x1e').strip()
            if line:
                yield json.loads(line)


def load_places(path, only=None):
    places = []
    for f in feats(path):
        g = f.get('geometry', {})
        if g.get('type') != 'Point':
            continue
        p = f.get('properties', {}) or {}
        name = p.get('name')
        if not name:
            continue
        if only and name not in only:
            continue
        lon, lat = g['coordinates']
        places.append({'name': name, 'place': p.get('place'),
                       'lat': lat, 'lon': lon,
                       'pop': p.get('population')})
    # dedupe: same name within 2 km -> keep best rank
    places.sort(key=lambda d: (d['name'], RANK.get(d['place'], 9)))
    out, seen = [], {}
    for d in places:
        key = d['name']
        if key in seen:
            q = seen[key]
            dd = math.hypot((d['lat'] - q['lat']) * 111200.0,
                            (d['lon'] - q['lon']) * 111320.0 *
                            math.cos(math.radians(d['lat'])))
            if dd < 2000.0:
                continue
        seen[key] = d
        out.append(d)
    return out


def grid_index(places, cell=0.02):
    idx = {}
    for i, d in enumerate(places):
        key = (int(d['lat'] / cell), int(d['lon'] / cell))
        idx.setdefault(key, []).append(i)
    return idx, cell


def collect(places, hwy_path):
    idx, cell = grid_index(places)
    per = [[] for _ in places]
    nways = [0 for _ in places]
    n = 0
    for f in feats(hwy_path):
        g = f.get('geometry', {})
        if g.get('type') != 'LineString':
            continue
        coords = g['coordinates']
        if len(coords) < 2:
            continue
        n += 1
        lats = [c[1] for c in coords]
        lons = [c[0] for c in coords]
        # candidate cells via bbox expanded by R
        lat0, lat1 = min(lats), max(lats)
        lon0, lon1 = min(lons), max(lons)
        dlat = R / 111200.0
        dlon = R / (111320.0 * math.cos(math.radians((lat0 + lat1) / 2)))
        cand = set()
        cx0, cx1 = int((lat0 - dlat) / cell), int((lat1 + dlat) / cell)
        cy0, cy1 = int((lon0 - dlon) / cell), int((lon1 + dlon) / cell)
        for ix in range(cx0, cx1 + 1):
            for iy in range(cy0, cy1 + 1):
                for i in idx.get((ix, iy), ()):
                    cand.add(i)
        for i in cand:
            d = places[i]
            kx = 111320.0 * math.cos(math.radians(d['lat']))
            ky = 111200.0
            pts = [((lon - d['lon']) * kx, (lat - d['lat']) * ky)
                   for lon, lat in coords]
            # Clip each original segment to the R-circle (2026-11-23): dropping
            # out-of-window vertices joined the survivors with artificial chords.
            clipped = []
            for j in range(1, len(pts)):
                (x1, y1), (x2, y2) = pts[j - 1], pts[j]
                dx, dy = x2 - x1, y2 - y1
                A = dx * dx + dy * dy
                if A == 0:
                    continue
                B = 2 * (x1 * dx + y1 * dy)
                C = x1 * x1 + y1 * y1 - R * R
                disc = B * B - 4 * A * C
                if disc < 0:
                    continue
                sq = math.sqrt(disc)
                t0 = max(0.0, (-B - sq) / (2 * A))
                t1 = min(1.0, (-B + sq) / (2 * A))
                if t1 <= t0:
                    continue
                clipped.append(((x1 + dx * t0, y1 + dy * t0),
                                (x1 + dx * t1, y1 + dy * t1)))
            if clipped:
                nways[i] += 1
                for (x1, y1), (x2, y2) in clipped:
                    L = math.hypot(x2 - x1, y2 - y1)
                    if L >= 0.5:
                        per[i].append((x1, y1, x2, y2, L))
    return per, nways, n


def grid_score(segs):
    tot = sum(s[4] for s in segs)
    bears = np.array([math.degrees(math.atan2(x2 - x1, y2 - y1)) % 180.0
                      for x1, y1, x2, y2, L in segs])
    w = np.array([s[4] for s in segs])
    best, besta = 0.0, 0.0
    for a in np.arange(0.0, 180.0, 5.0):
        d1 = np.abs((bears - a + 90.0) % 180.0 - 90.0)
        d2 = np.abs((bears - a - 90.0 + 90.0) % 180.0 - 90.0)
        s1 = w[d1 <= WIN].sum()
        s2 = w[d2 <= WIN].sum()
        bal = 2 * min(s1, s2) / tot
        if bal > best:
            best, besta = bal, a
    rose = [0] * 18
    for b, wi in zip(bears, w):
        rose[int(b // 10) % 18] += wi
    rose = [int(round(1000 * x / tot)) if tot else 0 for x in rose]
    return best, float(besta), rose


LOOP_MIN, LOOP_MAX = 250.0, 800.0


def best_loop(segs):
    """Return (circularity, length_m, middle_kind, polygon_points) or None."""
    import loops as LP
    import math as _m
    nodes, adj, edges = LP.build_graph(segs)
    tot = sum(s[4] for s in segs)
    cx = sum((x1 + x2) / 2 * L for x1, y1, x2, y2, L in segs) / tot
    cy = sum((y1 + y2) / 2 * L for x1, y1, x2, y2, L in segs) / tot
    best = None
    for ei, (a, b, L, geom) in enumerate(edges):
        path, plen = LP.shortest_path(adj, a, b, ei)
        if path is None:
            continue
        cyc = path + [ei]
        total = plen + L
        if not (LOOP_MIN <= total <= LOOP_MAX):
            continue
        pts = LP.cycle_polygon(nodes, edges, cyc)
        if len(pts) < 3:
            continue
        area = LP.shoelace(pts)
        circ = 4 * _m.pi * area / (total * total)
        if LP.point_in_poly(0.0, 0.0, pts):
            mid = 'pin'
        elif LP.point_in_poly(cx, cy, pts):
            mid = 'centroid'
        else:
            continue
        if best is None or circ > best[0]:
            best = (circ, total, mid, pts)
    return best


def ring_score(segs):
    best = best_loop(segs)
    if best is None:
        return 0.0, None
    circ, total, mid, _pts = best
    tot = sum(s[4] for s in segs)
    share = total / tot
    return circ * share, (round(circ, 3), round(total, 1), mid,
                              round(share, 3))


def main():
    only = None
    chunk = None
    if len(sys.argv) > 1 and '/' in sys.argv[1]:
        c, n = sys.argv[1].split('/')
        chunk = (int(c), int(n))
    elif len(sys.argv) > 1:
        only = set(sys.argv[1].split(','))
    places = load_places('places.geojsonseq', only)
    if chunk:
        c, n = chunk
        places = [p for i, p in enumerate(places) if i % n == c]
    print('places:', len(places), flush=True)
    per, nways, n = collect(places, 'highways.geojsonseq')
    print('ways streamed:', n, flush=True)
    out = []
    for d, segs, nw in zip(places, per, nways):
        tot = sum(s[4] for s in segs)
        row = {'name': d['name'], 'place': d['place'], 'lat': d['lat'],
               'lon': d['lon'], 'length_m': round(tot), 'ways': nw}
        if tot < MIN_LEN or nw < MIN_WAYS:
            row['scorable'] = False
        else:
            ring, loop = ring_score(segs)
            grid, ang, rose = grid_score(segs)
            row.update({'scorable': True, 'ring': round(float(ring), 3),
                        'grid': round(float(grid), 3),
                        'loop': loop, 'grid_angle': ang, 'rose': rose})
        out.append(row)
        if only:
            print(row, flush=True)
    tag = 'scores-calib.json' if only else (
        'scores.json' if chunk is None else 'scores-c%d.json' % chunk[0])
    json.dump(out, open(tag, 'w'), ensure_ascii=False)
    print('wrote', tag, flush=True)


if __name__ == '__main__':
    main()
