#!/usr/bin/env python3
"""Reproduce the Inirida source extract from the pinned public Basemap wheel.

This selects original WDBII coordinates. It does not fill the source gap,
smooth the line, or adjust the geographic trace to a published river length.
"""
import argparse
import hashlib
import json
import struct
import zipfile
from pathlib import Path

SEGMENTS = [12628, 12626, 12547, 12548, 12550, 12551, 12549, 12552, 12554, 12488, 12489]
DATA_SHA = '228980d2f39bf42675eacf450d042a84e1231c5bbfae9d98ff1e3fe6b1e33e90'
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('wheel', type=Path)
parser.add_argument('--output', type=Path, required=True)
args = parser.parse_args()
with zipfile.ZipFile(args.wheel) as archive:
    data = archive.read('mpl_toolkits/basemap_data/rivers_f.dat')
    metadata = archive.read('mpl_toolkits/basemap_data/riversmeta_f.dat').decode()
assert hashlib.sha256(data).hexdigest() == DATA_SHA, 'Different river source data'
rows = {int(row[7]): row for row in (line.split() for line in metadata.splitlines())}
features = []
for segment in SEGMENTS:
    row = rows[segment]
    count, start, size = int(row[2]), int(row[5]), int(row[6])
    values = struct.unpack('<' + str(count * 2) + 'f', data[start:start + size])
    points = [[values[i] - 360 if values[i] > 180 else values[i], values[i + 1]]
              for i in range(0, len(values), 2)]
    features.append({'type': 'Feature', 'properties': {
        'riverId': 'river-inirida', 'sourceDataset': 'gshhg-wdbii-basemap',
        'sourceSegmentId': segment,
        'identification': 'Historic Inirida course independently identified by FAO source and mouth coordinates; WDBII has no name field.'
    }, 'geometry': {'type': 'LineString', 'coordinates': points}})
args.output.write_text(json.dumps({'type': 'FeatureCollection', 'features': features}, indent=2) + '\n')
