"""Builds Ondulo's bundled green-lanes file (public/lanes.json, format v2) from OpenStreetMap extracts (.osm.pbf).

Keeps ways that the map says are open to motor traffic as green lanes:
  designation=byway_open_to_all_traffic, designation=unclassified_county_road / unclassified_highway (on a track, or on a
  road that is mapped as unpaved), and highway=byway (status not recorded).
Drops anything closed to motorcycles, private, or under a conditional / seasonal order.
Joins lanes that were split into several OSM ways, simplifies the shape and writes compact JSON.

Each lane is [kind, surface, len, name, enc5, grade, dead, flags, wid]:
  kind     B byway open to all traffic, U unclassified county road / unsurfaced public road, Y byway, status not recorded
  surface  u unpaved, p paved, '' unknown
  len      metres
  name     name or ref ('' if none)
  enc5     Google polyline, precision 5
  grade    0 unknown, 1 easy, 2 moderate, 3 hard (hardest of the joined ways; from tracktype, smoothness, surface, 4wd_only)
  dead     0 both ends meet a public motor road or another lane, 1 one end goes nowhere a motor vehicle can use
           (there-and-back), 2 neither end does
  flags    bitmask: 1 ford on the lane, 2 gate on the lane, 4 steep (incline 15 % or more, or "steep")
  wid      smallest OSM way id in the joined chain (a stable key across rebuilds)

usage: python -I extract_lanes.py out.json in1.osm.pbf [in2.osm.pbf ...]
"""
import json, math, re, sys, time
import osmium
from osmium.filter import TagFilter, IdFilter, KeyFilter

UNPAVED = {'unpaved', 'gravel', 'fine_gravel', 'dirt', 'earth', 'ground', 'grass', 'mud', 'compacted', 'rock', 'stone',
           'stones', 'pebblestone', 'sand', 'woodchips', 'grass_paver', 'shells', 'clay', 'loose_gravel', 'scree'}
PAVED = {'asphalt', 'paved', 'concrete', 'sett', 'paving_stones', 'chipseal', 'concrete:plates', 'concrete:lanes',
         'metal', 'wood', 'cobblestone', 'unhewn_cobblestone', 'bricks'}
CLOSED = {'no', 'private', 'forestry', 'agricultural', 'permit', 'delivery', 'customers'}
# roads a motor vehicle can leave a lane onto
MOTOR = {'motorway', 'motorway_link', 'trunk', 'trunk_link', 'primary', 'primary_link', 'secondary', 'secondary_link',
         'tertiary', 'tertiary_link', 'unclassified', 'residential', 'living_street', 'service', 'road'}

# how hard a lane is, per tag value (0 = says nothing)
TRACKTYPE = {'grade1': 1, 'grade2': 1, 'grade3': 2, 'grade4': 3, 'grade5': 3}
SMOOTH = {'excellent': 1, 'good': 1, 'intermediate': 1, 'bad': 2, 'very_bad': 2, 'horrible': 3, 'very_horrible': 3,
          'impassable': 3}
SURF_GRADE = {'asphalt': 1, 'paved': 1, 'concrete': 1, 'chipseal': 1, 'sett': 1, 'paving_stones': 1, 'compacted': 1,
              'fine_gravel': 1, 'gravel': 1, 'grass_paver': 1,
              'unpaved': 2, 'dirt': 2, 'earth': 2, 'ground': 2, 'grass': 2, 'sand': 2, 'stones': 2, 'pebblestone': 2,
              'loose_gravel': 2, 'clay': 2, 'woodchips': 2, 'stone': 2,
              'mud': 3, 'rock': 3, 'scree': 3}


def kind_of(t):
    des, hw = t.get('designation', ''), t.get('highway', '')
    if des == 'byway_open_to_all_traffic':
        return 'B'
    # unsurfaced public roads: the older UK tag and the one Wales mostly uses. A track always counts; a road only
    # when the map says it is unpaved (otherwise it is an ordinary tarmac lane).
    if des in ('unclassified_county_road', 'unclassified_highway'):
        if hw == 'track' or (hw in ('unclassified', 'service', 'road') and surface_of(t) == 'u'):
            return 'U'
    if hw == 'byway' and not any(x in des for x in ('restricted', 'bridleway', 'footpath')):
        return 'Y'
    return None


def open_to_bikes(t):
    for k in ('motorcycle', 'motor_vehicle', 'vehicle', 'access'):
        v = t.get(k)
        if v is None:
            continue
        if v in ('yes', 'designated', 'permissive', 'destination'):
            return True          # the most specific key that is set decides
        if v in CLOSED:
            return False
    return True


def motor_ok(t):
    """An ordinary road counts as a way out of a lane unless it is closed to motor traffic."""
    for k in ('motor_vehicle', 'vehicle', 'access'):
        v = t.get(k)
        if v is None:
            continue
        if v in ('yes', 'designated', 'permissive', 'destination'):
            return True
        if v in ('no', 'private'):
            return False
    return True


def conditional(t):
    return any(k.endswith(':conditional') and k.split(':')[0] in ('motorcycle', 'motor_vehicle', 'vehicle', 'access') for k in t)


def surface_of(t):
    s = t.get('surface', '')
    if s in UNPAVED or t.get('tracktype') in ('grade2', 'grade3', 'grade4', 'grade5'):
        return 'u'
    if s in PAVED or t.get('tracktype') == 'grade1':
        return 'p'
    return ''


def grade_of(t):
    g = max(TRACKTYPE.get(t.get('tracktype', ''), 0), SMOOTH.get(t.get('smoothness', ''), 0),
            SURF_GRADE.get(t.get('surface', ''), 0))
    if t.get('4wd_only') in ('yes', 'recommended'):
        g = 3
    return g


def steep(v):
    if not v:
        return False
    v = v.strip().lower()
    if v == 'steep':
        return True
    m = re.match(r'^[-+]?\s*(\d+(?:\.\d+)?)\s*(%|°)?', v)
    if not m:
        return False
    x = float(m.group(1))
    if m.group(2) == '°':
        x = math.tan(math.radians(x)) * 100
    return x >= 15


def hav(a, b):
    R = 6371000.0
    p1, p2 = math.radians(a[0]), math.radians(b[0])
    dp, dl = p2 - p1, math.radians(b[1] - a[1])
    h = math.sin(dp / 2) ** 2 + math.cos(p1) * math.cos(p2) * math.sin(dl / 2) ** 2
    return 2 * R * math.asin(math.sqrt(h))


def simplify(pts, tol=15.0):
    """Douglas-Peucker in local metres."""
    if len(pts) < 3:
        return pts
    lat0 = math.radians(pts[0][0])
    xy = [((p[1]) * 111320 * math.cos(lat0), p[0] * 110540) for p in pts]
    keep = [False] * len(pts)
    keep[0] = keep[-1] = True
    stack = [(0, len(pts) - 1)]
    while stack:
        i, j = stack.pop()
        ax, ay = xy[i]; bx, by = xy[j]
        dx, dy = bx - ax, by - ay
        L2 = dx * dx + dy * dy or 1e-9
        best, bi = -1.0, -1
        for k in range(i + 1, j):
            px, py = xy[k]
            u = max(0.0, min(1.0, ((px - ax) * dx + (py - ay) * dy) / L2))
            d = math.hypot(px - (ax + u * dx), py - (ay + u * dy))
            if d > best:
                best, bi = d, k
        if best > tol:
            keep[bi] = True
            stack += [(i, bi), (bi, j)]
    return [p for p, k in zip(pts, keep) if k]


def encode(pts, prec=5):
    f = 10 ** prec
    out, plat, plon = [], 0, 0
    for lat, lon in pts:
        ilat, ilon = round(lat * f), round(lon * f)
        for v in (ilat - plat, ilon - plon):
            v = ~(v << 1) if v < 0 else (v << 1)
            while v >= 0x20:
                out.append(chr((0x20 | (v & 0x1f)) + 63))
                v >>= 5
            out.append(chr(v + 63))
        plat, plon = ilat, ilon
    return ''.join(out)


def main(out_path, inputs):
    t0 = time.time()
    ways, dropped = {}, {'closed': 0, 'conditional': 0}
    filt = TagFilter(('designation', 'byway_open_to_all_traffic'), ('designation', 'unclassified_county_road'),
                     ('designation', 'unclassified_highway'), ('highway', 'byway'))
    for path in inputs:
        for w in osmium.FileProcessor(path, osmium.osm.WAY).with_filter(filt):
            if w.id in ways:
                continue         # a way near the border is in both extracts
            t = {tag.k: tag.v for tag in w.tags}
            k = kind_of(t)
            if not k:
                continue
            if not open_to_bikes(t):
                dropped['closed'] += 1
                continue
            if conditional(t):
                dropped['conditional'] += 1
                continue
            fl = (1 if t.get('ford') in ('yes', 'stepping_stones') else 0) | (4 if steep(t.get('incline')) else 0)
            ways[w.id] = {'k': k, 's': surface_of(t), 'n': t.get('name') or t.get('ref') or '', 'g': grade_of(t), 'f': fl,
                          'nodes': [n.ref for n in w.nodes]}
        print(f'{path}: {len(ways)} lane ways so far, dropped {dropped}, {time.time() - t0:.0f}s', flush=True)

    need = set()
    for w in ways.values():
        need.update(w['nodes'])
    loc, ford, gate = {}, set(), set()
    for path in inputs:
        for n in osmium.FileProcessor(path, osmium.osm.NODE).with_filter(IdFilter(need)):
            loc[n.id] = (n.location.lat, n.location.lon)
            if n.tags.get('ford') in ('yes', 'stepping_stones'):
                ford.add(n.id)
            if n.tags.get('barrier') in ('gate', 'lift_gate', 'swing_gate'):
                gate.add(n.id)
    print(f'node locations: {len(loc)} of {len(need)}, fords {len(ford)}, gates {len(gate)}, {time.time() - t0:.0f}s', flush=True)

    # join ways that continue each other (same kind, meeting at a node no other lane way touches)
    ends = {}
    for wid, w in ways.items():
        for nd in (w['nodes'][0], w['nodes'][-1]):
            ends.setdefault(nd, []).append(wid)
    used, chains = set(), []
    for wid in ways:
        if wid in used:
            continue
        used.add(wid)
        w = ways[wid]
        seq, kind = list(w['nodes']), w['k']
        members = [wid]
        for forward in (True, False):
            while True:
                tip = seq[-1] if forward else seq[0]
                nxt = [x for x in ends.get(tip, []) if x not in used and ways[x]['k'] == kind]
                if len(ends.get(tip, [])) != 2 or len(nxt) != 1:
                    break
                x = nxt[0]; used.add(x)
                ns = ways[x]['nodes']
                if forward:
                    seq += (ns if ns[0] == tip else ns[::-1])[1:]
                else:
                    seq = (ns if ns[-1] == tip else ns[::-1])[:-1] + seq
                members.append(x)
        chains.append((seq, kind, members))

    # which lane ends meet a road a motor vehicle can use (or another lane)
    tips = set()
    for seq, _, _ in chains:
        tips.add(seq[0]); tips.add(seq[-1])
    on_road = set()
    for path in inputs:
        for w in osmium.FileProcessor(path, osmium.osm.WAY).with_filter(KeyFilter('highway')):
            if w.id in ways or w.tags.get('highway') not in MOTOR:
                continue
            if not motor_ok({tag.k: tag.v for tag in w.tags}):
                continue
            for n in w.nodes:
                if n.ref in tips:
                    on_road.add(n.ref)
    lane_nodes = {}
    for ci, (seq, _, _) in enumerate(chains):
        for nd in seq:
            lane_nodes.setdefault(nd, set()).add(ci)
    print(f'lane ends on a motor road: {len(on_road)} of {len(tips)}, {time.time() - t0:.0f}s', flush=True)

    out = []
    for ci, (seq, kind, members) in enumerate(chains):
        pts = [loc[n] for n in seq if n in loc]
        if len(pts) < 2:
            continue
        length = sum(hav(pts[i - 1], pts[i]) for i in range(1, len(pts)))
        if length < 150:
            continue
        surf = [ways[m]['s'] for m in members]
        s = 'u' if 'u' in surf else ('p' if all(x == 'p' for x in surf) else '')
        name = next((ways[m]['n'] for m in members if ways[m]['n']), '')
        grade = max(ways[m]['g'] for m in members)
        flags = 0
        for m in members:
            flags |= ways[m]['f']
        if any(n in ford for n in seq):
            flags |= 1
        if any(n in gate for n in seq):
            flags |= 2

        def connected(nd):
            return nd in on_road or len(lane_nodes.get(nd, ())) > 1
        if seq[0] == seq[-1]:
            dead = 0 if connected(seq[0]) else 2
        else:
            dead = (0 if connected(seq[0]) else 1) + (0 if connected(seq[-1]) else 1)
        out.append([kind, s, round(length), name, encode(simplify(pts)), grade, dead, flags, min(members)])

    out.sort(key=lambda c: -c[2])
    doc = {'v': 2, 'built': time.strftime('%Y-%m-%d'), 'source': 'OpenStreetMap contributors (ODbL), via Geofabrik extracts',
           'note': ('each lane is [kind, surface, len m, name, polyline5, grade, dead, flags, wid]. kind B byway open to all '
                    'traffic, U unclassified county road, Y byway with status not recorded; surface u unpaved, p paved, blank '
                    'unknown; grade 0 unknown, 1 easy, 2 moderate, 3 hard; dead 0 both ends meet a road or lane, 1 one end is '
                    'a dead end, 2 both are; flags 1 ford, 2 gate, 4 steep; wid smallest OSM way id in the lane'),
           'lanes': out}
    with open(out_path, 'w') as fh:
        json.dump(doc, fh, separators=(',', ':'), ensure_ascii=False)
    km = sum(c[2] for c in out) / 1000
    by = {k: sum(1 for c in out if c[0] == k) for k in 'BUY'}
    sv = {k: sum(1 for c in out if c[1] == k) for k in ('u', 'p', '')}
    gr = {g: sum(1 for c in out if c[5] == g) for g in range(4)}
    dd = {d: sum(1 for c in out if c[6] == d) for d in range(3)}
    fl = {name: sum(1 for c in out if c[7] & bit) for name, bit in (('ford', 1), ('gate', 2), ('steep', 4))}
    print(f'{len(out)} lanes, {km:.0f} km, kinds {by}, surfaces {sv}, grades {gr}, dead {dd}, flags {fl}, '
          f'dropped {dropped}, {time.time() - t0:.0f}s')


if __name__ == '__main__':
    main(sys.argv[1], sys.argv[2:])
