"""Builds Ondulo's European green lanes (public/eu-lanes/) from a Geofabrik country extract (.osm.pbf).

Europe has no register of lanes open to motor vehicles like England and Wales's byways, so a lane here is an unpaved
track or road the map does not close to motorbikes:
  highway=track, or highway=unclassified / road mapped as unpaved, that is
  - not tagged no / private / agricultural / forestry / permit / delivery / customers for motorcycle, motor_vehicle,
    vehicle or access (the most specific key that is set decides),
  - not under a conditional or seasonal order (motor_vehicle:conditional and the like),
  - not paved (tracktype=grade1, surface asphalt/concrete/...),
  - at least 800 m long once ways that continue each other are joined.
In France that is the chemins ruraux the map leaves open (open to motor vehicles unless a local order closes them) and,
untagged, some private farm tracks too; Spain, Portugal and Italy have regional rules. The app says so: check signs.

Each lane is [kind, surface, len, name, enc5, grade, dead, flags, wid, cc]: as public/lanes.json v2 (see
extract_lanes.py), with kind T track, R unpaved road, and cc the country code. Lanes go in the z8 tile holding their
midpoint: public/eu-lanes/<cc>/<x>_<y>.json.gz ({"lanes": [...]}, gzip), listed in public/eu-lanes/index.json.

Node locations: only the lane ways' own nodes are kept (sorted id / lat / lon arrays, 16 bytes a node), not an index of
every node in the country; France's full index (8.5 GB) would not stay in memory on a 16 GB Mac.

usage: python -I extract_eu.py <public dir> <work dir> <cc> <country.osm.pbf>
"""
import gzip, json, math, os, resource, sys, time
from array import array
from bisect import bisect_left
import osmium
from osmium.filter import IdFilter, KeyFilter
from osmium.index import IdSet

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from extract_lanes import (UNPAVED, PAVED, CLOSED, MOTOR, surface_of, grade_of, steep, hav, simplify, encode,  # noqa: E402
                           motor_ok, conditional)

Z = 8
MIN_LEN = 800


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
        if v in CLOSED or v in ('discouraged', 'use_sidepath', 'official'):
            return False
    return True


def kind_of(t):
    hw = t.get('highway')
    if hw == 'track':
        s = t.get('surface', '')
        if t.get('tracktype') == 'grade1' or s in PAVED:
            return None                                  # a paved farm road is not a lane
        return 'T'
    if hw in ('unclassified', 'road') and surface_of(t) == 'u':
        return 'R'
    return None


def tile_of(lat, lon, z=Z):
    n = 2 ** z
    x = int((lon + 180) / 360 * n)
    r = math.radians(lat)
    y = int((1 - math.log(math.tan(r) + 1 / math.cos(r)) / math.pi) / 2 * n)
    return x, y


def gb():
    return f'{resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 2 ** 30:.1f} GB'   # peak so far (macOS: bytes)


def main(public, work, cc, path):
    t0 = time.time()
    os.makedirs(work, exist_ok=True)
    cc = cc.lower()
    dropped = {'closed': 0, 'conditional': 0, 'paved': 0}

    # pass 1 (ways): which ways are lanes, and which nodes two lane ways share (osmium's id sets keep this small)
    lane_ids, once, multi = IdSet(), IdSet(), IdSet()
    lane_nodes = array('q')     # every lane node once, for the node pass
    for w in osmium.FileProcessor(path, osmium.osm.WAY).with_filter(KeyFilter('highway')):
        tg = w.tags
        hw = tg.get('highway')
        if hw != 'track' and hw not in ('unclassified', 'road'):
            continue
        t = {x.k: x.v for x in tg}
        k = kind_of(t)
        if not k:
            if hw == 'track':
                dropped['paved'] += 1
            continue
        if not open_to_bikes(t):
            dropped['closed'] += 1
            continue
        if conditional(t):
            dropped['conditional'] += 1
            continue
        lane_ids.set(w.id)
        for n in w.nodes:
            r = n.ref
            if r in once:
                multi.set(r)
            else:
                once.set(r)
                lane_nodes.append(r)
    del once
    print(f'{cc}: pass 1 done, dropped {dropped}, {len(lane_nodes)} lane nodes, {time.time() - t0:.0f}s, peak {gb()}', flush=True)

    # pass 2a (nodes): the lane nodes' locations, and which of them are fords or gates
    ids, lats, lons = array('q'), array('i'), array('i')
    ford, gate = set(), set()
    flt = IdFilter(lane_nodes)
    del lane_nodes
    for n in osmium.FileProcessor(path, osmium.osm.NODE).with_filter(flt):
        loc = n.location
        if not loc.valid():
            continue
        ids.append(n.id); lats.append(round(loc.lat * 1e6)); lons.append(round(loc.lon * 1e6))
        tg = n.tags
        if len(tg):
            if tg.get('ford') in ('yes', 'stepping_stones'):
                ford.add(n.id)
            if tg.get('barrier') in ('gate', 'lift_gate', 'swing_gate'):
                gate.add(n.id)
    del flt
    if any(ids[i] > ids[i + 1] for i in range(len(ids) - 1)):     # extracts are sorted by id; sort if this one is not
        order = sorted(range(len(ids)), key=ids.__getitem__)
        ids, lats, lons = array('q', (ids[i] for i in order)), array('i', (lats[i] for i in order)), array('i', (lons[i] for i in order))
        del order
    nn = len(ids)
    print(f'{cc}: {nn} lane node locations, {len(ford)} fords, {len(gate)} gates, {time.time() - t0:.0f}s, peak {gb()}', flush=True)

    # pass 2b (ways): each lane way's shape and end nodes
    ways = {}               # id -> (kind, surface, name, grade, flags, first node, last node, lat/lon * 1e6)
    for o in osmium.FileProcessor(path, osmium.osm.WAY).with_filter(KeyFilter('highway')):
        if o.id not in lane_ids:
            continue
        t = {x.k: x.v for x in o.tags}
        ll = array('i')
        first = last = None
        fl = (1 if t.get('ford') in ('yes', 'stepping_stones') else 0) | (4 if steep(t.get('incline')) else 0)
        for n in o.nodes:
            r = n.ref
            i = bisect_left(ids, r)
            if i >= nn or ids[i] != r:
                continue                                 # node missing from the extract (cut at the border)
            if first is None:
                first = r
            last = r
            if r in ford:
                fl |= 1
            if r in gate:
                fl |= 2
            ll.append(lats[i]); ll.append(lons[i])
        if len(ll) < 4:
            continue
        ways[o.id] = (kind_of(t), surface_of(t), t.get('name') or t.get('ref') or '', grade_of(t), fl, first, last, ll)
    del ford, gate, lane_ids, ids, lats, lons
    print(f'{cc}: {len(ways)} lane ways, {time.time() - t0:.0f}s, peak {gb()}', flush=True)

    # join ways that continue each other (same kind, meeting where no other lane way ends)
    ends = {}
    for wid, w in ways.items():
        ends.setdefault(w[5], []).append(wid)
        ends.setdefault(w[6], []).append(wid)
    used = set()
    chains = []             # (kind, [(way id, forward)], first node, last node)
    for wid in ways:
        if wid in used:
            continue
        used.add(wid)
        kind = ways[wid][0]
        parts = [(wid, True)]
        head, tail = ways[wid][5], ways[wid][6]
        for forward in (True, False):
            while True:
                tip = tail if forward else head
                at = ends.get(tip, [])
                nxt = [x for x in at if x not in used and ways[x][0] == kind]
                if len(at) != 2 or len(nxt) != 1:
                    break
                x = nxt[0]
                used.add(x)
                xf, xl = ways[x][5], ways[x][6]
                if forward:
                    on = xf == tip                       # x runs on from the tail as mapped
                    parts.append((x, on))
                    tail = xl if on else xf
                else:
                    on = xl == tip                       # x runs into the head as mapped
                    parts.insert(0, (x, on))
                    head = xf if on else xl
        chains.append((kind, parts, head, tail))
    del ends, used

    # pass 3: which chain ends meet a road a motor vehicle can use (or another lane way part-way along)
    tips = set()
    for _, _, h, t in chains:
        tips.add(h); tips.add(t)
    on_road = set()
    for w in osmium.FileProcessor(path, osmium.osm.WAY).with_filter(KeyFilter('highway')):
        if w.tags.get('highway') not in MOTOR or w.id in ways:
            continue
        if not motor_ok({x.k: x.v for x in w.tags}):
            continue
        for n in w.nodes:
            if n.ref in tips:
                on_road.add(n.ref)
    print(f'{cc}: {len(chains)} chains, {len(on_road)} of {len(tips)} ends on a motor road, {time.time() - t0:.0f}s, peak {gb()}', flush=True)

    tiles = {}
    stats = {'lanes': 0, 'km': 0.0, 'T': 0, 'R': 0, 'grade': [0, 0, 0, 0], 'dead': [0, 0, 0], 'ford': 0, 'gate': 0, 'short': 0}
    for kind, parts, head, tail in chains:
        pts = []
        for x, on in parts:
            ll = ways[x][7]
            seg = [(ll[2 * i] / 1e6, ll[2 * i + 1] / 1e6) for i in range(len(ll) // 2)]
            if not on:
                seg.reverse()
            pts.extend(seg[1:] if pts else seg)
        length = sum(hav(pts[i - 1], pts[i]) for i in range(1, len(pts)))
        if length < MIN_LEN:
            stats['short'] += 1
            continue
        mw = [ways[x] for x, _ in parts]
        surf = [w[1] for w in mw]
        s = 'u' if 'u' in surf else ('p' if all(x == 'p' for x in surf) else '')
        name = next((w[2] for w in mw if w[2]), '')
        grade = max(w[3] for w in mw)
        flags = 0
        for w in mw:
            flags |= w[4]
        members = [x for x, _ in parts]

        def connected(nd):
            return nd in on_road or nd in multi
        if head == tail:
            dead = 0 if connected(head) else 2
        else:
            dead = (0 if connected(head) else 1) + (0 if connected(tail) else 1)
        # the tile holding the lane's halfway point
        half, acc, mid = length / 2, 0.0, pts[0]
        for i in range(1, len(pts)):
            d = hav(pts[i - 1], pts[i])
            if acc + d >= half:
                mid = pts[i]
                break
            acc += d
        rec = [kind, s, round(length), name, encode(simplify(pts)), grade, dead, flags, min(members), cc]
        tiles.setdefault(tile_of(*mid), []).append(rec)
        stats['lanes'] += 1; stats['km'] += length / 1000; stats[kind] += 1
        stats['grade'][grade] += 1; stats['dead'][dead] += 1
        stats['ford'] += 1 if flags & 1 else 0; stats['gate'] += 1 if flags & 2 else 0

    out_dir = os.path.join(public, 'eu-lanes', cc)
    os.makedirs(out_dir, exist_ok=True)
    for f in os.listdir(out_dir):
        if f.endswith('.json.gz'):
            os.remove(os.path.join(out_dir, f))
    listing = []
    for (x, y), recs in sorted(tiles.items()):
        recs.sort(key=lambda r: -r[2])
        data = gzip.compress(json.dumps({'lanes': recs}, separators=(',', ':'), ensure_ascii=False).encode('utf-8'), 9)
        with open(os.path.join(out_dir, f'{x}_{y}.json.gz'), 'wb') as fh:
            fh.write(data)
        listing.append([x, y, len(recs), len(data)])

    # the index lists every country built so far
    ipath = os.path.join(public, 'eu-lanes', 'index.json')
    index = {'v': 1, 'z': Z, 'source': 'OpenStreetMap contributors (ODbL), via Geofabrik extracts', 'sets': {}}
    if os.path.exists(ipath):
        with open(ipath) as fh:
            index = json.load(fh)
    index['sets'][cc] = {'built': time.strftime('%Y-%m-%d'), 'lanes': stats['lanes'], 'km': round(stats['km']), 'tiles': listing}
    index['note'] = ('each lane is [kind, surface, len m, name, polyline5, grade, dead, flags, wid, cc]; kind T track, R unpaved '
                     'road; otherwise as lanes.json v2. Tiles are z' + str(Z) + ', by the lane\'s halfway point.')
    with open(ipath, 'w') as fh:
        json.dump(index, fh, separators=(',', ':'))
    total = sum(r[3] for r in listing)
    print(f'{cc}: {stats["lanes"]} lanes ({stats["T"]} tracks, {stats["R"]} roads), {stats["km"]:.0f} km, grades {stats["grade"]}, '
          f'dead {stats["dead"]}, fords {stats["ford"]}, gates {stats["gate"]}, under {MIN_LEN} m {stats["short"]}; '
          f'{len(listing)} tiles, {total / 1e6:.1f} MB gzipped, biggest {max((r[3] for r in listing), default=0) / 1e6:.2f} MB; '
          f'{time.time() - t0:.0f}s, peak {gb()}', flush=True)


if __name__ == '__main__':
    main(*sys.argv[1:5])
