"""Appendix C map: ville30_detailed vs brr_segments_speed on the Woluwelaan. Run fetch_bxl.py and compare.py first."""
import json, math
import matplotlib; matplotlib.use('Agg')
import matplotlib.pyplot as plt
from shapely.geometry import shape
v = {int(f['properties']['urbis_id']): f for f in json.load(open('ville30_detailed.geojson'))['features'] if f['properties']['urbis_id']}
b = {f['properties']['urbis_id']: f for f in json.load(open('brr_segments_speed.geojson'))['features']}
c = json.load(open('conflicts.json'))
conf = set(c['30_vs_50']) | set(c['50_vs_30'])
CX, CY, R = 4.4347, 50.8372, 0.0075
BOX = (CX - R, CX + R, CY - R * 0.63, CY + R * 0.63)
def inbox(f):
    if not f.get('geometry'): return False
    return any(BOX[0] < x < BOX[1] and BOX[2] < y < BOX[3] for line in f['geometry']['coordinates'] for x, y in line)
BLUE, ORANGE, GREY, RED = '#3b6fb6', '#e08a1e', '#b9b9b9', '#d62728'
col_v = lambda s: BLUE if s == '30' else ORANGE if s == '50' else GREY
col_b = lambda s: ORANGE if s == 50 else BLUE if s == 30 else GREY
fig, axes = plt.subplots(1, 2, figsize=(16, 8.2), dpi=150)
for ax, layer, title, colf in ((axes[0], v, 'ville30_detailed', col_v), (axes[1], b, 'brr_segments_speed', col_b)):
    for k, f in layer.items():
        if not inbox(f): continue
        lw = 1.4
        if k in conf:
            lw = 3.4
            for line in f['geometry']['coordinates']:
                xs, ys = zip(*line); ax.plot(xs, ys, color=RED, lw=9, alpha=0.30, solid_capstyle='round')
        for line in f['geometry']['coordinates']:
            xs, ys = zip(*line); ax.plot(xs, ys, color=colf(f['properties']['speed']), lw=lw, solid_capstyle='round')
    for sid, txt, pos in ((155054217, 'segment 155054217:  50 vs 30', (0.60, 0.86)),
                          (11052339, 'segment 11052339 (8 m):  30 vs 50', (0.60, 0.62)),
                          (155057471, 'segment 155057471:  50 vs 30', (0.60, 0.40))):
        p = shape(b[sid]['geometry']).interpolate(0.5, normalized=True)
        ax.annotate(txt, xy=(p.x, p.y), xytext=pos, textcoords='axes fraction', fontsize=10, color=RED,
                    bbox=dict(boxstyle='round,pad=0.25', fc='white', ec=RED, lw=0.8),
                    arrowprops=dict(arrowstyle='->', color=RED, lw=1.3))
    ax.set_xlim(BOX[0], BOX[1]); ax.set_ylim(BOX[2], BOX[3]); ax.set_aspect(1 / math.cos(math.radians(CY)))
    ax.set_xticks([]); ax.set_yticks([])
    ax.set_title(title, fontsize=15, loc='left', family='monospace')
axes[0].text(0.01, 0.01, 'blue = 30   orange = 50   grey = other value', transform=axes[0].transAxes, fontsize=10)
axes[1].text(0.01, 0.01, 'orange = 50   blue = 30   grey = code (1, 2, 13, 99 ...)', transform=axes[1].transAxes, fontsize=10)
fig.suptitle('Same road segments, two official speed layers (Brussels Mobility GeoServer). Red halo: the layers disagree on the same segment '
             '(labels: ville30_detailed vs brr_segments_speed, km/h).', fontsize=12, x=0.01, ha='left', y=0.985)
fig.text(0.01, 0.01, 'Source: data-mobility.irisnet.be/geoserver/wfs, layers bm_network:ville30_detailed and bm_network:brr_segments_speed, '
         'joined on urbis_id, downloaded 24 November 2026. Sint-Pieters-Woluwe.', fontsize=9, color='#444')
plt.tight_layout(rect=(0, 0.03, 1, 0.95))
plt.savefig('appendix-c-woluwelaan.png')
