"""Derive the census subdivision of every dissemination area and record the round's source hashes, offline from fetched files."""
import argparse
import json
from pathlib import Path
import sys

from pyproj import Transformer
import shapely
from shapely.ops import transform

STUDY = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(STUDY / "src"))

from geography import esri_polygon  # noqa: E402
from region import digest, load_region  # noqa: E402


def assign(root, csd_json):
    document = json.loads(Path(csd_json).read_text(encoding="utf-8"))
    if document.get("exceededTransferLimit"):
        raise ValueError("Incomplete census subdivision response")
    to_model = Transformer.from_crs(3347, 26910, always_xy=True)
    polygons, attributes = [], []
    for feature in document["features"]:
        polygons.append(transform(to_model.transform, esri_polygon(feature["geometry"]["rings"])))
        attributes.append(feature["attributes"])
    tree = shapely.STRtree(polygons)
    _, _, areas, _ = load_region(root)
    out = {}
    for area in areas:
        if area["exclusion"] is not None:
            continue
        hits = tree.query(area["representative"], predicate="intersects")
        if len(hits) != 1:
            # A representative point on a shared line takes the lowest id, so the assignment stays deterministic.
            hits = sorted(hits, key=lambda i: attributes[i]["CSDUID"])
        if not len(hits):
            raise ValueError("Area outside every census subdivision: " + area["da_uid"])
        row = attributes[hits[0]]
        out[area["da_uid"]] = {"csd_uid": row["CSDUID"], "csd_name": row["CSDNAME"], "csd_type": row["CSDTYPE"]}
    return out


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--csd-json", type=Path, required=True)
    args = parser.parse_args()
    source = STUDY / "data/walk-network-source"
    source.mkdir(parents=True, exist_ok=True)
    mapping = assign(STUDY, args.csd_json)
    with (source / "da-to-csd.json").open("w", encoding="utf-8") as handle:
        json.dump(mapping, handle, indent=0, sort_keys=True)
        handle.write("\n")
    print("VERDICT: PASS", len(mapping), "areas assigned", len({row["csd_uid"] for row in mapping.values()}), "subdivisions;",
          "raw response sha256", digest(args.csd_json))
