"""Download bounded OSM extracts and project features to the game's coordinates.
The resulting extract is distributed under ODbL with attribution in public/circuits.
Run manually, not during game builds. Cached XML stays outside the repository.
"""
import concurrent.futures, json, math, pathlib, urllib.request, xml.etree.ElementTree as ET
from shapely.geometry import LineString, Point, box
from shapely.ops import polygonize, unary_union

root=pathlib.Path(__file__).resolve().parent.parent
circuits=json.loads((root/'src/circuit-data.json').read_text())
cache=pathlib.Path('/tmp/sprint-osm');cache.mkdir(exist_ok=True)

def download(c):
    coords=c['coordinates'];xs=[p[0] for p in coords];ys=[p[1] for p in coords]
    bbox=(min(xs)-.002,min(ys)-.0015,max(xs)+.002,max(ys)+.0015)
    target=cache/(c['id']+'.osm')
    if not target.exists():
        url='https://api.openstreetmap.org/api/0.6/map?bbox='+','.join(map(str,bbox))
        req=urllib.request.Request(url,headers={'User-Agent':'TinyTorque scenery importer'})
        with urllib.request.urlopen(req,timeout=50) as r:target.write_bytes(r.read())
    tree=ET.parse(target).getroot();nodes={n.attrib['id']:(float(n.attrib['lon']),float(n.attrib['lat'])) for n in tree.findall('node')}
    ways={w.attrib['id']:w for w in tree.findall('way')}
    latitude=sum(ys)/len(ys);factor=111320*math.cos(math.radians(latitude))*4;cx=(min(xs)+max(xs))/2;cy=(min(ys)+max(ys))/2
    def project(refs):return [[round((nodes[n][0]-cx)*factor,1),round(-(nodes[n][1]-cy)*111320*4,1)] for n in refs if n in nodes]
    def tags(w):return {t.attrib['k']:t.attrib['v'] for t in w.findall('tag')}
    def category(t):
        if t.get('natural') in ('water','bay') or t.get('waterway')=='riverbank':return 'water'
        if t.get('natural') in ('wood','scrub') or t.get('landuse')=='forest':return 'forest'
        if t.get('natural') in ('sand','beach') or t.get('landuse')=='quarry':return 'sand'
        if t.get('leisure') in ('park','garden','golf_course') or t.get('landuse') in ('grass','meadow','recreation_ground'):return 'park'
        if t.get('landuse') in ('residential','industrial','commercial','retail'):return 'urban'
        if t.get('landuse') in ('farmland','orchard','vineyard'):return 'field'
        if t.get('amenity')=='parking':return 'parking'
        if t.get('leisure') in ('pitch','sports_centre','stadium'):return 'sport'
    out={'buildings':[],'areas':[],'roads':[],'waterways':[],'coastlines':[]}
    for w in ways.values():
        t=tags(w);refs=[n.attrib['ref'] for n in w.findall('nd')];points=project(refs)
        if len(points)<2:continue
        closed=refs[0]==refs[-1]
        if t.get('building') and t['building']!='no' and closed:
            out['buildings'].append({'points':points,'roof':t.get('roof:colour',''),'kind':t['building']})
        elif closed and category(t):out['areas'].append({'kind':category(t),'points':points})
        if t.get('highway') in ('residential','service','tertiary','secondary','unclassified','primary','pedestrian'):
            out['roads'].append({'kind':t['highway'],'points':points})
        if t.get('waterway') in ('river','stream','canal'):out['waterways'].append({'kind':t['waterway'],'points':points})
        if t.get('natural')=='coastline':out['coastlines'].append({'kind':'coastline','points':points})
    # Multipolygon outer rings retain major water and forest footprints.
    for rel in tree.findall('relation'):
        t=tags(rel);kind=category(t)
        if not kind or t.get('type')!='multipolygon':continue
        pending=[]
        for m in rel.findall('member'):
            if m.attrib.get('type')=='way' and m.attrib.get('role','') in ('outer','') and m.attrib['ref'] in ways:
                pending.append([n.attrib['ref'] for n in ways[m.attrib['ref']].findall('nd')])
        while pending:
            ring=pending.pop(0);changed=True
            while changed and ring[0]!=ring[-1]:
                changed=False
                for i,r in enumerate(pending):
                    if ring[-1]==r[0]:ring+=r[1:]
                    elif ring[-1]==r[-1]:ring+=list(reversed(r[:-1]))
                    elif ring[0]==r[-1]:ring=r[:-1]+ring
                    elif ring[0]==r[0]:ring=list(reversed(r[1:]))+ring
                    else:continue
                    pending.pop(i);changed=True;break
            if len(ring)>3 and ring[0]==ring[-1]:out['areas'].append({'kind':kind,'points':project(ring)})
    if out['coastlines']:
        frame=box((bbox[0]-cx)*factor,-(bbox[3]-cy)*111320*4,(bbox[2]-cx)*factor,-(bbox[1]-cy)*111320*4)
        lines=[LineString(feature['points']).intersection(frame) for feature in out['coastlines']]
        seeds=[]
        for feature in out['coastlines']:
            for a,b in zip(feature['points'],feature['points'][1:]):
                dx,dy=b[0]-a[0],b[1]-a[1];length=math.hypot(dx,dy)
                if length>1:
                    seed=Point((a[0]+b[0])/2-dy/length*3,(a[1]+b[1])/2+dx/length*3)
                    if frame.contains(seed):seeds.append(seed)
        # Split the bounded extract along the real coastline, then identify its sea side.
        for polygon in polygonize(unary_union([frame.boundary,*lines])):
            if any(polygon.contains(seed) for seed in seeds):out['areas'].append({'kind':'sea','points':[[round(x,1),round(y,1)] for x,y in polygon.exterior.coords]})
    print(c['id'],{k:len(v) for k,v in out.items()},flush=True)
    return c['id'],out

with concurrent.futures.ThreadPoolExecutor(max_workers=3) as pool:
    result=dict(pool.map(download,circuits))
(root/'src/scenery-data.json').write_text(json.dumps(result,separators=(',',':'))+'\n')
(root/'public/circuits/scenery-data.json').write_text(json.dumps(result,separators=(',',':'))+'\n')
