"""Mappa del primo appuntamento: strade OSM (ODbL) -> mappa.js compatto + il percorso in macchina raccontato:
Galleria Umberto I (Litro) -> corso San Maurizio -> lungo Po -> corso Massimo d'Azeglio -> corso Spezia -> via Genova
fino all'inizio nord (numeri bassi). Il civico non compare nella pagina."""
import json, math, heapq, base64, struct, os
D = os.path.dirname(os.path.abspath(__file__))
d = json.load(open(os.path.join(D, 'osm/strade.json')))
LAT0 = 45.055; KX = 111320 * math.cos(math.radians(LAT0)); KY = 110540
def P(lat, lon): return ((lon - 7.6775) * KX, (LAT0 - lat) * KY)   # metri, y verso sud
PREF = ('Corso San Maurizio','Lungo Po Luigi Cadorna','Lungo Po Armando Diaz','Corso Cairoli',"Corso Massimo D'Azeglio",'Corso Spezia','Via Genova','Galleria Umberto I')
A = (45.07458, 7.68302); B = (45.04253, 7.67254)
W0 = (45.0362, 7.6761)  # inizio est di corso Spezia
W1 = (45.0370, 7.6716)  # corso Spezia x via Genova
nodes = {}; adj = {}
walk = {'primary','secondary','tertiary','residential','unclassified','living_street','pedestrian','footway','path','primary_link','secondary_link','tertiary_link','service','steps','cycleway'}
major = {'primary','secondary','tertiary','trunk','primary_link','secondary_link','trunk_link'}
minor = {'residential','unclassified','living_street','pedestrian','tertiary_link'}
lines = {'M': [], 'm': [], 'r': []}
for w in d['elements']:
    t = w['tags']; g = w['geometry']; hw = t.get('highway')
    pts = [P(p['lat'], p['lon']) for p in g]
    if t.get('waterway') == 'river': lines['r'].append(pts); continue
    if hw in major: lines['M'].append(pts)
    elif hw in minor: lines['m'].append(pts)
    if hw in walk or hw in major:
        ids = w.get('nodes') or [None]*len(g)
        for i in range(len(g) - 1):
            a = (round(g[i]['lat'], 7), round(g[i]['lon'], 7)); b = (round(g[i+1]['lat'], 7), round(g[i+1]['lon'], 7))
            pa, pb = P(*a), P(*b); dd = math.dist(pa, pb)
            # leggera preferenza per strade "da passeggio" (pedonali, residenziali) rispetto a corsi trafficati
            nm = t.get('name','')
            # il percorso raccontato: le vie nominate costano poco, tutto il resto molto (solo raccordi brevi)
            k = 0.2 if any(nm.startswith(p) for p in PREF) else (12.0 if nm in ('Corso Bramante','Via Nizza','Sottopasso Spezia') else 1.6)
            for x, y in ((a, b), (b, a)): adj.setdefault(x, []).append((y, dd * k))
def near(q):
    pq = P(*q); return min(adj, key=lambda n: math.dist(P(*n), pq))
def route(a, b):
    dist = {a: 0}; prev = {}; h = [(0, a)]
    while h:
        c, u = heapq.heappop(h)
        if u == b: break
        if c > dist[u]: continue
        for v, wv in adj[u]:
            nc = c + wv
            if nc < dist.get(v, 1e18): dist[v] = nc; prev[v] = u; heapq.heappush(h, (nc, v))
    p = [b]
    while p[-1] != a: p.append(prev[p[-1]])
    return list(reversed(p))
pts = [near(A), near(W0), near(W1), near(B)]
nodes_path = route(pts[0], pts[1]) + route(pts[1], pts[2])[1:] + route(pts[2], pts[3])[1:]
path = [P(*n) for n in nodes_path]
L = sum(math.dist(path[i], path[i+1]) for i in range(len(path) - 1))
print('percorso: %d punti, %.0f m' % (len(path), L))
# semplificazione Douglas-Peucker
def dp(pts, eps):
    if len(pts) < 3: return pts
    a, b = pts[0], pts[-1]; dx, dy = b[0]-a[0], b[1]-a[1]; n = math.hypot(dx, dy) or 1e-9
    i, m = 0, -1
    for k in range(1, len(pts)-1):
        dd = abs(dy*(pts[k][0]-a[0]) - dx*(pts[k][1]-a[1])) / n
        if dd > m: i, m = k, dd
    if m > eps: return dp(pts[:i+1], eps)[:-1] + dp(pts[i:], eps)
    return [a, b]
def pack(polys, eps):
    out = bytearray()
    for p in polys:
        p = dp(p, eps)
        if len(p) < 2: continue
        out += struct.pack('<h', len(p))
        for x, y in p: out += struct.pack('<hh', max(-32767, min(32767, round(x*2))), max(-32767, min(32767, round(y*2))))  # mezzo metro
    return base64.b64encode(bytes(out)).decode()
xs = [x for x, y in path]; ys = [y for x, y in path]
out = {'M': pack(lines['M'], 3), 'm': pack(lines['m'], 3), 'r': pack(lines['r'], 6), 'path': pack([path], 1.5),
       'len': round(L), 'bbox': [min(xs), min(ys), max(xs), max(ys)],
       'fonte': 'OpenStreetMap contributors, ODbL'}
js = 'window.MAPPA=' + json.dumps(out, separators=(',', ':')) + ';'
open(os.path.join(D, '..', 'mappa.js'), 'w').write(js)
print('mappa.js %.0f KB' % (len(js) / 1024))
