"""Fetch the fixed-date OpenStreetMap network snapshots and census subdivisions for the walking-network round.

Writes one gzip per date holding only ways: id, node ids, coordinates and the protocol's kept tags. Resumable: a snapshot
whose file exists and parses is left alone. Network access happens here and nowhere else in the round.
"""
import argparse
import gzip
import hashlib
import json
import os
from pathlib import Path
import subprocess
import tempfile
import time

STUDY = Path(__file__).resolve().parents[1]


def query_text(protocol, date):
    overpass = protocol["overpass"]
    s, w, n, e = overpass["bbox_s_w_n_e"]
    return overpass["query_template"].format(date=date, bbox=f"{s},{w},{n},{e}")


def compact(document, kept_tags):
    """Reduce an Overpass response to sorted compact ways, refusing a response that reports a problem."""
    remark = document.get("remark")
    if remark:
        raise ValueError("Overpass reported a problem: " + str(remark)[:200])
    ways = []
    for element in document["elements"]:
        if element["type"] != "way":
            continue
        tags = {key: element.get("tags", {})[key] for key in kept_tags if key in element.get("tags", {})}
        coords = [[round(point["lon"], 7), round(point["lat"], 7)] for point in element["geometry"]]
        if len(coords) != len(element["nodes"]):
            raise ValueError("Way geometry and node list disagree")
        ways.append({"id": element["id"], "nodes": element["nodes"], "coords": coords, "tags": tags})
    ways.sort(key=lambda way: way["id"])
    if not ways:
        raise ValueError("Empty network response")
    return ways


def write_snapshot(path, ways):
    path.parent.mkdir(parents=True, exist_ok=True)
    fd, temporary = tempfile.mkstemp(dir=path.parent, suffix=".tmp")
    os.close(fd)
    with open(temporary, "wb") as raw, gzip.GzipFile(fileobj=raw, mode="wb", mtime=0, compresslevel=9) as out:
        for way in ways:
            out.write((json.dumps(way, separators=(",", ":"), sort_keys=True, ensure_ascii=False) + "\n").encode("utf-8"))
        out.flush()
    os.replace(temporary, path)


def read_snapshot(path):
    with gzip.open(path, "rt", encoding="utf-8") as lines:
        return [json.loads(line) for line in lines]


def fetch_date(protocol, date, output):
    target = output / ("osm-" + date[:10] + ".jsonl.gz")
    if target.exists() and read_snapshot(target):
        print("KEEP", target.name, target.stat().st_size)
        return target
    raw = output / ("raw-" + date[:10] + ".json")
    result = subprocess.run(["curl", "-fsS", "-m", "290", "-A", protocol["router"]["user_agent"], "-o", str(raw),
                             "--data-urlencode", "data=" + query_text(protocol, date), protocol["overpass"]["endpoint"]],
                            capture_output=True, text=True, check=False)
    if result.returncode:
        print("FAILED", date, result.returncode, result.stderr[:200])
        return None
    document = json.loads(raw.read_text(encoding="utf-8"))
    write_snapshot(target, compact(document, protocol["overpass"]["kept_tags"]))
    raw.unlink()
    print("WROTE", target.name, target.stat().st_size, hashlib.sha256(target.read_bytes()).hexdigest())
    return target


def fetch_router(protocol, pairs_path, cache_path):
    """Ask the public foot router for each sampled pair, at the protocol's rate, once. A failed pair stays null, counted."""
    spec = protocol["router"]
    answers = []
    for pair in json.loads(Path(pairs_path).read_text(encoding="utf-8")):
        (lon1, lat1), (lon2, lat2) = pair["from"], pair["to"]
        url = f"{spec['url']}{lon1:.7f},{lat1:.7f};{lon2:.7f},{lat2:.7f}?overview=false"
        done = subprocess.run(["curl", "-fsS", "-m", "20", "-A", spec["user_agent"], url], capture_output=True, text=True, check=False)
        distance = None
        if done.returncode == 0:
            body = json.loads(done.stdout)
            if body.get("code") == "Ok" and body.get("routes"):
                distance = body["routes"][0]["distance"]
        answers.append(distance)
        time.sleep(spec["seconds_between_requests"])
    with Path(cache_path).open("x", encoding="utf-8") as handle:
        json.dump({"url": spec["url"], "answers": answers}, handle, indent=0)
        handle.write("\n")
    print("ROUTER", len(answers), "pairs,", sum(a is None for a in answers), "failed")


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--output", type=Path, required=True)
    parser.add_argument("--dates", nargs="*")
    parser.add_argument("--router-pairs", type=Path)
    parser.add_argument("--router-cache", type=Path)
    args = parser.parse_args()
    protocol = json.loads((STUDY / "walk-protocol.json").read_text(encoding="utf-8"))
    if args.router_pairs:
        fetch_router(protocol, args.router_pairs, args.router_cache)
        raise SystemExit(0)
    dates = args.dates or [protocol["overpass"]["main_date"], *protocol["overpass"]["drift_dates"]]
    for date in dates:
        fetch_date(protocol, date, args.output)
