"""Builds Ondulo's offline road map and its fuel / cafe list from OpenStreetMap extracts (.osm.pbf).

usage: python -I build_offline.py <public dir> <work dir> in1.osm.pbf [in2.osm.pbf ...]
  e.g. python -I research/tools/build_offline.py public /tmp/work wales-latest.osm.pbf england-latest.osm.pbf
  <work dir> holds the on-disk node location index while it runs (about 16 bytes per node in the extract: England
  needs about 4 GB); it is deleted at the end.

Writes
  <public>/offline/index.json      {"v":1,"built":"YYYY-MM-DD","z":10,"tiles":[[x,y,bytes],...],"source":...}
  <public>/offline/{x}_{y}.json.gz gzip of {"r":[[cls,flags,ref,name,enc5],...],"w":[[kind,enc5],...],"p":[[name,kind,lat,lon],...]}
                                   one file per zoom-10 slippy-map tile that has anything in it
  <public>/pois.json               {"v":1,"built":...,"source":...,"fuel":[[lat,lon,name,brand,h24],...],"cafe":[[lat,lon,name],...]}

Roads (r)
  cls    0 motorway, 1 trunk, 2 primary, 3 secondary, 4 tertiary, 5 unclassified, 6 residential / living_street / road;
         a *_link takes its parent's class and flag 4
  flags  1 one way along the line, 2 one way against it, 4 link, 8 roundabout
  ref    road number ('' if none), name ('' if none)
  enc5   Google polyline, precision 5. Simplified (Douglas-Peucker, 3 m) but every end and every node shared with
         another kept road (or with a green lane) is kept exactly, so identical rounded coordinates mean a real
         junction and a client can rebuild a routable graph from them.
  Left out: service roads, tracks, paths, footways, cycleways, bridleways, steps, construction / proposed, area
  highways, and roads closed to motor traffic (access / motor_vehicle / motorcar / vehicle = no or private).
  A road that crosses tile edges is cut where it crosses (the cut point is in both pieces) and each piece goes in
  every tile its bounding box touches; a client should de-duplicate on the enc5 string.
Water (w)
  kind   0 coastline (line), 1 river or canal (line), 2 lake or reservoir outline (closed ring, first point repeated;
         outer rings only, at least 20,000 m2), simplified 10 m
Places (p)
  place=city / town / village / hamlet with a name, kind 0..3, in the tile holding the point
"""
import gzip, json, math, os, sys, time
import osmium
from osmium.filter import KeyFilter, TagFilter
from osmium.index import IdSet

Z = 10
N = 1 << Z
ROAD_CLS = {'motorway': 0, 'trunk': 1, 'primary': 2, 'secondary': 3, 'tertiary': 4, 'unclassified': 5,
            'residential': 6, 'living_street': 6, 'road': 6}
LINKS = {'motorway_link': 0, 'trunk_link': 1, 'primary_link': 2, 'secondary_link': 3, 'tertiary_link': 4}
PLACES = {'city': 0, 'town': 1, 'village': 2, 'hamlet': 3}
ROAD_TOL, WATER_TOL, LAKE_MIN = 3.0, 10.0, 20000.0


def road_of(tags):
    """(cls, flags) for a road the offline map keeps, else None."""
    hw = tags.get('highway')
    if hw in ROAD_CLS:
        cls, fl = ROAD_CLS[hw], 0
    elif hw in LINKS:
        cls, fl = LINKS[hw], 4
    else:
        return None
    if tags.get('area') == 'yes':
        return None
    for k in ('motor_vehicle', 'motorcar', 'vehicle', 'access'):
        v = tags.get(k)
        if v is None:
            continue
        if v in ('no', 'private'):
            return None
        break                    # the most specific key that is set decides
    ow, junc = tags.get('oneway', ''), tags.get('junction', '')
    if junc in ('roundabout', 'circular'):
        fl |= 8
    if ow in ('yes', 'true', '1'):
        fl |= 1
    elif ow in ('-1', 'reverse'):
        fl |= 2
    elif ow != 'no' and (junc in ('roundabout', 'circular') or hw in ('motorway', 'motorway_link')):
        fl |= 1
    return cls, fl


def tile_of(lat, lon):
    x = int((lon + 180.0) / 360.0 * N)
    la = math.radians(max(-85.0, min(85.0, lat)))
    y = int((1.0 - math.log(math.tan(la) + 1.0 / math.cos(la)) / math.pi) / 2.0 * N)
    return min(N - 1, max(0, x)), min(N - 1, max(0, y))


def simplify(pts, keep, tol):
    """Douglas-Peucker in local metres; indexes flagged in keep always stay. Returns the kept points."""
    n = len(pts)
    if n < 3:
        return pts
    c = math.cos(math.radians(pts[0][0]))
    xy = [(p[1] * 111320.0 * c, p[0] * 110540.0) for p in pts]
    keep = bytearray(keep)
    keep[0] = keep[n - 1] = 1
    anchors = [i for i in range(n) if keep[i]]
    tol2 = tol * tol
    for a, b in zip(anchors, anchors[1:]):
        if b - a < 2:
            continue
        stack = [(a, b)]
        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 = ((px - ax) * dx + (py - ay) * dy) / L2
                u = 0.0 if u < 0.0 else (1.0 if u > 1.0 else u)
                ex, ey = px - (ax + u * dx), py - (ay + u * dy)
                d = ex * ex + ey * ey
                if d > best:
                    best, bi = d, k
            if best > tol2:
                keep[bi] = 1
                if bi - i > 1:
                    stack.append((i, bi))
                if j - bi > 1:
                    stack.append((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 dedupe_rounded(pts):
    """Drops consecutive points that are the same at precision 5 (they would encode as a zero step)."""
    out, last = [], None
    for p in pts:
        k = (round(p[0] * 1e5), round(p[1] * 1e5))
        if k != last:
            out.append(p)
            last = k
    return out


def pieces(pts):
    """Cuts a line where it moves into another tile; the cut point belongs to both pieces."""
    tiles = [tile_of(p[0], p[1]) for p in pts]
    out, start = [], 0
    for i in range(1, len(pts)):
        if tiles[i] != tiles[i - 1] and i < len(pts) - 1:
            out.append(pts[start:i + 1])
            start = i
    out.append(pts[start:])
    return [p for p in out if len(p) >= 2]


def bbox_tiles(pts):
    x0, y0 = tile_of(max(p[0] for p in pts), min(p[1] for p in pts))
    x1, y1 = tile_of(min(p[0] for p in pts), max(p[1] for p in pts))
    for x in range(x0, x1 + 1):
        for y in range(y0, y1 + 1):
            yield x, y


def ring_area(pts):
    c = math.cos(math.radians(pts[0][0]))
    xy = [(p[1] * 111320.0 * c, p[0] * 110540.0) for p in pts]
    s = 0.0
    for i in range(len(xy) - 1):
        s += xy[i][0] * xy[i + 1][1] - xy[i + 1][0] * xy[i][1]
    return abs(s) / 2.0


def lane_like(tags):
    return tags.get('designation') in ('byway_open_to_all_traffic', 'unclassified_county_road', 'unclassified_highway') \
        or tags.get('highway') == 'byway'


def closed_to_public(tags):
    return tags.get('access') in ('private', 'no')


def main(public, work, inputs):
    t0 = time.time()
    os.makedirs(work, exist_ok=True)
    stats = {'roads': [0] * 7, 'road_pts': [0] * 7, 'road_pts_raw': [0] * 7, 'water': [0, 0, 0], 'water_pts': [0, 0, 0],
             'places': [0] * 4}

    # pass 1: which nodes are shared by two or more kept roads (junctions). Green lanes count too, so the point where
    # a lane leaves a road stays on the road's line.
    seen, once, multi = IdSet(), IdSet(), IdSet()
    for path in inputs:
        for w in osmium.FileProcessor(path, osmium.osm.WAY).with_filter(KeyFilter('highway')):
            if w.id in seen:
                continue
            seen.set(w.id)
            if road_of(w.tags) is None and not lane_like(w.tags):
                continue
            for n in w.nodes:
                r = n.ref
                if r in once:
                    multi.set(r)
                else:
                    once.set(r)
        print(f'junctions: {path} done, {time.time() - t0:.0f}s', flush=True)
    del once

    tiles = {}                    # (x, y) -> {'r': [json str], 'w': [...], 'p': [...]}

    def put(x, y, kind, rec):
        t = tiles.get((x, y))
        if t is None:
            t = tiles[(x, y)] = {'r': [], 'w': [], 'p': []}
        t[kind].append(rec)

    done_w, done_a, done_n = IdSet(), IdSet(), IdSet()
    fuel, cafe = [], []
    for path in inputs:
        idx = os.path.join(work, os.path.basename(path) + '.idx')
        if os.path.exists(idx):
            os.remove(idx)
        fp = (osmium.FileProcessor(path)
              .with_locations('sparse_file_array,' + idx)
              .with_areas(TagFilter(('natural', 'water'), ('landuse', 'reservoir')))
              .with_filter(KeyFilter('highway', 'natural', 'waterway', 'landuse', 'place', 'amenity')))
        for o in fp:
            if o.is_node():
                if o.id in done_n:
                    continue
                tg = o.tags
                pl, am = tg.get('place'), tg.get('amenity')
                if pl in PLACES and tg.get('name'):
                    done_n.set(o.id)
                    lat, lon = o.location.lat, o.location.lon
                    x, y = tile_of(lat, lon)
                    put(x, y, 'p', json.dumps([tg.get('name'), PLACES[pl], round(lat, 5), round(lon, 5)],
                                              separators=(',', ':'), ensure_ascii=False))
                    stats['places'][PLACES[pl]] += 1
                elif am in ('fuel', 'cafe'):
                    done_n.set(o.id)
                    poi(am, {t.k: t.v for t in tg}, o.location.lat, o.location.lon, fuel, cafe)
            elif o.is_way():
                if o.id in done_w:
                    continue
                tg = o.tags
                rd = road_of(tg)
                if rd is not None:
                    done_w.set(o.id)
                    road(o, rd, tg, multi, put, stats)
                    continue
                nat, ww = tg.get('natural'), tg.get('waterway')
                if nat == 'coastline' or ww in ('river', 'canal'):
                    done_w.set(o.id)
                    kind = 0 if nat == 'coastline' else 1
                    pts = [(n.location.lat, n.location.lon) for n in o.nodes if n.location.valid()]
                    if len(pts) < 2:
                        continue
                    pts = dedupe_rounded(simplify(pts, [0] * len(pts), WATER_TOL))
                    for piece in pieces(pts):
                        if len(piece) < 2:
                            continue
                        rec = json.dumps([kind, encode(piece)], separators=(',', ':'))
                        for x, y in bbox_tiles(piece):
                            put(x, y, 'w', rec)
                        stats['water'][kind] += 1
                        stats['water_pts'][kind] += len(piece)
                elif tg.get('amenity') in ('fuel', 'cafe') and o.is_closed() and len(o.nodes) > 2:
                    done_w.set(o.id)
                    nl = list(o.nodes)[:-1]
                    pts = [(n.location.lat, n.location.lon) for n in nl if n.location.valid()]
                    if pts:
                        poi(tg.get("amenity"), {t.k: t.v for t in tg}, sum(p[0] for p in pts) / len(pts), sum(p[1] for p in pts) / len(pts),
                            fuel, cafe)
            elif o.is_area():
                tg = o.tags
                if not (tg.get('natural') == 'water' or tg.get('landuse') == 'reservoir'):
                    continue
                key = o.id               # area ids: way id * 2, relation id * 2 + 1
                if key in done_a:
                    continue
                done_a.set(key)
                for ring in o.outer_rings():
                    pts = [(n.location.lat, n.location.lon) for n in ring if n.location.valid()]
                    if len(pts) < 4 or ring_area(pts) < LAKE_MIN:
                        continue
                    pts = dedupe_rounded(simplify(pts, [0] * len(pts), WATER_TOL))
                    if len(pts) < 4:
                        continue
                    if (round(pts[0][0] * 1e5), round(pts[0][1] * 1e5)) != (round(pts[-1][0] * 1e5), round(pts[-1][1] * 1e5)):
                        pts.append(pts[0])
                    rec = json.dumps([2, encode(pts)], separators=(',', ':'))
                    for x, y in bbox_tiles(pts):
                        put(x, y, 'w', rec)
                    stats['water'][2] += 1
                    stats['water_pts'][2] += len(pts)
        os.remove(idx)
        print(f'map: {path} done, {len(tiles)} tiles so far, {time.time() - t0:.0f}s', flush=True)

    out_dir = os.path.join(public, 'offline')
    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))
    index, total, biggest = [], 0, (0, None)
    for (x, y), t in sorted(tiles.items()):
        if not (t['r'] or t['w'] or t['p']):
            continue
        # one piece can land in a tile twice (a line that leaves and comes back); keep the first
        body = '{"r":[' + ','.join(dict.fromkeys(t['r'])) + '],"w":[' + ','.join(dict.fromkeys(t['w'])) + \
               '],"p":[' + ','.join(dict.fromkeys(t['p'])) + ']}'
        data = gzip.compress(body.encode('utf-8'), compresslevel=9, mtime=0)
        with open(os.path.join(out_dir, f'{x}_{y}.json.gz'), 'wb') as fh:
            fh.write(data)
        index.append([x, y, len(data)])
        total += len(data)
        if len(data) > biggest[0]:
            biggest = (len(data), (x, y))
    built = time.strftime('%Y-%m-%d')
    with open(os.path.join(out_dir, 'index.json'), 'w') as fh:
        json.dump({'v': 1, 'built': built, 'z': Z, 'tiles': index, 'source': 'OpenStreetMap contributors (ODbL)'}, fh,
                  separators=(',', ':'))
    pois = {'v': 1, 'built': built, 'source': 'OpenStreetMap contributors (ODbL)', 'fuel': fuel, 'cafe': cafe}
    with open(os.path.join(public, 'pois.json'), 'w') as fh:
        json.dump(pois, fh, separators=(',', ':'), ensure_ascii=False)
    psize = os.path.getsize(os.path.join(public, 'pois.json'))
    print(f'{len(index)} tiles, {total / 1e6:.1f} MB gzipped, biggest {biggest[0] / 1e3:.0f} KB at {biggest[1]}')
    print('roads per class', stats['roads'], 'points kept', stats['road_pts'], 'of', stats['road_pts_raw'])
    print('water lines/rings', stats['water'], 'points', stats['water_pts'], 'places', stats['places'])
    print(f'pois: {len(fuel)} fuel, {len(cafe)} cafes, {psize / 1e3:.0f} KB; {time.time() - t0:.0f}s')


def road(w, rd, tg, multi, put, stats):
    cls, fl = rd
    nodes = w.nodes
    pts, keep = [], []
    last = len(nodes) - 1
    for i, n in enumerate(nodes):
        if not n.location.valid():
            continue
        pts.append((n.location.lat, n.location.lon))
        keep.append(1 if (i == 0 or i == last or n.ref in multi) else 0)
    if len(pts) < 2:
        return
    stats['road_pts_raw'][cls] += len(pts)
    pts = dedupe_rounded(simplify(pts, keep, ROAD_TOL))
    if len(pts) < 2:
        return
    ref = tg.get('ref') or ''
    name = tg.get('name') or ''
    stats['roads'][cls] += 1
    stats['road_pts'][cls] += len(pts)
    for piece in pieces(pts):
        rec = json.dumps([cls, fl, ref, name, encode(piece)], separators=(',', ':'), ensure_ascii=False)
        for x, y in bbox_tiles(piece):
            put(x, y, 'r', rec)


def poi(kind, tg, lat, lon, fuel, cafe):
    if closed_to_public(tg) or tg.get('disused') == 'yes' or tg.get('abandoned') == 'yes':
        return
    if kind == 'fuel':
        fuel.append([round(lat, 5), round(lon, 5), tg.get('name') or '', tg.get('brand') or '',
                     1 if (tg.get('opening_hours') or '').strip() == '24/7' else 0])
    elif tg.get('name'):
        cafe.append([round(lat, 5), round(lon, 5), tg.get('name')])


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