"""Bake sourced vector geography and recorded positions, never map photographs."""
from pathlib import Path
import hashlib
import json
import re
import sys
import urllib.request
import requests
import shapefile
from shapely.geometry import shape, box, mapping

EP=Path(__file__).resolve().parent
ROOT=EP.parents[1]
RAW=ROOT/'outputs/starship-catch/geography'
ARCHIVE='https://stardash.live/assets/flight15-BVZn0ikJ-r2.js'
LAYERS=['ne_50m_land','ne_10m_land','ne_10m_admin_0_boundary_lines_land']
GSHHG='https://www.ncei.noaa.gov/data/oceans/archive/arc0234/0304143/1.1/data/0-data/GSHHS_shp/f/'


def fetch_inputs():
    RAW.mkdir(parents=True,exist_ok=True)
    for layer in LAYERS:
        url=f'https://raw.githubusercontent.com/nvkelso/natural-earth-vector/master/geojson/{layer}.geojson'
        (RAW/(layer+'.geojson')).write_bytes(urllib.request.urlopen(url,timeout=40).read())
    for ext in ['shp','shx']:
        name=f'GSHHS_f_L1.{ext}'
        response=requests.get(GSHHG+name,timeout=45)
        response.raise_for_status()
        (RAW/name).write_bytes(response.content)
    response=requests.get(ARCHIVE,timeout=30)
    response.raise_for_status()
    payload=response.content
    module=payload.decode('utf-8').strip()
    match=re.fullmatch(r'const ([A-Za-z_$][\w$]*)=(\[\[.*\]\]);export\{\1 as F15_ROWS\};',module,re.S)
    if not match:
        raise ValueError('Archive module format changed; inspect its schema before importing.')
    # Decode only the numeric array. Never execute downloaded JavaScript.
    values=json.loads(re.sub(r'(?<=[,\[])(-?)\.',r'\g<1>0.',match[2]))
    if len(values)!=2749 or any(len(r)!=6 for r in values):
        raise ValueError('Archive row count/schema changed; review before rebaking.')
    (RAW/'flight15-recording.js').write_bytes(payload)
    (RAW/'gps-raw.json').write_text(json.dumps(values))


def coordinates(geom):
    m=mapping(geom)
    def rounded(x):
        if isinstance(x,(list,tuple)):
            return [rounded(v) for v in x]
        return round(x,5)
    return {'type':m['type'],'coordinates':rounded(m['coordinates'])}


def bake():
    world=[]
    for f in json.loads((RAW/'ne_50m_land.geojson').read_text())['features']:
        g=shape(f['geometry']).simplify(.035,preserve_topology=True)
        if not g.is_empty:world.append(coordinates(g))
    region=[]
    for f in json.loads((RAW/'ne_10m_land.geojson').read_text())['features']:
        g=shape(f['geometry']).intersection(box(-161,12,-70,43)).simplify(.0015,preserve_topology=True)
        if not g.is_empty and g.geom_type in ['Polygon','MultiPolygon']:region.append(coordinates(g))
    borders=[]
    for f in json.loads((RAW/'ne_10m_admin_0_boundary_lines_land.geojson').read_text())['features']:
        g=shape(f['geometry']).intersection(box(-161,12,-70,43)).simplify(.005,preserve_topology=True)
        if not g.is_empty and g.geom_type in ['LineString','MultiLineString']:borders.append(coordinates(g))
    gps=json.loads((RAW/'gps-raw.json').read_text())
    # Higher-resolution shoreline for the look-back and final turn maps.
    # GSHHG 2.3.7, LGPL: attribution, changes and source links in geography-credits.md.
    local_land=[]
    reader=shapefile.Reader(shp=str(RAW/'GSHHS_f_L1.shp'),shx=str(RAW/'GSHHS_f_L1.shx'))
    for item in reader.iterShapes(bbox=[-100,24,-95,29]):
        g=shape(item.__geo_interface__).intersection(box(-100,24,-95,29)).simplify(.00012,preserve_topology=True)
        if not g.is_empty and g.geom_type in ['Polygon','MultiPolygon']:local_land.append(coordinates(g))
    # Fields verified against the archiver's replay decoder: elapsed wall seconds,
    # metres, latitude, longitude, trajectory version, reported vehicle MET.
    fixes=[{'t':r[0],'altitudeM':r[1],'lat':r[2],'lon':r[3],'vehicleMet':r[5]} for r in gps if -61<=r[0]<=81257]
    data={'worldLand':world,'regionalLand':region,'localLand':local_land,'borders':borders,'fixes':fixes,
          'sources':{'land':'Natural Earth vector data, public domain; 1:50m global, 1:10m regional',
                     'positions':'SpaceX published position telemetry, recorded by StarDash; about 30 s fixes',
                     'archive':ARCHIVE,
                     'archiveLaunchEpoch':1794610056,
                     'clock':'Elapsed wall time relative to archiver launch epoch; independent of webcast overlay clock',
                     'sha256':hashlib.sha256((RAW/'flight15-recording.js').read_bytes()).hexdigest(),
                     'localShoreline':{'name':'GSHHG 2.3.7 full-resolution L1; clipped and simplified to 0.00012 degrees','license':'LGPL-3.0-or-earlier','source':GSHHG,'files':{f'GSHHS_f_L1.{ext}':hashlib.sha256((RAW/f'GSHHS_f_L1.{ext}').read_bytes()).hexdigest() for ext in ['shp','shx']}},
                     'naturalEarthFiles':{layer:{'url':f'https://raw.githubusercontent.com/nvkelso/natural-earth-vector/master/geojson/{layer}.geojson','sha256':hashlib.sha256((RAW/(layer+'.geojson')).read_bytes()).hexdigest()} for layer in LAYERS}}}
    (EP/'geography.json').write_text(json.dumps(data,separators=(',',':'))+'\n')
    print('Baked geography:',len(world),'global features;',len(region),'regional;',len(local_land),'local;',len(fixes),'recorded fixes')


if __name__=='__main__':
    if '--fetch' in sys.argv:fetch_inputs()
    bake()
