#!/usr/bin/env python3
"""Import real SRTM v3 DEM samples; no generated/fallback elevation values.

Run from repository root: python3 scripts/import-elevations.py
Optional ELEVATION_ARCHIVE directory stores exact API response bytes.
Public API limit: <=100 locations/request, <=1 request/second.
"""
import datetime
import hashlib
import json
import math
import os
from pathlib import Path
import time
import urllib.parse
import urllib.request

ROOT = Path(__file__).resolve().parents[1]
SOURCE = ROOT / 'src/circuit-data.json'
TARGET = ROOT / 'src/elevation-data.json'
ENDPOINT = 'https://api.opentopodata.org/v1/srtm30m'
archive = Path(os.environ.get('ELEVATION_ARCHIVE', str(ROOT / '.elevation-source-archive')))
archive.mkdir(parents=True, exist_ok=True)
circuits = json.loads(SOURCE.read_text())
output = {
    'schemaVersion': 1,
    'dataset': 'SRTMGL1 v003 via Open Topo Data srtm30m',
    'sourceUrl': 'https://www.opentopodata.org/datasets/srtm/',
    'endpoint': ENDPOINT,
    'retrievedAt': datetime.datetime.now(datetime.timezone.utc).isoformat(),
    'resolutionMetersApprox': 30,
    'horizontalDatum': 'WGS84',
    'verticalDatum': 'EGM96 geoid',
    'units': 'meters',
    'interpolation': 'bilinear',
    'license': 'SRTM data: public domain; acknowledge NASA/USGS and Open Topo Data',
    'licenseUrl': 'https://www.usa.gov/government-works',
    'licenseEvidenceUrl': 'https://data.nasa.gov/dataset/nasa-shuttle-radar-topography-mission-global-1-arc-second-v003-e47e1',
    'coordinateFileSha256': hashlib.sha256(SOURCE.read_bytes()).hexdigest(),
    'limitations': 'Coarse radar-derived terrain/surface heights acquired in February 2000 with void filling. Not surveyed road elevations. Buildings, vegetation, bridges, tunnels and later earthworks may differ. Integer-meter API output is not meter-level accuracy.',
    'circuits': [],
}
last_request = 0.0
for circuit in circuits:
    heights, requests = [], []
    coords = circuit['coordinates']
    for start in range(0, len(coords), 100):
        batch = coords[start:start + 100]
        locations = '|'.join(f'{lat:.6f},{lon:.6f}' for lon, lat in batch)
        url = ENDPOINT + '?' + urllib.parse.urlencode({'locations': locations, 'interpolation': 'bilinear', 'nodata_value': 'null'})
        cached = archive / f"{circuit['id']}-{start:04d}.json"
        for attempt in range(4):
            time.sleep(max(0, 1.2 - (time.monotonic() - last_request)))
            last_request = time.monotonic()
            try:
                if os.environ.get('ELEVATION_USE_ARCHIVE') == '1' and cached.exists():
                    raw = cached.read_bytes()
                else:
                    with urllib.request.urlopen(url, timeout=60) as response:
                        raw = response.read()
                result = json.loads(raw)
                if result.get('status') != 'OK':
                    raise RuntimeError(str(result))
                break
            except Exception:
                if attempt == 3:
                    raise
                time.sleep(2 ** (attempt + 1))
        rows = result['results']
        assert len(rows) == len(batch), (circuit['id'], 'wrong count')
        for row, (lon, lat) in zip(rows, batch):
            assert row['dataset'] == 'srtm30m'
            assert abs(row['location']['lat'] - lat) < 0.000001
            assert abs(row['location']['lng'] - lon) < 0.000001
            assert row['elevation'] is not None and math.isfinite(row['elevation']), (circuit['id'], 'missing DEM sample')
            heights.append(row['elevation'])
        name = f"{circuit['id']}-{start:04d}.json"
        (archive / name).write_bytes(raw)
        requests.append({'startIndex': start, 'count': len(batch), 'url': url, 'sha256': hashlib.sha256(raw).hexdigest(), 'archiveFile': name})
    warnings = ['Terrain/surface DEM only; not a surveyed circuit road profile.']
    if circuit['id'] == 'monaco':
        warnings.append('Monaco includes a tunnel and dense buildings. SRTM observes surfaces above the road; tunnel road elevation cannot be recovered from these samples. Do not call this an accurate Monaco road profile.')
    if circuit['id'] in ('bahrain', 'spielberg', 'zandvoort', 'silverstone'):
        warnings.append('Circuit construction or later layout/earthwork changes can postdate the February 2000 radar acquisition.')
    output['circuits'].append({'id': circuit['id'], 'elevationsMeters': heights, 'minMeters': min(heights), 'maxMeters': max(heights), 'warnings': warnings, 'requests': requests})
    print(circuit['id'], len(heights), min(heights), max(heights), flush=True)
# Only replace target after every circuit succeeds and is validated.
TARGET.write_text(json.dumps(output, ensure_ascii=False, indent=2) + '\n')
print('Wrote', TARGET)
