"""Plot the documented Paris topology discrepancy. Run alongside raumvergleich.py."""
import io
import json
import sys
import zipfile
from pathlib import Path
from urllib.request import urlopen

import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
from raumvergleich import SOURCE, ROOT

if len(sys.argv) > 1:
    archive = Path(sys.argv[1])
else:
    with urlopen(SOURCE, timeout=45) as response:
        archive = io.BytesIO(response.read())
with zipfile.ZipFile(archive) as source:
    features = json.loads(source.read("guerry/guerry.geojson"))["features"]

fig, ax = plt.subplots(figsize=(5.6, 3.8))
colors = {75: "#245f5d", 77: "#bfd7d0", 78: "#eadbb9"}
segments = {i: set() for i in colors}
for feature in features:
    dept = int(feature["properties"]["dept"])
    if dept not in colors:
        continue
    geom = feature["geometry"]
    polygons = geom["coordinates"] if geom["type"] == "MultiPolygon" else [geom["coordinates"]]
    for rings in polygons:
        for index, ring in enumerate(rings):
            ax.fill(*zip(*ring), color=colors[dept] if index == 0 else "#faf8f1",
                    edgecolor="#52665f", lw=.5, zorder=3 if dept == 75 else 1)
            for a, b in zip(ring, ring[1:]):
                if a != b:
                    segments[dept].add(tuple(sorted((tuple(a), tuple(b)))))
disputed = segments[75] & segments[77]
ax.add_collection(LineCollection(sorted(disputed), colors="#a52d1c", linewidths=3, zorder=5))
ax.autoscale_view()
ax.set_aspect("equal")
ax.axis("off")
fig.tight_layout(pad=0.1)
fig.savefig(ROOT / "paris.svg", transparent=True, bbox_inches="tight", pad_inches=.04)
