"""Loop-road detector: finds the most circular closed street loop
enclosing the village middle. Research prototype."""

import heapq
import math


def build_graph(segs, snap=5.0):
    def key(x, y):
        return (round(x / snap), round(y / snap))

    nodes = {}
    adj = {}

    def nid(x, y):
        k = key(x, y)
        if k not in nodes:
            nodes[k] = (x, y)
            adj[k] = []
        return k

    edges = []
    for x1, y1, x2, y2, L in segs:
        a, b = nid(x1, y1), nid(x2, y2)
        if a == b:
            continue
        ei = len(edges)
        edges.append((a, b, L, (x1, y1, x2, y2)))
        adj[a].append((b, L, ei))
        adj[b].append((a, L, ei))
    return nodes, adj, edges


def shortest_path(adj, src, dst, ban):
    dist = {src: 0.0}
    prev = {}
    pq = [(0.0, src)]
    while pq:
        d, u = heapq.heappop(pq)
        if u == dst:
            break
        if d > dist.get(u, float('inf')):
            continue
        for v, L, ei in adj[u]:
            if ei == ban:
                continue
            nd = d + L
            if nd < dist.get(v, float('inf')):
                dist[v] = nd
                prev[v] = (u, ei)
                heapq.heappush(pq, (nd, v))
    if dst not in dist:
        return None, float('inf')
    path = []
    u = dst
    while u != src:
        u, ei = prev[u][0], prev[u][1]
        path.append(ei)
    return path, dist[dst]


def cycle_polygon(nodes, edges, eis):
    # Vertices in TRAVEL ORDER around the cycle (2026-11-23): walk the edge
    # ring node to node; the old start-point collection self-intersected on
    # reversed OSM ways and understated area/circularity.
    if not eis:
        return []
    nxt = {}
    for ei in eis:
        a, b, L, geom = edges[ei]
        nxt.setdefault(a, []).append((b, ei))
        nxt.setdefault(b, []).append((a, ei))
    start = edges[eis[0]][0]
    pts = [nodes[start]]
    cur, prev_ei = start, None
    for _ in range(len(eis)):
        cands = [(nb, ei) for nb, ei in nxt.get(cur, []) if ei != prev_ei]
        if not cands:
            break
        nb, ei = cands[0]
        if nb != start:
            pts.append(nodes[nb])
        cur, prev_ei = nb, ei
        if cur == start:
            break
    return pts


def shoelace(pts):
    s = 0.0
    n = len(pts)
    for i in range(n):
        x1, y1 = pts[i]
        x2, y2 = pts[(i + 1) % n]
        s += x1 * y2 - x2 * y1
    return abs(s) / 2.0


def point_in_poly(px, py, pts):
    inside = False
    n = len(pts)
    for i in range(n):
        x1, y1 = pts[i]
        x2, y2 = pts[(i + 1) % n]
        if (y1 > py) != (y2 > py):
            xi = x1 + (py - y1) * (x2 - x1) / (y2 - y1)
            if xi > px:
                inside = not inside
    return inside


def best_loop(segs, min_len=250.0):
    nodes, adj, edges = build_graph(segs)
    if len(edges) < 3:
        return None
    cands = []
    for ei, (a, b, L, geom) in enumerate(edges):
        path, plen = shortest_path(adj, a, b, ei)
        if path is None:
            continue
        cyc = path + [ei]
        total = plen + L
        if total < min_len:
            continue
        pts = cycle_polygon(nodes, edges, cyc)
        if len(pts) < 3:
            continue
        area = shoelace(pts)
        circ = 4 * math.pi * area / (total * total) if total > 0 else 0
        encloses = point_in_poly(0.0, 0.0, pts)
        cands.append((circ, total, encloses, cyc))
    if not cands:
        return None
    enc = [c for c in cands if c[2]]
    pool = enc if enc else []
    if not pool:
        return {'ring': 0.0, 'loops': len(cands), 'enclosing': 0}
    pool.sort(reverse=True)
    circ, total, _, cyc = pool[0]
    return {'ring': round(circ, 3), 'loop_m': round(total),
            'loops': len(cands), 'enclosing': len(enc)}
