"""Download the legacy address hierarchy published by tinhthanhpho.com (CC BY 4.0)."""
import json
import subprocess
import sys
from pathlib import Path


def fetch(level):
    url = f"https://tinhthanhpho.com/data/{level}-legacy.json"
    result = json.loads(subprocess.check_output([
        "curl", "--fail", "--silent", "--show-error", "--retry", "3",
        "--max-time", "30", url,
    ]))
    rows = result["data"]
    if not isinstance(rows, list) or not rows:
        raise ValueError(f"Empty or invalid address data: {url}")
    return rows


if __name__ == "__main__":
    snapshot = {level: fetch(level) for level in ("provinces", "districts", "wards")}
    Path(sys.argv[1]).write_text(json.dumps(snapshot, ensure_ascii=False), encoding="utf-8")
