#!/usr/bin/env python3
"""Build bundled GeoNames (CC BY 4.0) and timezone-boundary-builder (ODbL) data.

Requires Shapely. Usage: build-location-data.py cities1000.zip countryInfo.txt timezones.zip
"""
import gzip
import hashlib
import json
from pathlib import Path
import sqlite3
import struct
import sys
import unicodedata
import zipfile
from shapely.geometry import shape

OUTPUT = Path(__file__).resolve().parents[1] / "app/src/main/assets/location"

def folded(value):
    return "".join(c for c in unicodedata.normalize("NFKD", value.casefold())
                   if not unicodedata.combining(c))

def build_cities(cities_zip, countries_file):
    countries = {}
    for line in countries_file.read_text().splitlines():
        if line and not line.startswith("#"):
            fields = line.split("\t")
            countries[fields[0]] = fields[4]
    database = OUTPUT / "cities-v1.db"
    database.unlink(missing_ok=True)
    db = sqlite3.connect(database)
    db.execute("CREATE TABLE cities(id INTEGER PRIMARY KEY, name TEXT NOT NULL, "
               "name_search TEXT NOT NULL, latitude REAL NOT NULL, longitude REAL NOT NULL, "
               "zone TEXT NOT NULL, country TEXT NOT NULL, population INTEGER NOT NULL)")
    db.execute("CREATE VIRTUAL TABLE city_search USING fts4(search_text, tokenize=unicode61)")
    with zipfile.ZipFile(cities_zip) as archive:
        lines = archive.read("cities1000.txt").decode().splitlines()
    for line in lines:
        f = line.split("\t")
        if len(f) < 19 or not f[17]:
            continue
        db.execute("INSERT INTO cities VALUES(?,?,?,?,?,?,?,?)", (
            int(f[0]), f[1], folded(f[1]), float(f[4]), float(f[5]), f[17], f[8], int(f[14] or 0)))
        db.execute("INSERT INTO city_search(rowid,search_text) VALUES(?,?)", (
            int(f[0]), folded(" ".join((f[1], f[2], f[3].replace(",", " "), f[8], countries.get(f[8], ""))))))
    db.execute("CREATE INDEX city_coordinates ON cities(latitude,longitude)")
    db.commit()
    db.execute("VACUUM")
    assert db.execute("PRAGMA integrity_check").fetchone()[0] == "ok"
    count = db.execute("SELECT count(*) FROM cities").fetchone()[0]
    for query, expected in (("jakarta", "ID"), ("london", "GB"), ("makkah", "SA"),
                            ("new york", "US"), ("sao paulo", "BR")):
        match = " ".join(token + '*' for token in query.split())
        row = db.execute("SELECT c.country FROM cities c JOIN city_search s ON c.id=s.rowid "
                         "WHERE city_search MATCH ? ORDER BY c.population DESC LIMIT 1", (match,)).fetchone()
        assert row and row[0] == expected, (query, row)
    db.close()
    with database.open("rb") as source, gzip.open(OUTPUT / "cities-v1.db.gz", "wb") as target:
        target.write(source.read())
    database.unlink()
    return count

def build_zones(zones_zip):
    with zipfile.ZipFile(zones_zip) as archive:
        name = next(name for name in archive.namelist() if name.endswith(".json"))
        data = json.loads(archive.read(name))
    polygons = []
    for feature in data["features"]:
        geometry = shape(feature["geometry"]).simplify(0.001, preserve_topology=True)
        parts = list(geometry.geoms) if geometry.geom_type == "MultiPolygon" else [geometry]
        for polygon in parts:
            rings = [list(polygon.exterior.coords)] + [list(r.coords) for r in polygon.interiors]
            polygons.append((feature["properties"]["tzid"], polygon.bounds, rings))
    with gzip.open(OUTPUT / "timezones-v1.bin.gz", "wb") as target:
        target.write(b"ADTZ\x00\x00\x00\x01")
        target.write(struct.pack(">i", len(polygons)))
        for zone, bounds, rings in polygons:
            name = zone.encode("ascii")
            target.write(struct.pack(">H", len(name)) + name)
            target.write(struct.pack(">4fi", *bounds, len(rings)))
            for ring in rings:
                target.write(struct.pack(">i", len(ring)))
                for longitude, latitude in ring:
                    target.write(struct.pack(">2f", longitude, latitude))
    return len(polygons)

if __name__ == "__main__":
    OUTPUT.mkdir(parents=True, exist_ok=True)
    cities, countries, zones = map(Path, sys.argv[1:])
    counts = {"cities": build_cities(cities, countries), "timezone_polygons": build_zones(zones)}
    manifest = {
        "snapshot_date": "2026-10-13", "timezone_release": "2026e",
        "simplification_tolerance_degrees": 0.001,
        "sources": ["https://download.geonames.org/export/dump/cities1000.zip",
                    "https://download.geonames.org/export/dump/countryInfo.txt",
                    "https://github.com/evansiroky/timezone-boundary-builder/releases/tag/2026e"],
        "counts": counts,
        "sha256": {p.name: hashlib.sha256(p.read_bytes()).hexdigest() for p in sorted(OUTPUT.glob("*.gz"))},
        "input_sha256": {p.name: hashlib.sha256(p.read_bytes()).hexdigest() for p in (cities, countries, zones)},
    }
    (OUTPUT / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n")
    print(json.dumps(counts))
