#!/usr/bin/env python3
"""Convert Passport One's city-bounds.bin (format PCB1) to GeoJSON.

Usage: python3 city_bounds_to_geojson.py city-bounds.bin > city-bounds.geojson
       python3 city_bounds_to_geojson.py city-bounds.bin 3117735   # one GeoNames id

Each feature: id = GeoNames id, properties.area_km2, geometry = MultiPolygon (lon, lat).
Data: (c) OpenStreetMap contributors, ODbL 1.0, via Overture Maps Foundation divisions;
79 New Zealand outlines: Land Information New Zealand (LINZ), CC BY 4.0.
Standard library only.
"""
import json, struct, sys

SCALE = 1e-5

def varint(buf, pos):
    shift = result = 0
    while True:
        b = buf[pos]; pos += 1
        result |= (b & 0x7F) << shift
        if b < 0x80:
            break
        shift += 7
    return (result >> 1) ^ -(result & 1), pos

def read(path):
    data = open(path, 'rb').read()
    magic, count, _ = struct.unpack_from('<4sII', data, 0)
    if magic != b'PCB1':
        raise SystemExit('not a PCB1 file')
    base = 12 + 32 * count
    for i in range(count):
        gid, x0, y0, x1, y1, off, length, area = struct.unpack_from('<IiiiiIIf', data, 12 + 32 * i)
        pos = base + off
        (npoly,) = struct.unpack_from('<H', data, pos); pos += 2
        polys = []
        for _ in range(npoly):
            (nring,) = struct.unpack_from('<H', data, pos); pos += 2
            rings = []
            for _ in range(nring):
                nv, lon, lat = struct.unpack_from('<Iii', data, pos); pos += 12
                ring = [[round(lon * SCALE, 5), round(lat * SCALE, 5)]]
                for _ in range(nv - 1):
                    dx, pos = varint(data, pos)
                    dy, pos = varint(data, pos)
                    lon += dx; lat += dy
                    ring.append([round(lon * SCALE, 5), round(lat * SCALE, 5)])
                ring.append(ring[0])  # GeoJSON rings are closed
                rings.append(ring)
            polys.append(rings)
        yield gid, round(area, 3), polys

def main():
    path = sys.argv[1]
    only = int(sys.argv[2]) if len(sys.argv) > 2 else None
    out = sys.stdout
    out.write('{"type":"FeatureCollection","features":[\n')
    first = True
    for gid, area, polys in read(path):
        if only is not None and gid != only:
            continue
        f = {"type": "Feature", "id": gid, "properties": {"geonameid": gid, "area_km2": area},
             "geometry": {"type": "MultiPolygon", "coordinates": polys}}
        out.write(('' if first else ',\n') + json.dumps(f, separators=(',', ':')))
        first = False
    out.write('\n]}\n')

if __name__ == '__main__':
    main()
