weathervane 0.13.0

Weather data, air quality, and alerts from public APIs. Fetches, parses, and returns clean Rust types.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
// SPDX-License-Identifier: MIT OR Apache-2.0

//! Weather alerts from regional providers (NWS, MeteoAlarm, ECCC, BOM).

use std::collections::HashSet;
use std::sync::RwLock;

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};

use crate::client::http_client;
use crate::error::{Error, Result};
use crate::geo::{
    detect_region, encode_geohash, get_eccc_office_codes, get_meteoalarm_info, point_in_polygon,
    reverse_geocode, MeteoAlarmCodenames, NominatimAddress, Region,
};

/// Weather alert severity levels.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum AlertSeverity {
    /// Low-impact advisory. Frost warnings, wind advisories, etc.
    Minor,
    /// Moderate impact. Weather watches, flood advisories.
    Moderate,
    /// High impact. Severe thunderstorm warnings, winter storm warnings.
    Severe,
    /// Life-threatening. Tornado warnings, hurricane warnings.
    Extreme,
    /// Provider didn't include a severity or used an unrecognized value.
    Unknown,
}

impl AlertSeverity {
    /// Parses CAP severity string into enum variant.
    /// Handles variations across providers (NWS, MeteoAlarm, ECCC).
    fn from_cap_string(s: &str) -> Self {
        match s.to_lowercase().as_str() {
            "minor" => Self::Minor,
            "moderate" => Self::Moderate,
            "severe" | "major" => Self::Severe,
            "extreme" => Self::Extreme,
            _ => Self::Unknown,
        }
    }
}

/// Weather alert from NWS, MeteoAlarm, ECCC, or BOM.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Alert {
    /// Provider-specific identifier for deduplication.
    pub id: String,
    /// Short event type (e.g. "Tornado Warning", "Heat Advisory").
    pub event: String,
    /// How bad it is.
    pub severity: AlertSeverity,
    /// One-line summary from the provider.
    pub headline: String,
    /// Full alert text. May be empty for some providers (MeteoAlarm, BOM).
    pub description: String,
    /// When this alert stops being relevant.
    pub expires: DateTime<Utc>,
}

/// One alert with the provider's name for the area it covers.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AlertEntry {
    pub alert: Alert,
    /// Provider's area name for this entry: MeteoAlarm `cap:areaDesc`, NWS
    /// `areaDesc`, the containing ECCC polygon's `areaDesc`. Empty where the
    /// provider sends none (BOM).
    pub area_desc: String,
}

/// What `fetch_alerts_detailed` returns: the alerts, and whether they were
/// narrowed to the caller's area.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AlertReport {
    pub alerts: Vec<AlertEntry>,
    /// `false` only when a MeteoAlarm national feed was returned unfiltered
    /// because no region could be matched for the location, by EMMA_ID, by
    /// area name, or by local-language area name, so the entries are
    /// national, not local. NWS, ECCC and BOM
    /// filter by point, polygon and geohash respectively, and an empty result
    /// is trivially filtered, so all of those are `true`.
    pub region_filtered: bool,
}

/// Fetches active weather alerts based on location, with each entry's area
/// name and whether the list was narrowed to the caller's area.
/// Dispatches to the appropriate regional API.
pub async fn fetch_alerts_detailed(latitude: f64, longitude: f64) -> Result<AlertReport> {
    match detect_region(latitude, longitude) {
        Region::Us => fetch_nws_alerts(latitude, longitude).await,
        Region::Europe => fetch_meteoalarm_alerts(latitude, longitude).await,
        Region::Canada => fetch_eccc_alerts(latitude, longitude).await,
        Region::Australia => fetch_bom_alerts(latitude, longitude).await,
        Region::Unknown => Ok(AlertReport {
            alerts: vec![],
            region_filtered: true,
        }),
    }
}

/// Fetches active weather alerts based on location.
/// Thin wrapper over `fetch_alerts_detailed` that drops the area names and
/// the filtering flag.
pub async fn fetch_alerts(latitude: f64, longitude: f64) -> Result<Vec<Alert>> {
    let report = fetch_alerts_detailed(latitude, longitude).await?;
    Ok(report.alerts.into_iter().map(|entry| entry.alert).collect())
}

// ---------------------------------------------------------------------------
// NWS (United States)
// ---------------------------------------------------------------------------

/// NWS API GeoJSON response.
#[derive(Debug, Deserialize)]
struct NwsAlertsResponse {
    features: Vec<NwsAlertFeature>,
}

#[derive(Debug, Deserialize)]
struct NwsAlertFeature {
    properties: NwsAlertProperties,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct NwsAlertProperties {
    id: String,
    event: String,
    severity: Option<String>,
    headline: Option<String>,
    description: Option<String>,
    sent: String,
    expires: Option<String>,
    #[serde(rename = "areaDesc")]
    area_desc: Option<String>,
}

/// Fetches active weather alerts from the NWS API for US locations.
async fn fetch_nws_alerts(latitude: f64, longitude: f64) -> Result<AlertReport> {
    let url = format!(
        "https://api.weather.gov/alerts/active?point={},{}",
        latitude, longitude
    );

    let response = http_client()?
        .get(&url)
        .header("Accept", "application/geo+json")
        .send()
        .await?;

    if !response.status().is_success() {
        tracing::warn!("NWS API returned status: {}", response.status());
        return Ok(AlertReport {
            alerts: vec![],
            region_filtered: true,
        });
    }

    let data: NwsAlertsResponse = response.json().await?;

    let alerts = nws_alerts_from_response(data);

    tracing::debug!("Fetched {} alert(s) from NWS", alerts.len());
    // The point query already narrowed the list to the caller's location.
    Ok(AlertReport {
        alerts,
        region_filtered: true,
    })
}

/// Lives in its own function so it can be unit-tested against fixtures without a live network.
fn nws_alerts_from_response(data: NwsAlertsResponse) -> Vec<AlertEntry> {
    data.features
        .into_iter()
        .filter_map(|feature| {
            let props = feature.properties;

            let sent = DateTime::parse_from_rfc3339(&props.sent)
                .ok()?
                .with_timezone(&Utc);

            let expires = props
                .expires
                .as_ref()
                .and_then(|e| DateTime::parse_from_rfc3339(e).ok())
                .map(|dt| dt.with_timezone(&Utc))
                .unwrap_or_else(|| sent + chrono::Duration::hours(24));

            if expires < Utc::now() {
                return None;
            }

            Some(AlertEntry {
                alert: Alert {
                    id: props.id,
                    event: props.event,
                    severity: props
                        .severity
                        .as_deref()
                        .map(AlertSeverity::from_cap_string)
                        .unwrap_or(AlertSeverity::Unknown),
                    headline: props.headline.unwrap_or_default(),
                    description: props.description.unwrap_or_default(),
                    expires,
                },
                area_desc: props.area_desc.unwrap_or_default(),
            })
        })
        .collect()
}

// ---------------------------------------------------------------------------
// MeteoAlarm (Europe)
// ---------------------------------------------------------------------------

/// MeteoAlarm Atom feed response.
#[derive(Debug, Deserialize)]
struct MeteoAlarmFeed {
    #[serde(rename = "entry", default)]
    entries: Vec<MeteoAlarmEntry>,
}

/// Single alert entry from MeteoAlarm Atom feed.
#[derive(Debug, Deserialize)]
struct MeteoAlarmEntry {
    id: String,
    title: Option<String>,
    #[serde(rename = "identifier")]
    cap_identifier: Option<String>,
    #[serde(rename = "event")]
    cap_event: Option<String>,
    #[serde(rename = "severity")]
    cap_severity: Option<String>,
    #[serde(rename = "sent")]
    cap_sent: Option<String>,
    #[serde(rename = "expires")]
    cap_expires: Option<String>,
    #[serde(rename = "geocode")]
    cap_geocode: Option<MeteoAlarmGeocode>,
    #[serde(rename = "areaDesc")]
    cap_area_desc: Option<String>,
}

/// Geocode element containing EMMA_ID area identifier.
#[derive(Debug, Deserialize)]
struct MeteoAlarmGeocode {
    /// Which scheme `value` belongs to. Most feeds say `EMMA_ID`; France says
    /// `NUTS3`, whose codes are not EMMA_IDs and must not be filtered as such.
    #[serde(rename = "valueName")]
    value_name: Option<String>,
    value: Option<String>,
}

/// MeteoAlarm v1 JSON API response, `/api/v1/warnings/feeds-<slug>`. Read
/// only for its per-language `areaDesc` values; the atom feed stays the
/// source of alerts.
#[derive(Debug, Deserialize)]
struct MeteoAlarmJsonFeed {
    #[serde(default)]
    warnings: Vec<MeteoAlarmJsonWarning>,
}

#[derive(Debug, Deserialize)]
struct MeteoAlarmJsonWarning {
    alert: MeteoAlarmJsonAlert,
}

#[derive(Debug, Deserialize)]
struct MeteoAlarmJsonAlert {
    #[serde(default)]
    info: Vec<MeteoAlarmJsonInfo>,
}

/// One `info` block per language (`en-GB`, `el-GR`, `bg`, ...), each with
/// the same areas in the same order.
#[derive(Debug, Deserialize)]
struct MeteoAlarmJsonInfo {
    language: Option<String>,
    #[serde(default)]
    area: Vec<MeteoAlarmJsonArea>,
}

#[derive(Debug, Deserialize)]
struct MeteoAlarmJsonArea {
    #[serde(rename = "areaDesc")]
    area_desc: Option<String>,
}

/// One region as the feed names it in the local language and in English.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
struct LocalArea {
    local: String,
    english: String,
}

/// Resolves the user's EMMA_ID by matching their place names against the
/// MeteoAlarm codename list.
async fn resolve_user_emma_id(address: &NominatimAddress, country_code: &str) -> Option<String> {
    let codenames = fetch_meteoalarm_codenames().await?;
    match_emma_id(address, country_code, &codenames)
}

/// The codename list, fetched once per process. It is 72 KB from a third
/// party's `master` branch and changes rarely, so refetching it on every
/// call was the largest request in the whole alerts path.
static CODENAMES_CACHE: RwLock<Option<MeteoAlarmCodenames>> = RwLock::new(None);

fn cached_codenames() -> Option<MeteoAlarmCodenames> {
    CODENAMES_CACHE.read().ok()?.clone()
}

fn cache_codenames(codenames: &MeteoAlarmCodenames) {
    if let Ok(mut guard) = CODENAMES_CACHE.write() {
        *guard = Some(codenames.clone());
    }
}

/// Cached front for the network fetch, in the shape of `STATION_CACHE` and
/// the geocode cache: filled on the first success, failures not cached so a
/// transient miss retries on the next call.
async fn fetch_meteoalarm_codenames() -> Option<MeteoAlarmCodenames> {
    if let Some(codenames) = cached_codenames() {
        return Some(codenames);
    }
    let codenames = fetch_meteoalarm_codenames_uncached().await?; // no lock held across .await
    cache_codenames(&codenames);
    Some(codenames)
}

/// Split from the matching so its three failure points get distinct messages
/// rather than collapsing into one silent `None`.
async fn fetch_meteoalarm_codenames_uncached() -> Option<MeteoAlarmCodenames> {
    const CODENAMES_URL: &str =
        "https://raw.githubusercontent.com/ktrue/Meteoalarm-warning/master/meteoalarm-codenames.json";

    let client = match http_client() {
        Ok(client) => client,
        Err(e) => {
            tracing::warn!(
                "No HTTP client for MeteoAlarm codenames ({}); region filter cannot be applied",
                e
            );
            return None;
        }
    };

    let response = match client.get(CODENAMES_URL).send().await {
        Ok(response) => response,
        Err(e) => {
            tracing::warn!(
                "MeteoAlarm codenames fetch failed ({}); region filter cannot be applied",
                e
            );
            return None;
        }
    };

    match response.json::<MeteoAlarmCodenames>().await {
        Ok(codenames) => Some(codenames),
        Err(e) => {
            tracing::warn!(
                "MeteoAlarm codenames decode failed ({}); region filter cannot be applied",
                e
            );
            None
        }
    }
}

/// The feed's own local-language area names, paired with the English names
/// the atom feed uses. Read from the v1 JSON API, whose alerts carry one
/// `info` block per language. Expired warnings are kept: this is a name
/// inventory, not an alert list, and a larger one matches more quiet regions.
/// Not cached: it is fetched only on the non-Latin miss path, once per
/// refresh, and a fresh inventory is worth more than one saved request.
async fn fetch_meteoalarm_local_areas(slug: &str) -> Option<Vec<LocalArea>> {
    let url = format!(
        "https://feeds.meteoalarm.org/api/v1/warnings/feeds-{}",
        slug
    );

    let client = match http_client() {
        Ok(client) => client,
        Err(e) => {
            tracing::warn!(
                "No HTTP client for MeteoAlarm local area names ({}); national feed stays unfiltered",
                e
            );
            return None;
        }
    };

    let response = match client.get(&url).send().await {
        Ok(response) => response,
        Err(e) => {
            tracing::warn!(
                "MeteoAlarm local area names fetch failed ({}); national feed stays unfiltered",
                e
            );
            return None;
        }
    };

    match response.json::<MeteoAlarmJsonFeed>().await {
        Ok(feed) => Some(local_areas_from_json(feed)),
        Err(e) => {
            tracing::warn!(
                "MeteoAlarm local area names decode failed ({}); national feed stays unfiltered",
                e
            );
            None
        }
    }
}

/// Every (local name, English name) pair the feed carries, sorted and
/// deduplicated. Every non-English block pairs with every English block
/// (Serbia sends `sr-Latn` and `sr` beside `en-GB`); within a block, area
/// `i` pairs with area `i`, which is how the sampled feeds are laid out.
fn local_areas_from_json(feed: MeteoAlarmJsonFeed) -> Vec<LocalArea> {
    let mut pairs = Vec::new();
    for warning in feed.warnings {
        let (english, local): (Vec<_>, Vec<_>) = warning.alert.info.into_iter().partition(|info| {
            info.language
                .as_deref()
                .map(|l| l.starts_with("en"))
                .unwrap_or(false)
        });
        for local_info in &local {
            for english_info in &english {
                for (l, e) in local_info.area.iter().zip(english_info.area.iter()) {
                    if let (Some(l), Some(e)) = (l.area_desc.as_deref(), e.area_desc.as_deref()) {
                        if !l.is_empty() && !e.is_empty() {
                            pairs.push(LocalArea {
                                local: l.to_string(),
                                english: e.to_string(),
                            });
                        }
                    }
                }
            }
        }
    }
    pairs.sort();
    pairs.dedup();
    pairs
}

/// Place names to try, most specific first.
fn emma_search_terms(address: &NominatimAddress) -> Vec<String> {
    let mut terms: Vec<String> = Vec::new();

    if let Some(city) = &address.city {
        terms.push(city.clone());
        terms.push(format!("Stadt {}", city));
    }
    if let Some(town) = &address.town {
        terms.push(town.clone());
    }
    if let Some(village) = &address.village {
        terms.push(village.clone());
    }
    if let Some(municipality) = &address.municipality {
        terms.push(municipality.clone());
    }
    if let Some(county) = &address.county {
        terms.push(county.clone());
        terms.push(format!("Kreis {}", county));
    }
    if let Some(state) = &address.state {
        terms.push(state.clone());
    }

    terms
}

/// The matching itself, split from the fetch so it is testable without a network.
fn match_emma_id(
    address: &NominatimAddress,
    country_code: &str,
    codenames: &MeteoAlarmCodenames,
) -> Option<String> {
    let country_prefix = country_code.to_uppercase();
    let search_terms = emma_search_terms(address);

    for search_term in &search_terms {
        let search_lower = search_term.to_lowercase();

        // Rank every candidate rather than taking the first hit. `codes` is a
        // HashMap, so "first hit" means whichever one iteration happened to
        // reach, and Vienna's "Wien" matches 26 Austrian codenames.
        let best = codenames
            .codes
            .iter()
            .filter(|(emma_id, _)| emma_id.starts_with(&country_prefix))
            .filter_map(|(emma_id, name)| {
                rank_emma_match(&search_lower, &name.to_lowercase()).map(|rank| (rank, emma_id))
            })
            // Equal ranks fall back to the EMMA_ID, which is unique, so the
            // winner is total and identical on every run. Reversed because the
            // lower ID is the one to keep.
            .max_by(|(a_rank, a_id), (b_rank, b_id)| {
                a_rank.cmp(b_rank).then_with(|| b_id.cmp(a_id))
            });

        if let Some((_, emma_id)) = best {
            tracing::debug!("Resolved EMMA_ID: {}", emma_id);
            return Some(emma_id.clone());
        }
    }

    tracing::warn!(
        "No EMMA_ID matched {:?} in {}; will try the feed's own area names",
        search_terms,
        country_prefix
    );
    None
}

/// How well one codename fits one search term, worst variant first so `max_by`
/// picks the strongest fit.
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
enum EmmaMatch {
    /// The codename is the longer string, as "Wiener Neustadt" is for a search
    /// of "Wien". The weakest kind of hit, and the shorter codename is the
    /// closer one, hence the `Reverse`.
    CodenameContainsTerm(std::cmp::Reverse<usize>),
    /// The search term is the longer string, as "Warsaw County" is for a
    /// codename of "Warsaw". A real hit on a coarser region, and here the
    /// longer codename is the more specific one.
    TermContainsCodename(usize),
    /// Same name on both sides.
    Exact,
}

/// Returns None when the two do not relate at all. Empty strings never match,
/// since `contains("")` is true for everything and would hand back an arbitrary
/// region for a location Nominatim gave a blank name.
fn rank_emma_match(search_lower: &str, name_lower: &str) -> Option<EmmaMatch> {
    if search_lower.is_empty() || name_lower.is_empty() {
        return None;
    }

    if name_lower == search_lower {
        Some(EmmaMatch::Exact)
    } else if search_lower.contains(name_lower) {
        Some(EmmaMatch::TermContainsCodename(name_lower.len()))
    } else if name_lower.contains(search_lower) {
        Some(EmmaMatch::CodenameContainsTerm(std::cmp::Reverse(
            name_lower.len(),
        )))
    } else {
        None
    }
}

/// Administrative words that name a level, not a place. Dropped from both
/// sides of an area-name compare so "Grad Zagreb" and "Zagreb region" meet.
const AREA_AFFIXES: &[&str] = &[
    "grad",
    "stadt",
    "kreis",
    "landkreis",
    "region",
    "county",
    "district",
    "city",
    "municipality",
    "powiat",
    "gmina",
    "okres",
    "kraj",
    "oblast",
    "περιφερεια",
    "περιφερειακη",
    "ενοτητα",
    "δημος",
    "νομος",
    "област",
    "община",
    "град",
];

/// Lowercase, diacritics folded, split into tokens, administrative affixes
/// dropped. "Grad Zagreb" and "Zagreb region" both become ["zagreb"].
fn area_tokens(name: &str) -> Vec<String> {
    use unicode_normalization::UnicodeNormalization;

    let folded: String = name
        .nfd()
        .filter(|c| !unicode_normalization::char::is_combining_mark(*c))
        .collect::<String>()
        .to_lowercase();
    folded
        .split(|c: char| !c.is_alphanumeric())
        .filter(|t| !t.is_empty() && !AREA_AFFIXES.contains(t))
        .map(str::to_string)
        .collect()
}

fn is_latin(c: char) -> bool {
    c.is_ascii_alphabetic()
        || ('\u{00C0}'..='\u{024F}').contains(&c)
        || ('\u{1E00}'..='\u{1EFF}').contains(&c)
}

/// True when any name carries a letter outside the Latin script, which is
/// when the atom feed's English area names cannot match and the
/// local-language inventory is worth a request.
fn has_non_latin(names: &[String]) -> bool {
    names
        .iter()
        .flat_map(|t| t.chars())
        .any(|c| c.is_alphabetic() && !is_latin(c))
}

/// Token equality with one concession to inflection: two non-Latin tokens of
/// five or more characters match when one is the other plus at most two
/// trailing characters ("αττικη" and "αττικης"). Latin tokens compare exactly,
/// so nothing changes for Latin-script countries.
fn tokens_equal(a: &str, b: &str) -> bool {
    if a == b {
        return true;
    }
    let (shorter, longer) = if a.chars().count() <= b.chars().count() {
        (a, b)
    } else {
        (b, a)
    };
    let non_latin = |s: &str| s.chars().any(|c| c.is_alphabetic() && !is_latin(c));
    non_latin(shorter)
        && non_latin(longer)
        && shorter.chars().count() >= 5
        && longer.starts_with(shorter)
        && longer.chars().count() - shorter.chars().count() <= 2
}

/// How well one place name fits one area name, weakest first so `max` picks
/// the strongest.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
enum AreaMatch {
    /// Every significant token of the shorter name appears in the longer one.
    Tokens,
    /// Same tokens in the same order.
    Exact,
}

/// Returns None when the two do not relate. No substring or prefix compare on
/// Latin tokens: "seine" does not fit "seinemaritime"; non-Latin tokens get
/// the `tokens_equal` inflection allowance. The shorter side must carry at
/// least one token of three or more characters, so a stray "i" or "de"
/// cannot anchor a match on its own.
fn rank_area_match(term_tokens: &[String], area_tokens: &[String]) -> Option<AreaMatch> {
    if term_tokens.is_empty() || area_tokens.is_empty() {
        return None;
    }
    if term_tokens.len() == area_tokens.len()
        && term_tokens
            .iter()
            .zip(area_tokens)
            .all(|(t, a)| tokens_equal(t, a))
    {
        return Some(AreaMatch::Exact);
    }
    let (shorter, longer) = if term_tokens.len() <= area_tokens.len() {
        (term_tokens, area_tokens)
    } else {
        (area_tokens, term_tokens)
    };
    let anchored = shorter.iter().any(|t| t.chars().count() >= 3);
    if anchored
        && shorter
            .iter()
            .all(|t| longer.iter().any(|l| tokens_equal(t, l)))
    {
        Some(AreaMatch::Tokens)
    } else {
        None
    }
}

/// The one area name the user's place names pick out of the feed, or None.
///
/// Terms run most specific first. Within a term the best rank wins, and it
/// counts only when every area at that rank is the same area, so a place name
/// that fits several regions ("Seine" against three départements) is a miss
/// for that term rather than a guess, and the next term is tried.
fn match_area(search_terms: &[String], area_names: &[String]) -> Option<String> {
    for term in search_terms {
        let term_tokens = area_tokens(term);
        let mut ranked: Vec<(AreaMatch, &str)> = area_names
            .iter()
            .filter_map(|area| {
                rank_area_match(&term_tokens, &area_tokens(area)).map(|rank| (rank, area.as_str()))
            })
            .collect();
        let Some(best) = ranked.iter().map(|(rank, _)| rank.clone()).max() else {
            continue;
        };
        ranked.retain(|(rank, _)| *rank == best);
        let mut distinct: Vec<&str> = ranked.iter().map(|(_, area)| *area).collect();
        distinct.sort_unstable();
        distinct.dedup();
        match distinct.as_slice() {
            [area] => {
                tracing::debug!("Matched area {:?} by place name {:?}", area, term);
                return Some(area.to_string());
            }
            many => tracing::debug!(
                "Place name {:?} is ambiguous across {:?}; trying the next",
                term,
                many
            ),
        }
    }
    None
}

/// Fetches active weather alerts from MeteoAlarm for European locations.
async fn fetch_meteoalarm_alerts(latitude: f64, longitude: f64) -> Result<AlertReport> {
    // Failing to determine the country is an error, not an absence of alerts.
    // Returning Ok(vec![]) here would be indistinguishable from a quiet day,
    // which is the silent-failure pattern this whole path is being fixed for.
    // The warn! stays because consumers do swallow errors.
    let address = match reverse_geocode(latitude, longitude).await {
        Ok(address) => address,
        Err(e) => {
            tracing::warn!(
                "Reverse geocoding failed ({}); cannot determine country for MeteoAlarm",
                e
            );
            return Err(e);
        }
    };

    let iso_code = match address.country_code.as_deref() {
        Some(iso_code) => iso_code,
        None => {
            tracing::warn!("Reverse geocode returned no country code; cannot select a feed");
            return Err(Error::LocationDetection);
        }
    };

    // Local-language name, for logs only; every lookup below keys on the code.
    let country = address.country.as_deref().unwrap_or(iso_code);

    // Not covered is a real absence: the country exists, MeteoAlarm has no feed
    // for it. That stays Ok(vec![]).
    let (slug, country_code) = match get_meteoalarm_info(iso_code) {
        Some(info) => info,
        None => {
            tracing::debug!("{} ({}) is not covered by MeteoAlarm", country, iso_code);
            return Ok(AlertReport {
                alerts: vec![],
                region_filtered: true,
            });
        }
    };

    let user_emma_id = resolve_user_emma_id(&address, country_code).await;

    let url = format!(
        "https://feeds.meteoalarm.org/feeds/meteoalarm-legacy-atom-{}",
        slug
    );

    let response = http_client()?.get(&url).send().await?;
    if !response.status().is_success() {
        tracing::warn!("MeteoAlarm returned status: {}", response.status());
        return Ok(AlertReport {
            alerts: vec![],
            region_filtered: user_emma_id.is_some(),
        });
    }

    let xml_text = response.text().await?;
    let feed: MeteoAlarmFeed = quick_xml::de::from_str(&xml_text)?;

    let search_terms = emma_search_terms(&address);
    let report = meteoalarm_alerts_from_feed(feed, &user_emma_id, &search_terms, country);

    // Stage 3, only after a stage-2 miss for a non-Latin place name: the
    // feed's local-language area names, one request, no cache.
    if report.region_filtered || !has_non_latin(&search_terms) {
        return Ok(report);
    }
    let Some(local_areas) = fetch_meteoalarm_local_areas(slug).await else {
        return Ok(report);
    };
    Ok(apply_local_area_match(
        report,
        &search_terms,
        &local_areas,
        country,
    ))
}

/// The entry's EMMA_ID, if the feed tagged it with one. A geocode under any
/// other scheme (`NUTS3` in France) is not an EMMA_ID and yields `None`.
fn entry_emma_id(entry: &MeteoAlarmEntry) -> Option<&str> {
    entry
        .cap_geocode
        .as_ref()
        .filter(|gc| gc.value_name.as_deref() == Some("EMMA_ID"))
        .and_then(|gc| gc.value.as_deref())
}

/// Lives in its own function so it can be unit-tested against fixtures without a live network.
///
/// Two stages. Stage 1: a resolved EMMA_ID filters a feed that tags its
/// entries with EMMA_IDs; this is exact and, since the feed only lists regions
/// that are alerting, it is the only stage that can tell a quiet day from a
/// miss. Stage 2, when stage 1 has no usable filter: the user's place names
/// are matched against the feed's own `areaDesc` values. A hit filters to that
/// area; a miss keeps the national feed and says so. Stage 3, in
/// `fetch_meteoalarm_alerts`, retries a stage-2 miss for non-Latin place
/// names against the feed's local-language names (`apply_local_area_match`).
fn meteoalarm_alerts_from_feed(
    feed: MeteoAlarmFeed,
    user_emma_id: &Option<String>,
    search_terms: &[String],
    country: &str,
) -> AlertReport {
    if feed.entries.is_empty() {
        tracing::debug!("Fetched 0 alert(s) from MeteoAlarm ({})", country);
        return AlertReport {
            alerts: vec![],
            region_filtered: true,
        };
    }

    let feed_has_emma_ids = feed
        .entries
        .iter()
        .any(|entry| entry_emma_id(entry).is_some());

    // Stage 1: EMMA_ID against an EMMA_ID-tagged feed.
    if let Some(user_id) = user_emma_id {
        if feed_has_emma_ids {
            let untagged = feed
                .entries
                .iter()
                .filter(|entry| entry_emma_id(entry).is_none())
                .count();
            if untagged > 0 {
                tracing::debug!(
                    "Dropped {} untagged MeteoAlarm entr(y/ies) while filtering to {}",
                    untagged,
                    user_id
                );
            }
            let filter = Some(user_id.clone());
            let alerts: Vec<AlertEntry> = feed
                .entries
                .into_iter()
                .filter_map(|entry| parse_meteoalarm_entry(entry, &filter))
                .collect();
            tracing::debug!(
                "Fetched {} alert(s) from MeteoAlarm ({}), filtered to {}",
                alerts.len(),
                country,
                user_id
            );
            return AlertReport {
                alerts,
                region_filtered: true,
            };
        }

        let mut schemes: Vec<&str> = feed
            .entries
            .iter()
            .filter_map(|entry| entry.cap_geocode.as_ref())
            .filter_map(|gc| gc.value_name.as_deref())
            .collect();
        schemes.sort_unstable();
        schemes.dedup();
        tracing::warn!(
            "MeteoAlarm feed ({}) carries no EMMA_ID geocodes (found {:?}); the filter to {} \
            cannot apply, matching by area name instead",
            country,
            schemes,
            user_id
        );
    }

    // Stage 2: place names against the feed's own area names.
    let mut area_names: Vec<String> = feed
        .entries
        .iter()
        .filter_map(|entry| entry.cap_area_desc.clone())
        .filter(|name| !name.is_empty())
        .collect();
    area_names.sort_unstable();
    area_names.dedup();

    match match_area(search_terms, &area_names) {
        Some(area) => {
            let alerts: Vec<AlertEntry> = feed
                .entries
                .into_iter()
                .filter(|entry| entry.cap_area_desc.as_deref() == Some(area.as_str()))
                .filter_map(|entry| parse_meteoalarm_entry(entry, &None))
                .collect();
            tracing::debug!(
                "Fetched {} alert(s) from MeteoAlarm ({}), filtered to area {:?}",
                alerts.len(),
                country,
                area
            );
            AlertReport {
                alerts,
                region_filtered: true,
            }
        }
        None => {
            let alerts: Vec<AlertEntry> = feed
                .entries
                .into_iter()
                .filter_map(|entry| parse_meteoalarm_entry(entry, &None))
                .collect();
            let shown: Vec<&str> = area_names.iter().take(10).map(String::as_str).collect();
            tracing::warn!(
                "Fetched {} alert(s) from MeteoAlarm ({}), UNFILTERED - no area name matched {:?} \
                among {} area(s) ({:?}{}); these are national alerts, not local ones",
                alerts.len(),
                country,
                search_terms,
                area_names.len(),
                shown,
                if area_names.len() > shown.len() {
                    ", ..."
                } else {
                    ""
                }
            );
            AlertReport {
                alerts,
                region_filtered: false,
            }
        }
    }
}

/// Stage 3: the stage-2 miss retried against the feed's local-language area
/// names. A hit narrows the already-parsed entries to the region whose
/// English name is the paired one; a miss returns the report unchanged.
fn apply_local_area_match(
    report: AlertReport,
    search_terms: &[String],
    local_areas: &[LocalArea],
    country: &str,
) -> AlertReport {
    let local_names: Vec<String> = local_areas.iter().map(|a| a.local.clone()).collect();
    if !has_non_latin(&local_names) {
        // Israel's `he-IL` block repeats the English names; say so rather than
        // report a miss that no place name could ever have avoided.
        tracing::warn!(
            "MeteoAlarm ({}) JSON feed carries no local-language area names ({} English only); \
            national feed stays unfiltered",
            country,
            local_names.len()
        );
        return report;
    }
    let Some(local) = match_area(search_terms, &local_names) else {
        tracing::warn!(
            "No local-language area name matched {:?} among {} for MeteoAlarm ({}); \
            national feed stays unfiltered",
            search_terms,
            local_names.len(),
            country
        );
        return report;
    };
    // Raw compare: the parsed atom `area_desc` and the JSON English name are
    // byte-identical (quick_xml has already unescaped the atom's extra level).
    // Token equality would collapse "Sofia-city" and "Sofia-region".
    let english: Vec<&str> = local_areas
        .iter()
        .filter(|a| a.local == local)
        .map(|a| a.english.as_str())
        .collect();
    let alerts: Vec<AlertEntry> = report
        .alerts
        .into_iter()
        .filter(|entry| english.contains(&entry.area_desc.as_str()))
        .collect();
    tracing::debug!(
        "Fetched {} alert(s) from MeteoAlarm ({}), filtered to area {:?} via its local name {:?}",
        alerts.len(),
        country,
        english,
        local
    );
    AlertReport {
        alerts,
        region_filtered: true,
    }
}

/// Parses a MeteoAlarm entry into an AlertEntry.
/// Returns None if it doesn't match the user's EMMA_ID or is expired.
fn parse_meteoalarm_entry(
    entry: MeteoAlarmEntry,
    user_emma_id: &Option<String>,
) -> Option<AlertEntry> {
    let now = Utc::now();

    // Filter by EMMA_ID if we resolved one for the user
    if let Some(user_id) = user_emma_id {
        match entry_emma_id(&entry) {
            Some(entry_id) if entry_id != user_id => return None,
            // An untagged entry cannot be shown to belong to the user's region;
            // when a filter is active it is dropped, not leaked past it.
            None => return None,
            _ => {}
        }
    }

    let sent = entry
        .cap_sent
        .as_ref()
        .and_then(|s| DateTime::parse_from_rfc3339(s).ok())
        .map(|dt| dt.with_timezone(&Utc))
        .unwrap_or(now);

    let expires = entry
        .cap_expires
        .as_ref()
        .and_then(|s| DateTime::parse_from_rfc3339(s).ok())
        .map(|dt| dt.with_timezone(&Utc))
        .unwrap_or_else(|| sent + chrono::Duration::hours(24));

    if expires < now {
        return None;
    }

    let event = entry
        .cap_event
        .unwrap_or_else(|| "Weather Alert".to_string());

    let headline = entry.title.unwrap_or_else(|| event.clone());

    let severity = entry
        .cap_severity
        .as_deref()
        .map(AlertSeverity::from_cap_string)
        .unwrap_or(AlertSeverity::Unknown);

    Some(AlertEntry {
        alert: Alert {
            id: entry.cap_identifier.unwrap_or(entry.id),
            event,
            severity,
            headline,
            description: String::new(),
            expires,
        },
        area_desc: entry.cap_area_desc.unwrap_or_default(),
    })
}

// ---------------------------------------------------------------------------
// ECCC (Canada)
// ---------------------------------------------------------------------------

/// ECCC CAP alert response structure.
#[derive(Debug, Deserialize)]
struct EcccCapAlert {
    identifier: String,
    status: String,
    #[serde(rename = "msgType")]
    msg_type: String,
    sent: String,
    #[serde(rename = "info", default)]
    info_blocks: Vec<EcccCapInfo>,
}

/// Info block from ECCC CAP alert (one per language).
#[derive(Debug, Deserialize)]
struct EcccCapInfo {
    language: Option<String>,
    event: Option<String>,
    severity: Option<String>,
    expires: Option<String>,
    headline: Option<String>,
    description: Option<String>,
    #[serde(rename = "area", default)]
    areas: Vec<EcccCapArea>,
}

/// Area element from ECCC CAP alert.
#[derive(Debug, Deserialize)]
struct EcccCapArea {
    #[serde(rename = "areaDesc")]
    area_desc: Option<String>,
    polygon: Option<String>,
}

/// Fetches active weather alerts from ECCC (Environment and Climate Change Canada).
async fn fetch_eccc_alerts(latitude: f64, longitude: f64) -> Result<AlertReport> {
    let offices = get_eccc_office_codes(latitude, longitude);
    let today = chrono::Utc::now().format("%Y%m%d").to_string();
    let client = http_client()?;

    let mut all_alerts: Vec<AlertEntry> = Vec::new();
    let mut seen_ids: HashSet<String> = HashSet::new();

    for office in offices {
        let dir_url = format!(
            "https://dd.weather.gc.ca/today/alerts/cap/{}/{}/",
            today, office
        );

        let dir_response = match client.get(&dir_url).send().await {
            Ok(resp) if resp.status().is_success() => resp,
            _ => continue,
        };

        let dir_html = match dir_response.text().await {
            Ok(text) => text,
            Err(_) => continue,
        };

        // Parse hour directories from HTML listing
        let hour_dirs: Vec<String> = dir_html
            .lines()
            .filter_map(|line| {
                if line.contains("href=\"") && line.contains("/\"") {
                    let start = line.find("href=\"")? + 6;
                    let end = line[start..].find('"')? + start;
                    let href = &line[start..end];
                    if href.len() == 3 && href.ends_with('/') {
                        let hour = &href[..2];
                        if hour.chars().all(|c| c.is_ascii_digit()) {
                            return Some(hour.to_string());
                        }
                    }
                }
                None
            })
            .collect();

        for hour in hour_dirs {
            let hour_url = format!("{}{}/", dir_url, hour);

            let hour_response = match client.get(&hour_url).send().await {
                Ok(resp) if resp.status().is_success() => resp,
                _ => continue,
            };

            let hour_html = match hour_response.text().await {
                Ok(text) => text,
                Err(_) => continue,
            };

            let cap_files: Vec<String> = hour_html
                .lines()
                .filter_map(|line| {
                    if line.contains(".cap\"") {
                        let start = line.find("href=\"")? + 6;
                        let end = line[start..].find('"')? + start;
                        let href = &line[start..end];
                        if href.ends_with(".cap") {
                            return Some(href.to_string());
                        }
                    }
                    None
                })
                .collect();

            for cap_file in cap_files {
                let cap_url = format!("{}{}", hour_url, cap_file);

                let cap_response = match client.get(&cap_url).send().await {
                    Ok(resp) if resp.status().is_success() => resp,
                    _ => continue,
                };

                let cap_xml = match cap_response.text().await {
                    Ok(text) => text,
                    Err(_) => continue,
                };

                if let Some(alert) = parse_eccc_cap(&cap_xml, latitude, longitude, &mut seen_ids) {
                    all_alerts.push(alert);
                }
            }
        }
    }

    tracing::debug!("Fetched {} alert(s) from ECCC", all_alerts.len());
    // Every entry passed the polygon check for the caller's point.
    Ok(AlertReport {
        alerts: all_alerts,
        region_filtered: true,
    })
}

/// Parses an ECCC CAP XML document into an Alert.
/// Filters by location using polygon containment and deduplicates by identifier.
fn parse_eccc_cap(
    xml: &str,
    lat: f64,
    lon: f64,
    seen_ids: &mut HashSet<String>,
) -> Option<AlertEntry> {
    let cap: EcccCapAlert = quick_xml::de::from_str(xml).ok()?;

    if cap.status != "Actual" {
        return None;
    }

    if cap.msg_type == "Cancel" {
        return None;
    }

    // Find English info block (prefer en-CA)
    let info = cap
        .info_blocks
        .iter()
        .find(|i| {
            i.language
                .as_ref()
                .map(|l| l.starts_with("en"))
                .unwrap_or(false)
        })
        .or_else(|| cap.info_blocks.first())?;

    // Check if user's location is within any of the alert areas
    let area_desc = info.areas.iter().find_map(|area| {
        area.polygon
            .as_ref()
            .filter(|poly| point_in_polygon(lat, lon, poly))
            .map(|_| area.area_desc.clone().unwrap_or_default())
    });

    let area_desc = area_desc?;

    let event = info
        .event
        .clone()
        .unwrap_or_else(|| "Weather Alert".to_string());

    // Deduplicate by event type + area (ECCC issues updates with new identifiers)
    let dedup_key = format!("{}|{}", event, area_desc);
    if seen_ids.contains(&dedup_key) {
        return None;
    }
    seen_ids.insert(dedup_key);

    let now = Utc::now();

    let sent = cap
        .sent
        .parse::<DateTime<chrono::FixedOffset>>()
        .ok()
        .map(|dt| dt.with_timezone(&Utc))
        .unwrap_or(now);

    let expires = info
        .expires
        .as_ref()
        .and_then(|s| s.parse::<DateTime<chrono::FixedOffset>>().ok())
        .map(|dt| dt.with_timezone(&Utc))
        .unwrap_or_else(|| sent + chrono::Duration::hours(24));

    if expires < now {
        return None;
    }

    let headline = info.headline.clone().unwrap_or_else(|| event.clone());

    Some(AlertEntry {
        alert: Alert {
            id: cap.identifier,
            event,
            severity: info
                .severity
                .as_deref()
                .map(AlertSeverity::from_cap_string)
                .unwrap_or(AlertSeverity::Unknown),
            headline,
            description: info.description.clone().unwrap_or_default(),
            expires,
        },
        area_desc,
    })
}

// ---------------------------------------------------------------------------
// BOM (Australia)
// ---------------------------------------------------------------------------

/// BOM API response wrapper.
#[derive(Debug, Deserialize)]
struct BomWarningsResponse {
    data: Vec<BomWarning>,
}

/// BOM API warning structure.
#[derive(Debug, Deserialize)]
struct BomWarning {
    id: String,
    #[serde(rename = "type")]
    warning_type: Option<String>,
    short_title: Option<String>,
    warning_group_type: Option<String>,
    phase: Option<String>,
    expiry_time: Option<String>,
}

/// Fetches weather alerts from the Australian Bureau of Meteorology.
async fn fetch_bom_alerts(latitude: f64, longitude: f64) -> Result<AlertReport> {
    let geohash = encode_geohash(latitude, longitude, 6);
    let url = format!(
        "https://api.weather.bom.gov.au/v1/locations/{}/warnings",
        geohash
    );

    let response = http_client()?.get(&url).send().await?;

    if !response.status().is_success() {
        return Ok(AlertReport {
            alerts: vec![],
            region_filtered: true,
        });
    }

    let response_body: BomWarningsResponse = response.json().await?;

    let alerts = bom_alerts_from_response(response_body.data);

    // The geohash lookup already narrowed the list to the caller's location.
    Ok(AlertReport {
        alerts,
        region_filtered: true,
    })
}

/// Lives in its own function so it can be unit-tested against fixtures without a live network.
fn bom_alerts_from_response(data: Vec<BomWarning>) -> Vec<AlertEntry> {
    let now = Utc::now();

    data.into_iter()
        .filter(|w| w.phase.as_deref() != Some("cancelled"))
        .filter_map(|w| {
            let severity = match w.warning_group_type.as_deref() {
                Some("minor") => AlertSeverity::Minor,
                Some("moderate") => AlertSeverity::Moderate,
                Some("major") | Some("severe") => AlertSeverity::Severe,
                Some("extreme") => AlertSeverity::Extreme,
                _ => AlertSeverity::Unknown,
            };

            let expires = w
                .expiry_time
                .as_ref()
                .and_then(|t| DateTime::parse_from_rfc3339(t).ok())
                .map(|dt| dt.with_timezone(&Utc))
                .unwrap_or(now + chrono::Duration::hours(24));

            if expires < now {
                return None;
            }

            let headline = w
                .short_title
                .clone()
                .unwrap_or_else(|| "Weather Warning".to_string());
            let event = w
                .warning_type
                .as_ref()
                .map(|t| t.replace('_', " "))
                .unwrap_or_else(|| headline.clone());

            Some(AlertEntry {
                alert: Alert {
                    id: w.id.clone(),
                    event,
                    severity,
                    headline,
                    description: String::new(),
                    expires,
                },
                // BOM's warnings endpoint carries no area name.
                area_desc: String::new(),
            })
        })
        .collect()
}

#[cfg(test)]
mod tests {
    use super::*;

    // -----------------------------------------------------------------
    // NWS
    // -----------------------------------------------------------------

    #[test]
    fn nws_decodes_active_alert() {
        let json = r#"{"features":[{"properties":{
            "id":"NWS-IDP-PROD-123",
            "event":"Tornado Warning",
            "severity":"Severe",
            "headline":"Tornado Warning until 8 PM",
            "description":"Take cover now.",
            "sent":"2026-06-01T12:00:00Z",
            "expires":"2099-01-01T00:00:00Z"
        }}]}"#;
        let data: NwsAlertsResponse = serde_json::from_str(json).unwrap();
        let alerts = nws_alerts_from_response(data);

        assert_eq!(alerts.len(), 1);
        let alert = &alerts[0].alert;
        assert_eq!(alert.id, "NWS-IDP-PROD-123");
        assert_eq!(alert.event, "Tornado Warning");
        assert_eq!(alert.severity, AlertSeverity::Severe);
        assert_eq!(alert.headline, "Tornado Warning until 8 PM");
    }

    #[test]
    fn nws_drops_expired_alert() {
        let json = r#"{"features":[{"properties":{
            "id":"NWS-IDP-PROD-124",
            "event":"Winter Storm Warning",
            "severity":"Severe",
            "headline":"Winter Storm Warning",
            "description":"Snow expected.",
            "sent":"2026-06-01T12:00:00Z",
            "expires":"2020-01-01T01:00:00Z"
        }}]}"#;
        let data: NwsAlertsResponse = serde_json::from_str(json).unwrap();
        let alerts = nws_alerts_from_response(data);

        assert!(alerts.is_empty());
    }

    #[test]
    fn nws_null_severity_falls_back_to_unknown() {
        let json = r#"{"features":[{"properties":{
            "id":"NWS-IDP-PROD-125",
            "event":"Special Weather Statement",
            "severity":null,
            "headline":"Special Weather Statement",
            "description":"Details.",
            "sent":"2026-06-01T12:00:00Z",
            "expires":"2099-01-01T00:00:00Z"
        }}]}"#;
        let data: NwsAlertsResponse = serde_json::from_str(json).unwrap();
        let alerts = nws_alerts_from_response(data);

        assert_eq!(alerts.len(), 1);
        assert_eq!(alerts[0].alert.severity, AlertSeverity::Unknown);
    }

    #[test]
    fn nws_null_expires_uses_sent_plus_24h() {
        let json = r#"{"features":[{"properties":{
            "id":"NWS-IDP-PROD-126",
            "event":"Flood Watch",
            "severity":"Moderate",
            "headline":"Flood Watch",
            "description":"Details.",
            "sent":"2099-01-01T00:00:00Z",
            "expires":null
        }}]}"#;
        let data: NwsAlertsResponse = serde_json::from_str(json).unwrap();
        let alerts = nws_alerts_from_response(data);

        assert_eq!(alerts.len(), 1);
    }

    #[test]
    fn nws_null_headline_and_description_default_to_empty() {
        let json = r#"{"features":[{"properties":{
            "id":"NWS-IDP-PROD-127",
            "event":"Wind Advisory",
            "severity":"Minor",
            "headline":null,
            "description":null,
            "sent":"2026-06-01T12:00:00Z",
            "expires":"2099-01-01T00:00:00Z"
        }}]}"#;
        let data: NwsAlertsResponse = serde_json::from_str(json).unwrap();
        let alerts = nws_alerts_from_response(data);

        assert_eq!(alerts.len(), 1);
        assert_eq!(alerts[0].alert.headline, "");
        assert_eq!(alerts[0].alert.description, "");
    }

    // -----------------------------------------------------------------
    // AlertSeverity::from_cap_string
    // -----------------------------------------------------------------

    #[test]
    fn from_cap_string_maps_all_classes() {
        assert_eq!(
            AlertSeverity::from_cap_string("minor"),
            AlertSeverity::Minor
        );
        assert_eq!(
            AlertSeverity::from_cap_string("moderate"),
            AlertSeverity::Moderate
        );
        assert_eq!(
            AlertSeverity::from_cap_string("severe"),
            AlertSeverity::Severe
        );
        assert_eq!(
            AlertSeverity::from_cap_string("major"),
            AlertSeverity::Severe
        );
        assert_eq!(
            AlertSeverity::from_cap_string("extreme"),
            AlertSeverity::Extreme
        );
        assert_eq!(
            AlertSeverity::from_cap_string("not-a-severity"),
            AlertSeverity::Unknown
        );
    }

    // -----------------------------------------------------------------
    // BOM
    // -----------------------------------------------------------------

    #[test]
    fn bom_decodes_active_severe_warning() {
        let json = r#"{"data":[{
            "id":"bom-1",
            "type":"severe_thunderstorm",
            "short_title":"Severe Thunderstorm Warning",
            "warning_group_type":"severe",
            "phase":"active",
            "expiry_time":"2099-01-01T00:00:00Z"
        }]}"#;
        let resp: BomWarningsResponse = serde_json::from_str(json).unwrap();
        let alerts = bom_alerts_from_response(resp.data);

        assert_eq!(alerts.len(), 1);
        let alert = &alerts[0].alert;
        assert_eq!(alert.severity, AlertSeverity::Severe);
        assert_eq!(alert.event, "severe thunderstorm");
        assert_eq!(alert.headline, "Severe Thunderstorm Warning");
    }

    #[test]
    fn bom_major_group_type_maps_to_severe() {
        let json = r#"{"data":[{
            "id":"bom-1b",
            "type":"severe_thunderstorm",
            "short_title":"Severe Thunderstorm Warning",
            "warning_group_type":"major",
            "phase":"active",
            "expiry_time":"2099-01-01T00:00:00Z"
        }]}"#;
        let resp: BomWarningsResponse = serde_json::from_str(json).unwrap();
        let alerts = bom_alerts_from_response(resp.data);

        assert_eq!(alerts.len(), 1);
        assert_eq!(alerts[0].alert.severity, AlertSeverity::Severe);
    }

    #[test]
    fn bom_drops_cancelled_phase() {
        let json = r#"{"data":[{
            "id":"bom-1c",
            "type":"severe_thunderstorm",
            "short_title":"Severe Thunderstorm Warning",
            "warning_group_type":"severe",
            "phase":"cancelled",
            "expiry_time":"2099-01-01T00:00:00Z"
        }]}"#;
        let resp: BomWarningsResponse = serde_json::from_str(json).unwrap();
        let alerts = bom_alerts_from_response(resp.data);

        assert!(alerts.is_empty());
    }

    #[test]
    fn bom_drops_expired_warning() {
        let json = r#"{"data":[{
            "id":"bom-1d",
            "type":"severe_thunderstorm",
            "short_title":"Severe Thunderstorm Warning",
            "warning_group_type":"severe",
            "phase":"active",
            "expiry_time":"2020-01-01T00:00:00Z"
        }]}"#;
        let resp: BomWarningsResponse = serde_json::from_str(json).unwrap();
        let alerts = bom_alerts_from_response(resp.data);

        assert!(alerts.is_empty());
    }

    #[test]
    fn bom_missing_short_title_uses_default_headline() {
        let json = r#"{"data":[{
            "id":"bom-2",
            "type":"flood",
            "short_title":null,
            "warning_group_type":"moderate",
            "phase":"active",
            "expiry_time":"2099-01-01T00:00:00Z"
        }]}"#;
        let resp: BomWarningsResponse = serde_json::from_str(json).unwrap();
        let alerts = bom_alerts_from_response(resp.data);

        assert_eq!(alerts.len(), 1);
        assert_eq!(alerts[0].alert.headline, "Weather Warning");
        assert_eq!(alerts[0].alert.event, "flood");
    }

    #[test]
    fn bom_missing_warning_type_uses_headline_as_event() {
        let json = r#"{"data":[{
            "id":"bom-3",
            "type":null,
            "short_title":"Severe Weather Alert",
            "warning_group_type":"severe",
            "phase":"active",
            "expiry_time":"2099-01-01T00:00:00Z"
        }]}"#;
        let resp: BomWarningsResponse = serde_json::from_str(json).unwrap();
        let alerts = bom_alerts_from_response(resp.data);

        assert_eq!(alerts.len(), 1);
        assert_eq!(alerts[0].alert.event, "Severe Weather Alert");
        assert_eq!(alerts[0].alert.headline, "Severe Weather Alert");
    }

    // -----------------------------------------------------------------
    // MeteoAlarm
    // -----------------------------------------------------------------
    //
    // MeteoAlarm namespace binding (Assumptions Log A1, REVIEWS.md finding 3):
    // this crate's quick-xml 0.37 (features = ["serialize"]) matches serde
    // `rename` targets by LOCAL tag name, ignoring namespace prefixes. A
    // fixture using the real feed's `cap:identifier`, `cap:event`, etc.
    // prefixes decodes identically to an unprefixed fixture -- confirmed by
    // `meteoalarm_entry_decodes_all_fields` below, which uses the prefixed
    // form and asserts every field against its exact expected value (not
    // merely "did not panic"). This is the observed working form; the
    // fixture and test names in this module are written against it.

    #[test]
    fn meteoalarm_entry_decodes_all_fields() {
        let xml = r#"<entry>
            <id>https://feeds.meteoalarm.org/feed/example-entry-1</id>
            <title>Wind Warning for Test Region</title>
            <cap:identifier>2-717000-DE723</cap:identifier>
            <cap:areaDesc>Test Region</cap:areaDesc>
            <cap:event>Wind</cap:event>
            <cap:severity>Severe</cap:severity>
            <cap:sent>2026-06-01T08:00:00Z</cap:sent>
            <cap:expires>2099-01-01T00:00:00Z</cap:expires>
            <cap:geocode>
                <valueName>EMMA_ID</valueName>
                <cap:value>DE723</cap:value>
            </cap:geocode>
        </entry>"#;
        let entry: MeteoAlarmEntry = quick_xml::de::from_str(xml).unwrap();
        let entry = parse_meteoalarm_entry(entry, &None).expect("entry should decode to an alert");
        assert_eq!(entry.area_desc, "Test Region");
        let alert = entry.alert;

        assert_eq!(alert.id, "2-717000-DE723");
        assert_eq!(alert.event, "Wind");
        assert_eq!(alert.severity, AlertSeverity::Severe);
        assert_eq!(alert.headline, "Wind Warning for Test Region");
    }

    #[test]
    fn meteoalarm_entry_matches_user_emma_id() {
        let xml = r#"<entry>
            <id>https://feeds.meteoalarm.org/feed/example-entry-2</id>
            <title>Wind Warning for Test Region</title>
            <cap:identifier>2-717000-DE723</cap:identifier>
            <cap:event>Wind</cap:event>
            <cap:severity>Severe</cap:severity>
            <cap:sent>2026-06-01T08:00:00Z</cap:sent>
            <cap:expires>2099-01-01T00:00:00Z</cap:expires>
            <cap:geocode>
                <valueName>EMMA_ID</valueName>
                <cap:value>DE723</cap:value>
            </cap:geocode>
        </entry>"#;
        let entry: MeteoAlarmEntry = quick_xml::de::from_str(xml).unwrap();
        let alert = parse_meteoalarm_entry(entry, &Some("DE723".to_string()));

        assert!(alert.is_some());
        let alert = alert.unwrap().alert;
        assert_eq!(alert.event, "Wind");
        assert_eq!(alert.severity, AlertSeverity::Severe);
    }

    #[test]
    fn meteoalarm_entry_filters_wrong_emma_id() {
        let xml = r#"<entry>
            <id>https://feeds.meteoalarm.org/feed/example-entry-3</id>
            <title>Wind Warning for Test Region</title>
            <cap:identifier>2-717000-DE723</cap:identifier>
            <cap:event>Wind</cap:event>
            <cap:severity>Severe</cap:severity>
            <cap:sent>2026-06-01T08:00:00Z</cap:sent>
            <cap:expires>2099-01-01T00:00:00Z</cap:expires>
            <cap:geocode>
                <valueName>EMMA_ID</valueName>
                <cap:value>DE723</cap:value>
            </cap:geocode>
        </entry>"#;
        let entry: MeteoAlarmEntry = quick_xml::de::from_str(xml).unwrap();
        let alert = parse_meteoalarm_entry(entry, &Some("DE999".to_string()));

        assert!(alert.is_none());
    }

    #[test]
    fn meteoalarm_entry_drops_expired() {
        let xml = r#"<entry>
            <id>https://feeds.meteoalarm.org/feed/example-entry-4</id>
            <title>Wind Warning for Test Region</title>
            <cap:identifier>2-717000-DE723</cap:identifier>
            <cap:event>Wind</cap:event>
            <cap:severity>Severe</cap:severity>
            <cap:sent>2020-01-01T00:00:00Z</cap:sent>
            <cap:expires>2020-01-01T00:00:00Z</cap:expires>
            <cap:geocode>
                <valueName>EMMA_ID</valueName>
                <cap:value>DE723</cap:value>
            </cap:geocode>
        </entry>"#;
        let entry: MeteoAlarmEntry = quick_xml::de::from_str(xml).unwrap();
        let alert = parse_meteoalarm_entry(entry, &None);

        assert!(alert.is_none());
    }

    #[test]
    fn meteoalarm_feed_decodes_and_maps() {
        let xml = r#"<feed>
            <entry>
                <id>https://feeds.meteoalarm.org/feed/example-entry-future</id>
                <title>Wind Warning for Test Region (future)</title>
                <cap:identifier>2-717000-DE723-future</cap:identifier>
                <cap:event>Wind</cap:event>
                <cap:severity>Severe</cap:severity>
                <cap:sent>2026-06-01T08:00:00Z</cap:sent>
                <cap:expires>2099-01-01T00:00:00Z</cap:expires>
                <cap:geocode>
                    <valueName>EMMA_ID</valueName>
                    <cap:value>DE723</cap:value>
                </cap:geocode>
            </entry>
            <entry>
                <id>https://feeds.meteoalarm.org/feed/example-entry-past</id>
                <title>Wind Warning for Test Region (past)</title>
                <cap:identifier>2-717000-DE723-past</cap:identifier>
                <cap:event>Wind</cap:event>
                <cap:severity>Severe</cap:severity>
                <cap:sent>2020-01-01T00:00:00Z</cap:sent>
                <cap:expires>2020-01-01T00:00:00Z</cap:expires>
                <cap:geocode>
                    <valueName>EMMA_ID</valueName>
                    <cap:value>DE723</cap:value>
                </cap:geocode>
            </entry>
        </feed>"#;
        let feed: MeteoAlarmFeed = quick_xml::de::from_str(xml).unwrap();
        let alerts = meteoalarm_alerts_from_feed(feed, &None, &[], "test").alerts;

        assert_eq!(alerts.len(), 1);
        assert_eq!(alerts[0].alert.id, "2-717000-DE723-future");
    }

    // -----------------------------------------------------------------
    // ECCC
    // -----------------------------------------------------------------
    //
    // Fixtures reuse the exact test square from geo.rs's point_in_polygon_square
    // ("0,0 10,0 10,10 0,10") and its inside point (5.0, 5.0).

    fn eccc_fixture(status: &str, msg_type: &str, sent: &str, identifier: &str) -> String {
        format!(
            r#"<alert>
                <identifier>{identifier}</identifier>
                <status>{status}</status>
                <msgType>{msg_type}</msgType>
                <sent>{sent}</sent>
                <info>
                    <language>en-CA</language>
                    <event>Thunderstorm Warning</event>
                    <severity>Severe</severity>
                    <expires>2099-01-01T00:00:00Z</expires>
                    <headline>Severe Thunderstorm Warning</headline>
                    <description>Severe thunderstorm expected.</description>
                    <area>
                        <areaDesc>Test Region</areaDesc>
                        <polygon>0,0 10,0 10,10 0,10</polygon>
                    </area>
                </info>
            </alert>"#
        )
    }

    #[test]
    fn eccc_decodes_active_alert_in_polygon() {
        let xml = eccc_fixture(
            "Actual",
            "Alert",
            "2026-06-01T08:00:00-04:00",
            "CA-ON-2026-001",
        );
        let mut seen_ids = HashSet::new();
        let alert = parse_eccc_cap(&xml, 5.0, 5.0, &mut seen_ids);

        assert!(alert.is_some());
        let alert = alert.unwrap().alert;
        assert_eq!(alert.event, "Thunderstorm Warning");
        assert_eq!(alert.severity, AlertSeverity::Severe);
        assert_eq!(alert.id, "CA-ON-2026-001");
    }

    #[test]
    fn eccc_rejects_point_outside_polygon() {
        let xml = eccc_fixture(
            "Actual",
            "Alert",
            "2026-06-01T08:00:00-04:00",
            "CA-ON-2026-002",
        );
        let mut seen_ids = HashSet::new();
        let alert = parse_eccc_cap(&xml, 50.0, 50.0, &mut seen_ids);

        assert!(alert.is_none());
    }

    #[test]
    fn eccc_rejects_non_actual_status() {
        let xml = eccc_fixture(
            "Test",
            "Alert",
            "2026-06-01T08:00:00-04:00",
            "CA-ON-2026-003",
        );
        let mut seen_ids = HashSet::new();
        let alert = parse_eccc_cap(&xml, 5.0, 5.0, &mut seen_ids);

        assert!(alert.is_none());
    }

    #[test]
    fn eccc_rejects_cancel_msgtype() {
        let xml = eccc_fixture(
            "Actual",
            "Cancel",
            "2026-06-01T08:00:00-04:00",
            "CA-ON-2026-004",
        );
        let mut seen_ids = HashSet::new();
        let alert = parse_eccc_cap(&xml, 5.0, 5.0, &mut seen_ids);

        assert!(alert.is_none());
    }

    #[test]
    fn eccc_dedups_same_event_and_area() {
        let xml_first = eccc_fixture(
            "Actual",
            "Alert",
            "2026-06-01T08:00:00-04:00",
            "CA-ON-2026-005",
        );
        let xml_second = eccc_fixture(
            "Actual",
            "Alert",
            "2026-06-01T09:00:00-04:00",
            "CA-ON-2026-006",
        );
        let mut seen_ids = HashSet::new();

        let first = parse_eccc_cap(&xml_first, 5.0, 5.0, &mut seen_ids);
        assert!(first.is_some());

        let second = parse_eccc_cap(&xml_second, 5.0, 5.0, &mut seen_ids);
        assert!(second.is_none());
    }

    #[test]
    fn eccc_drops_expired_alert() {
        let xml = r#"<alert>
                <identifier>CA-ON-2026-007</identifier>
                <status>Actual</status>
                <msgType>Alert</msgType>
                <sent>2020-06-01T08:00:00-04:00</sent>
                <info>
                    <language>en-CA</language>
                    <event>Thunderstorm Warning</event>
                    <severity>Severe</severity>
                    <expires>2020-01-01T00:00:00Z</expires>
                    <headline>Severe Thunderstorm Warning</headline>
                    <description>Severe thunderstorm expected.</description>
                    <area>
                        <areaDesc>Test Region</areaDesc>
                        <polygon>0,0 10,0 10,10 0,10</polygon>
                    </area>
                </info>
            </alert>"#
            .to_string();
        let mut seen_ids = HashSet::new();
        let alert = parse_eccc_cap(&xml, 5.0, 5.0, &mut seen_ids);

        assert!(alert.is_none());
    }

    // -----------------------------------------------------------------
    // Region dispatch / routing
    // -----------------------------------------------------------------
    //
    // Only the Region::Unknown arm of fetch_alerts is offline-provable (it
    // returns Ok(vec![]) without touching the network). The Us/Europe/Canada/
    // Australia arms invoke live-HTTP fetch_* functions and remain an
    // accepted, documented coverage gap: no injectable base URL exists in
    // client.rs, and adding one is out of scope per REQUIREMENTS.md. The
    // coordinate->Region routing DECISION that feeds those arms is fully
    // proven below via detect_region -- this proves ROUTING, not live-arm
    // DISPATCH (per REVIEWS.md finding 2).

    #[tokio::test]
    async fn dispatch_unknown_region_returns_empty() {
        // Tokyo -> Region::Unknown (proven in geo.rs's
        // detect_region_unknown_outside_coverage test). This branch touches
        // no network.
        let result = fetch_alerts(35.68, 139.65).await;
        assert!(matches!(result, Ok(alerts) if alerts.is_empty()));
    }

    #[test]
    fn dispatch_routes_coordinates_to_expected_region() {
        // One representative coordinate per provider, reusing geo.rs's
        // existing test coordinates. Each Region maps 1:1 to a fetch_* arm
        // in fetch_alerts (Us -> fetch_nws_alerts, Europe -> fetch_meteoalarm_alerts,
        // Canada -> fetch_eccc_alerts, Australia -> fetch_bom_alerts). The
        // Us/Europe/Canada/Australia arms invoke live-HTTP fetch_* and REMAIN
        // UNCOVERED by this test suite -- this is the accepted, documented
        // gap referenced above and in REVIEWS.md finding 2.
        assert_eq!(detect_region(40.71, -74.01), Region::Us, "New York");
        assert_eq!(detect_region(43.65, -79.38), Region::Canada, "Toronto");
        assert_eq!(detect_region(51.51, -0.13), Region::Europe, "London");
        assert_eq!(detect_region(-33.87, 151.21), Region::Australia, "Sydney");
        assert_eq!(detect_region(35.68, 139.65), Region::Unknown, "Tokyo");
    }

    fn address(city: Option<&str>, county: Option<&str>, state: Option<&str>) -> NominatimAddress {
        NominatimAddress {
            country: Some("Polska".to_string()),
            country_code: Some("pl".to_string()),
            city: city.map(str::to_string),
            town: None,
            village: None,
            municipality: None,
            county: county.map(str::to_string),
            state: state.map(str::to_string),
        }
    }

    fn codenames(pairs: &[(&str, &str)]) -> MeteoAlarmCodenames {
        MeteoAlarmCodenames {
            codes: pairs
                .iter()
                .map(|(id, name)| (id.to_string(), name.to_string()))
                .collect(),
        }
    }

    #[test]
    fn emma_search_terms_are_most_specific_first() {
        let terms = emma_search_terms(&address(
            Some("Warsaw"),
            Some("Warsaw County"),
            Some("Masovian"),
        ));
        assert_eq!(
            terms,
            vec![
                "Warsaw",
                "Stadt Warsaw",
                "Warsaw County",
                "Kreis Warsaw County",
                "Masovian",
            ]
        );
    }

    #[test]
    fn match_emma_id_ignores_other_countries() {
        // A German codename must not match a Polish query, which is the prefix
        // check that the old bounding-box country guess kept getting wrong.
        let codes = codenames(&[("DE123", "Warsaw")]);
        assert_eq!(
            match_emma_id(&address(Some("Warsaw"), None, None), "PL", &codes),
            None
        );
    }

    #[test]
    fn match_emma_id_matches_on_city() {
        let codes = codenames(&[("PL1465", "Warsaw"), ("DE123", "Berlin")]);
        assert_eq!(
            match_emma_id(&address(Some("Warsaw"), None, None), "PL", &codes),
            Some("PL1465".to_string())
        );
    }

    #[test]
    fn match_emma_id_falls_back_to_state() {
        let codes = codenames(&[("PL0100", "Masovian")]);
        assert_eq!(
            match_emma_id(
                &address(Some("Nowhere"), None, Some("Masovian")),
                "PL",
                &codes
            ),
            Some("PL0100".to_string())
        );
    }

    #[test]
    fn match_emma_id_returns_none_when_nothing_matches() {
        let codes = codenames(&[("PL1465", "Warsaw")]);
        assert_eq!(
            match_emma_id(&address(Some("Nowhere"), None, None), "PL", &codes),
            None
        );
    }

    #[test]
    fn emma_search_terms_includes_town() {
        // Nominatim returns `town` instead of `city` for smaller places, so the
        // city-less path has to produce terms too.
        let address = NominatimAddress {
            country: Some("Polska".to_string()),
            country_code: Some("pl".to_string()),
            city: None,
            town: Some("Sopot".to_string()),
            village: None,
            municipality: None,
            county: None,
            state: None,
        };
        assert_eq!(emma_search_terms(&address), vec!["Sopot"]);
    }

    #[test]
    fn match_emma_id_matches_real_local_language_pair() {
        // Regression guard. MeteoAlarm's PL1465 is "Warszawa"; if Nominatim is
        // ever asked for English names it answers "Warsaw", this stops matching,
        // and the whole Polish feed renders unfiltered. Every other fixture here
        // is English on both sides, which is what let that slip through green.
        let codes = codenames(&[("PL1465", "Warszawa")]);
        assert_eq!(
            match_emma_id(&address(Some("Warszawa"), None, None), "PL", &codes),
            Some("PL1465".to_string())
        );
    }

    /// Vienna's real shape in the MeteoAlarm list: the city itself, a
    /// same-prefix neighbour, and the numbered districts. "Wien" matches all of
    /// them, and only AT010 is right.
    fn vienna_codenames() -> MeteoAlarmCodenames {
        let mut pairs = vec![
            ("AT010", "Wien"),
            ("AT304", "Wiener Neustadt (Stadt)"),
            ("AT323", "Wiener Neustadt (Land)"),
        ];
        let districts: Vec<String> = (901..=923).map(|n| format!("AT{n}")).collect();
        for id in &districts {
            pairs.push((id.as_str(), "Wien Innere Stadt"));
        }
        codenames(&pairs)
    }

    fn vienna_address() -> NominatimAddress {
        NominatimAddress {
            country: Some("Österreich".to_string()),
            country_code: Some("at".to_string()),
            city: Some("Wien".to_string()),
            town: None,
            village: None,
            municipality: None,
            county: None,
            state: Some("Wien".to_string()),
        }
    }

    #[test]
    fn match_emma_id_prefers_the_exact_codename_over_longer_ones() {
        assert_eq!(
            match_emma_id(&vienna_address(), "AT", &vienna_codenames()),
            Some("AT010".to_string())
        );
    }

    #[test]
    fn match_emma_id_is_stable_across_hashmap_instances() {
        // Regression guard for the ambiguity itself. `codes` is a HashMap, so a
        // first-hit-wins loop returned a different one of these 26 Austrian
        // codenames per run. A fresh map each round is what a fresh fetch
        // builds, and RandomState reseeds every instance.
        let resolved: std::collections::BTreeSet<String> = (0..200)
            .filter_map(|_| match_emma_id(&vienna_address(), "AT", &vienna_codenames()))
            .collect();
        assert_eq!(
            resolved,
            ["AT010".to_string()].into_iter().collect(),
            "one input must resolve to exactly one EMMA_ID"
        );
    }

    #[test]
    fn match_emma_id_prefers_the_longest_codename_the_term_contains() {
        // Both are real regions containing the search term. "Rhone-Alpes" is the
        // more specific of the two, so a search for "Auvergne-Rhone-Alpes"
        // should not settle for "Rhone".
        let codes = codenames(&[("FR001", "Rhone"), ("FR002", "Rhone-Alpes")]);
        let address = NominatimAddress {
            country: Some("France".to_string()),
            country_code: Some("fr".to_string()),
            city: None,
            town: None,
            village: None,
            municipality: None,
            county: None,
            state: Some("Auvergne-Rhone-Alpes".to_string()),
        };
        assert_eq!(
            match_emma_id(&address, "FR", &codes),
            Some("FR002".to_string())
        );
    }

    #[test]
    fn match_emma_id_ties_break_on_the_lower_id() {
        // Two codenames, same name, same rank. Nothing distinguishes them but
        // the ID, and the answer still has to be the same every run.
        let codes = codenames(&[("PL2000", "Warszawa"), ("PL1465", "Warszawa")]);
        for _ in 0..50 {
            assert_eq!(
                match_emma_id(&address(Some("Warszawa"), None, None), "PL", &codes),
                Some("PL1465".to_string())
            );
        }
    }

    #[test]
    fn match_emma_id_ignores_blank_place_names() {
        // Nominatim can answer with an empty string, and `contains("")` is true
        // for every codename, which would hand back an arbitrary region.
        let codes = codenames(&[("PL1465", "Warszawa")]);
        assert_eq!(
            match_emma_id(&address(Some(""), None, None), "PL", &codes),
            None
        );
    }

    #[test]
    fn match_emma_id_search_term_order_still_wins_over_rank() {
        // The city is checked before the state, so a weak city hit beats a
        // perfect state hit. Ranking is only a tie-break inside one term.
        let codes = codenames(&[("PL1465", "Warszawa Centrum"), ("PL0100", "Masovian")]);
        assert_eq!(
            match_emma_id(
                &address(Some("Warszawa"), None, Some("Masovian")),
                "PL",
                &codes
            ),
            Some("PL1465".to_string())
        );
    }

    #[test]
    fn match_emma_id_matches_when_search_term_contains_codename() {
        // Nominatim's county ("Warsaw County") is longer than the codename
        // ("Warsaw"), so the containment runs the other direction.
        let codes = codenames(&[("PL1465", "Warsaw")]);
        assert_eq!(
            match_emma_id(&address(None, Some("Warsaw County"), None), "PL", &codes),
            Some("PL1465".to_string())
        );
    }

    // -----------------------------------------------------------------
    // area_desc and AlertReport
    // -----------------------------------------------------------------

    #[test]
    fn meteoalarm_entry_without_area_desc_is_empty_string() {
        let xml = r#"<entry>
            <id>https://feeds.meteoalarm.org/feed/example-entry-5</id>
            <title>Wind Warning</title>
            <cap:event>Wind</cap:event>
            <cap:sent>2026-06-01T08:00:00Z</cap:sent>
            <cap:expires>2099-01-01T00:00:00Z</cap:expires>
        </entry>"#;
        let entry: MeteoAlarmEntry = quick_xml::de::from_str(xml).unwrap();
        let entry = parse_meteoalarm_entry(entry, &None).unwrap();

        assert_eq!(entry.area_desc, "");
    }

    /// Two entries: one tagged with a region that is not the user's, one with
    /// no geocode at all. With a filter active both must be dropped; before
    /// the `None` arm existed, the untagged one leaked through.
    fn untagged_feed() -> MeteoAlarmFeed {
        let xml = r#"<feed>
            <entry>
                <id>https://feeds.meteoalarm.org/feed/tagged-elsewhere</id>
                <title>Wind Warning for elsewhere</title>
                <cap:event>Wind</cap:event>
                <cap:severity>Moderate</cap:severity>
                <cap:sent>2026-06-01T08:00:00Z</cap:sent>
                <cap:expires>2099-01-01T00:00:00Z</cap:expires>
                <cap:geocode>
                    <valueName>EMMA_ID</valueName>
                    <cap:value>PL999</cap:value>
                </cap:geocode>
            </entry>
            <entry>
                <id>https://feeds.meteoalarm.org/feed/untagged</id>
                <title>Wind Warning with no geocode</title>
                <cap:event>Wind</cap:event>
                <cap:severity>Moderate</cap:severity>
                <cap:sent>2026-06-01T08:00:00Z</cap:sent>
                <cap:expires>2099-01-01T00:00:00Z</cap:expires>
            </entry>
        </feed>"#;
        quick_xml::de::from_str(xml).unwrap()
    }

    #[test]
    fn meteoalarm_untagged_entry_dropped_when_filter_active() {
        let alerts =
            meteoalarm_alerts_from_feed(untagged_feed(), &Some("PL1465".to_string()), &[], "test")
                .alerts;

        assert!(alerts.is_empty(), "untagged entry leaked past the filter");
    }

    #[test]
    fn meteoalarm_untagged_entry_kept_without_filter() {
        let alerts = meteoalarm_alerts_from_feed(untagged_feed(), &None, &[], "test").alerts;

        assert_eq!(alerts.len(), 2);
    }

    #[test]
    fn nws_decodes_area_desc() {
        let json = r#"{"features":[{"properties":{
            "id":"NWS-IDP-PROD-128",
            "event":"Heat Advisory",
            "severity":"Moderate",
            "headline":"Heat Advisory until 8 PM",
            "description":"Hot.",
            "sent":"2026-06-01T12:00:00Z",
            "expires":"2099-01-01T00:00:00Z",
            "areaDesc":"Coastal Los Angeles County; Los Angeles County Beaches"
        }}]}"#;
        let data: NwsAlertsResponse = serde_json::from_str(json).unwrap();
        let alerts = nws_alerts_from_response(data);

        assert_eq!(
            alerts[0].area_desc,
            "Coastal Los Angeles County; Los Angeles County Beaches"
        );
    }

    #[test]
    fn nws_missing_area_desc_is_empty_string() {
        let json = r#"{"features":[{"properties":{
            "id":"NWS-IDP-PROD-129",
            "event":"Heat Advisory",
            "severity":"Moderate",
            "headline":"Heat Advisory",
            "description":"Hot.",
            "sent":"2026-06-01T12:00:00Z",
            "expires":"2099-01-01T00:00:00Z"
        }}]}"#;
        let data: NwsAlertsResponse = serde_json::from_str(json).unwrap();
        let alerts = nws_alerts_from_response(data);

        assert_eq!(alerts[0].area_desc, "");
    }

    #[test]
    fn eccc_area_desc_is_the_containing_polygon() {
        let xml = eccc_fixture(
            "Actual",
            "Alert",
            "2026-06-01T08:00:00-04:00",
            "CA-ON-2026-008",
        );
        let mut seen_ids = HashSet::new();
        let entry = parse_eccc_cap(&xml, 5.0, 5.0, &mut seen_ids).unwrap();

        assert_eq!(entry.area_desc, "Test Region");
    }

    #[test]
    fn bom_area_desc_is_empty_string() {
        let json = r#"{"data":[{
            "id":"bom-4",
            "type":"flood",
            "short_title":"Flood Warning",
            "warning_group_type":"moderate",
            "phase":"active",
            "expiry_time":"2099-01-01T00:00:00Z"
        }]}"#;
        let resp: BomWarningsResponse = serde_json::from_str(json).unwrap();
        let alerts = bom_alerts_from_response(resp.data);

        assert_eq!(alerts[0].area_desc, "");
    }

    #[tokio::test]
    async fn dispatch_unknown_region_detailed_is_empty_and_filtered() {
        // Same Tokyo coordinate as dispatch_unknown_region_returns_empty.
        let report = fetch_alerts_detailed(35.68, 139.65).await.unwrap();

        assert!(report.alerts.is_empty());
        assert!(report.region_filtered);
    }

    // -----------------------------------------------------------------
    // Feeds that are not EMMA_ID-tagged (France uses NUTS3)
    // -----------------------------------------------------------------

    /// The shape of every entry in the live French feed on 2026-09-02: a NUTS3
    /// geocode, with the EMMA_ID only in a link href that is not parsed.
    fn nuts3_entry(id: &str, nuts3: &str, area: &str) -> String {
        format!(
            r#"<entry>
                <id>https://feeds.meteoalarm.org/feed/{id}</id>
                <cap:geocode>
                    <valueName>NUTS3</valueName>
                    <value>{nuts3}</value>
                </cap:geocode>
                <link title="{area}" href="https://meteoalarm.org?geocode=EMMA_ID:FR031" hreflang="en"/>
                <cap:areaDesc>{area}</cap:areaDesc>
                <cap:event>Yellow Wind Warning</cap:event>
                <cap:severity>Moderate</cap:severity>
                <cap:sent>2026-06-01T08:00:00Z</cap:sent>
                <cap:expires>2099-01-01T00:00:00Z</cap:expires>
            </entry>"#
        )
    }

    #[test]
    fn meteoalarm_nuts3_geocode_is_not_an_emma_id() {
        let entry: MeteoAlarmEntry =
            quick_xml::de::from_str(&nuts3_entry("fr-1", "FR713", "Drôme")).unwrap();

        assert_eq!(entry_emma_id(&entry), None);
        assert_eq!(entry.cap_geocode.unwrap().value.as_deref(), Some("FR713"));
    }

    #[test]
    fn meteoalarm_feed_without_emma_ids_renders_unfiltered() {
        let xml = format!(
            "<feed>{}{}</feed>",
            nuts3_entry("fr-1", "FR713", "Drôme"),
            nuts3_entry("fr-2", "FR813", "Hérault")
        );
        let feed: MeteoAlarmFeed = quick_xml::de::from_str(&xml).unwrap();
        let report = meteoalarm_alerts_from_feed(feed, &Some("FR101".to_string()), &[], "test");

        // The filter cannot apply to a feed that never carries an EMMA_ID, so
        // nothing is dropped and the report says the list is national.
        assert_eq!(report.alerts.len(), 2);
        assert!(!report.region_filtered);
        assert_eq!(report.alerts[0].area_desc, "Drôme");
    }

    #[test]
    fn meteoalarm_mixed_feed_drops_untagged_and_stays_filtered() {
        let xml = format!(
            r#"<feed>
                <entry>
                    <id>https://feeds.meteoalarm.org/feed/tagged-here</id>
                    <cap:event>Wind</cap:event>
                    <cap:sent>2026-06-01T08:00:00Z</cap:sent>
                    <cap:expires>2099-01-01T00:00:00Z</cap:expires>
                    <cap:geocode>
                        <valueName>EMMA_ID</valueName>
                        <value>FR101</value>
                    </cap:geocode>
                </entry>
                {}
            </feed>"#,
            nuts3_entry("fr-3", "FR713", "Drôme")
        );
        let feed: MeteoAlarmFeed = quick_xml::de::from_str(&xml).unwrap();
        let report = meteoalarm_alerts_from_feed(feed, &Some("FR101".to_string()), &[], "test");

        // One entry carries an EMMA_ID, so the feed is filterable: the NUTS3
        // entry is untagged for this purpose and is dropped.
        assert_eq!(report.alerts.len(), 1);
        assert_eq!(
            report.alerts[0].alert.id,
            "https://feeds.meteoalarm.org/feed/tagged-here"
        );
        assert!(report.region_filtered);
    }

    #[test]
    fn meteoalarm_empty_feed_with_filter_is_filtered() {
        let feed: MeteoAlarmFeed = quick_xml::de::from_str("<feed></feed>").unwrap();
        let report = meteoalarm_alerts_from_feed(feed, &Some("PL1465".to_string()), &[], "test");

        assert!(report.alerts.is_empty());
        assert!(report.region_filtered);
    }

    // -----------------------------------------------------------------
    // Stage 2: area names
    // -----------------------------------------------------------------

    fn strings(items: &[&str]) -> Vec<String> {
        items.iter().map(|s| s.to_string()).collect()
    }

    /// Live Portuguese area names, 2026-09-02.
    fn portugal_areas() -> Vec<String> {
        strings(&[
            "Beja",
            "Bragança",
            "Castelo Branco",
            "Coimbra",
            "Faro",
            "Guarda",
            "Leiria",
            "Lisboa",
            "Portalegre",
            "Santarém",
            "Setúbal",
            "Vila Real",
            "Viseu",
            "Évora",
        ])
    }

    /// Live Croatian area names, 2026-09-02.
    fn croatia_areas() -> Vec<String> {
        strings(&[
            "Dubrovnik region",
            "Kvarner i Kvarneric region",
            "Middle Dalmatia region",
            "North Dalmatia region",
            "Osijek region",
            "Rijeka region",
            "South Dalmatia region",
            "Split region",
            "Velebit channel region",
            "West Istrian coast region",
            "Zagreb region",
        ])
    }

    #[test]
    fn area_tokens_folds_diacritics_and_affixes() {
        assert_eq!(area_tokens("Évora"), strings(&["evora"]));
        assert_eq!(area_tokens("Setúbal"), strings(&["setubal"]));
        assert_eq!(area_tokens("Grad Zagreb"), strings(&["zagreb"]));
        assert_eq!(area_tokens("Zagreb region"), strings(&["zagreb"]));
        assert_eq!(
            area_tokens("Brussel-Hoofdstad - Bruxelles-Capitale"),
            strings(&["brussel", "hoofdstad", "bruxelles", "capitale"])
        );
        assert!(area_tokens("Kreis").is_empty());
    }

    #[test]
    fn rank_area_match_exact_beats_tokens() {
        let paris = area_tokens("Paris");
        assert_eq!(
            rank_area_match(&paris, &area_tokens("Paris")),
            Some(AreaMatch::Exact)
        );
        assert_eq!(
            rank_area_match(&paris, &area_tokens("Paris et Petite Ceinture")),
            Some(AreaMatch::Tokens)
        );
        assert!(AreaMatch::Exact > AreaMatch::Tokens);
    }

    #[test]
    fn rank_area_match_requires_an_anchor_token() {
        // "i" appears in "Kvarner i Kvarneric region" but is too short to
        // anchor a match on its own.
        assert_eq!(
            rank_area_match(
                &area_tokens("i"),
                &area_tokens("Kvarner i Kvarneric region")
            ),
            None
        );
        assert_eq!(rank_area_match(&[], &area_tokens("Faro")), None);
    }

    #[test]
    fn rank_area_match_rejects_substrings() {
        assert_eq!(
            rank_area_match(&area_tokens("Seine"), &area_tokens("Seinemaritime")),
            None
        );
    }

    #[test]
    fn match_area_zagreb() {
        let terms = strings(&["Grad Zagreb", "Stadt Grad Zagreb"]);
        assert_eq!(
            match_area(&terms, &croatia_areas()).as_deref(),
            Some("Zagreb region")
        );
    }

    #[test]
    fn match_area_lisboa_exact() {
        let terms = strings(&[
            "Lisboa",
            "Stadt Lisboa",
            "Arroios",
            "Lisboa",
            "Kreis Lisboa",
        ]);
        assert_eq!(
            match_area(&terms, &portugal_areas()).as_deref(),
            Some("Lisboa")
        );
    }

    #[test]
    fn match_area_paris_prefers_exact() {
        let areas = strings(&["Paris", "Paris et Petite Ceinture"]);
        assert_eq!(
            match_area(&strings(&["Paris"]), &areas).as_deref(),
            Some("Paris")
        );
    }

    #[test]
    fn match_area_ambiguous_term_is_a_miss() {
        let areas = strings(&["Seine-Maritime", "Seine-et-Marne", "Hauts-de-Seine"]);
        assert_eq!(match_area(&strings(&["Seine"]), &areas), None);
    }

    #[test]
    fn match_area_greek_script_misses_english_block() {
        // The legacy atom feed's areaDesc is the English transliteration;
        // Nominatim returns Greek script. Same-script matching needs the JSON
        // API's local-language block, which is a separate change.
        let areas = strings(&["Attiki", "Kriti", "Thessalia"]);
        assert_eq!(
            match_area(&strings(&["Αθήνα", "Περιφέρεια Αττικής"]), &areas),
            None
        );
    }

    #[test]
    fn match_area_no_terms_is_a_miss() {
        assert_eq!(match_area(&[], &portugal_areas()), None);
    }

    fn emma_entry(id: &str, emma_id: &str, area: &str) -> String {
        format!(
            r#"<entry>
                <id>https://feeds.meteoalarm.org/feed/{id}</id>
                <cap:geocode>
                    <valueName>EMMA_ID</valueName>
                    <value>{emma_id}</value>
                </cap:geocode>
                <cap:areaDesc>{area}</cap:areaDesc>
                <cap:event>Yellow High Temperature Warning</cap:event>
                <cap:severity>Moderate</cap:severity>
                <cap:sent>2026-06-01T08:00:00Z</cap:sent>
                <cap:expires>2099-01-01T00:00:00Z</cap:expires>
            </entry>"#
        )
    }

    fn portugal_feed() -> MeteoAlarmFeed {
        let xml = format!(
            "<feed>{}{}{}</feed>",
            emma_entry("pt-1", "PT021", "Faro"),
            emma_entry("pt-2", "PT013", "Lisboa"),
            emma_entry("pt-3", "PT015", "Setúbal")
        );
        quick_xml::de::from_str(&xml).unwrap()
    }

    #[test]
    fn portugal_user_in_lisboa_is_filtered_by_area() {
        // Stage 1 cannot resolve a Portuguese EMMA_ID (every codename is
        // "Portugal"), so the feed's own area names decide.
        let terms = strings(&[
            "Lisboa",
            "Stadt Lisboa",
            "Arroios",
            "Lisboa",
            "Kreis Lisboa",
        ]);
        let report = meteoalarm_alerts_from_feed(portugal_feed(), &None, &terms, "Portugal");

        assert_eq!(report.alerts.len(), 1);
        assert_eq!(report.alerts[0].area_desc, "Lisboa");
        assert!(report.region_filtered);
    }

    #[test]
    fn portugal_user_in_porto_renders_national() {
        // Porto is not alerting, so nothing in the feed can be matched to it;
        // the national feed renders and the report says so.
        let report =
            meteoalarm_alerts_from_feed(portugal_feed(), &None, &strings(&["Porto"]), "Portugal");

        assert_eq!(report.alerts.len(), 3);
        assert!(!report.region_filtered);
    }

    #[test]
    fn france_nuts3_feed_filters_by_area() {
        // An EMMA_ID resolved but the feed is NUTS3-tagged, so stage 1 cannot
        // apply; the area name can.
        let xml = format!(
            "<feed>{}{}</feed>",
            nuts3_entry("fr-1", "FR713", "Drôme"),
            nuts3_entry("fr-2", "FR813", "Hérault")
        );
        let feed: MeteoAlarmFeed = quick_xml::de::from_str(&xml).unwrap();
        let terms = strings(&["Valence", "Drôme"]);
        let report =
            meteoalarm_alerts_from_feed(feed, &Some("FR031".to_string()), &terms, "France");

        assert_eq!(report.alerts.len(), 1);
        assert_eq!(report.alerts[0].area_desc, "Drôme");
        assert!(report.region_filtered);
    }

    #[test]
    fn emma_id_quiet_day_stays_filtered_without_stage_two() {
        // Warsaw resolves PL1465 and nothing in the feed is for it: that is a
        // quiet day, not a miss, and stage 2 must not turn it into the
        // national feed.
        let xml = format!(
            "<feed>{}{}</feed>",
            emma_entry("pl-1", "PL999", "Kraków"),
            emma_entry("pl-2", "PL998", "Gdańsk")
        );
        let feed: MeteoAlarmFeed = quick_xml::de::from_str(&xml).unwrap();
        let report = meteoalarm_alerts_from_feed(
            feed,
            &Some("PL1465".to_string()),
            &strings(&["Warszawa"]),
            "Polska",
        );

        assert!(report.alerts.is_empty());
        assert!(report.region_filtered);
    }

    #[test]
    fn emma_search_terms_includes_village_and_municipality() {
        let mut address = address(Some("Lisboa"), Some("Lisboa"), None);
        address.village = Some("Arroios".to_string());
        address.municipality = Some("Lisboa".to_string());
        let terms = emma_search_terms(&address);

        assert_eq!(
            terms,
            vec![
                "Lisboa",
                "Stadt Lisboa",
                "Arroios",
                "Lisboa",
                "Lisboa",
                "Kreis Lisboa",
            ]
        );
    }

    #[test]
    fn cached_codenames_fills_then_reads() {
        // One process-wide value; the network fetch is not exercised here.
        cache_codenames(&codenames(&[("PT021", "Faro")]));
        let hit = cached_codenames().expect("cached after a successful fetch");
        assert_eq!(hit.codes.get("PT021").map(String::as_str), Some("Faro"));
    }

    fn local_areas(pairs: &[(&str, &str)]) -> Vec<LocalArea> {
        pairs
            .iter()
            .map(|(local, english)| LocalArea {
                local: local.to_string(),
                english: english.to_string(),
            })
            .collect()
    }

    /// Live Greek pairs from the v1 JSON feed, 2026-09-02, including the
    /// source's stray tonos on Δωδεκάνησα and its literal `&amp;`.
    fn greece_local_areas() -> Vec<LocalArea> {
        local_areas(&[
            ("Ήπειρο", "Epirus"),
            ("Ανατολική Μακεδονία", "East Makedonia"),
            ("Ανατολική Πελοπόννησο", "East Peloponnisos"),
            ("Ανατολική Στερεά &amp; Έυβοια", "East Sterea &amp; Evvoia"),
            ("Αττική", "Attiki"),
            ("Δυτική Μακεδονία", "West Makedonia"),
            ("Δυτική Πελοπόννησο", "West Peloponnisos"),
            ("Δυτική Στερεά", "West Sterea"),
            ("Δωδεκάνησα΄", "Dodekanisa Islands"),
            ("Θεσσαλία", "Thessalia"),
            ("Θράκη", "Thraki"),
            ("Κεντρική Μακεδονία", "Central Makedonia"),
            ("Κρήτη", "Kriti"),
            ("Κυκλάδες", "Kyklades"),
            (
                "Νησιά Βορειοανατολικού Αιγαίου",
                "North East Aegean Islands",
            ),
            ("Νησιά Ιονίου", "Ionion Islands"),
        ])
    }

    /// Live Bulgarian pairs from the v1 JSON feed, 2026-09-02.
    fn bulgaria_local_areas() -> Vec<LocalArea> {
        local_areas(&[
            ("Благоевград", "Blagoevgrad"),
            ("Бургас", "Burgas"),
            ("Варна", "Varna"),
            ("Велико Търново", "Veliko Tarnovo"),
            ("Видин", "Vidin"),
            ("Враца", "Vratsa"),
            ("Габрово", "Gabrovo"),
            ("Добрич", "Dobrich"),
            ("Кърджали", "Kardzhali"),
            ("Кюстендил", "Kyustendil"),
            ("Ловеч", "Lovech"),
            ("Монтана", "Montana"),
            ("Пазарджик", "Pazardzhik"),
            ("Перник", "Pernik"),
            ("Плевен", "Pleven"),
            ("Пловдив", "Plovdiv"),
            ("Разград", "Razgrad"),
            ("Русе", "Ruse"),
            ("Силистра", "Silistra"),
            ("Сливен", "Sliven"),
            ("Смолян", "Smolyan"),
            ("Софийска област", "Sofia-region"),
            ("София град", "Sofia-city"),
            ("Стара Загора", "Stara Zagora"),
            ("Търговище", "Targovishte"),
            ("Хасково", "Haskovo"),
            ("Шумен", "Shumen"),
            ("Ямбол", "Yambol"),
        ])
    }

    fn local_names(areas: &[LocalArea]) -> Vec<String> {
        areas.iter().map(|a| a.local.clone()).collect()
    }

    /// What `emma_search_terms` builds from Nominatim's Athens reverse
    /// geocode (city, municipality, county, state), 2026-09-02.
    fn athens_terms() -> Vec<String> {
        strings(&[
            "Αθήνα",
            "Stadt Αθήνα",
            "Δήμος Αθηναίων",
            "Περιφερειακή Ενότητα Κεντρικού Τομέα Αθηνών",
            "Kreis Περιφερειακή Ενότητα Κεντρικού Τομέα Αθηνών",
            "Περιφέρεια Αττικής",
        ])
    }

    /// Nominatim's Sofia reverse geocode (city, county, state), 2026-09-02.
    fn sofia_terms() -> Vec<String> {
        strings(&[
            "София",
            "Stadt София",
            "Средец",
            "Kreis Средец",
            "София-град",
        ])
    }

    /// The Greek atom feed as it reaches stage 2: English area names, and
    /// the double-escaped ampersand the source really sends.
    fn greece_report() -> AlertReport {
        let xml = format!(
            "<feed>{}{}{}</feed>",
            emma_entry("gr-1", "GR001", "Attiki"),
            emma_entry("gr-2", "GR002", "Kriti"),
            emma_entry("gr-3", "GR003", "East Sterea &amp;amp; Evvoia")
        );
        let feed: MeteoAlarmFeed = quick_xml::de::from_str(&xml).unwrap();
        let report = meteoalarm_alerts_from_feed(feed, &None, &athens_terms(), "Ελλάς");
        assert!(
            !report.region_filtered,
            "Greek terms cannot match the English block"
        );
        assert_eq!(report.alerts.len(), 3);
        report
    }

    #[test]
    fn is_latin_and_has_non_latin() {
        assert!(!has_non_latin(&strings(&["Évora", "Łódź", "Setúbal"])));
        assert!(has_non_latin(&strings(&["Αθήνα"])));
        assert!(has_non_latin(&strings(&["София"])));
        assert!(has_non_latin(&strings(&["ירושלים"])));
        assert!(has_non_latin(&strings(&["Lisboa", "Αθήνα"])));
        assert!(!has_non_latin(&[]));
    }

    #[test]
    fn area_tokens_drops_greek_and_bulgarian_affixes() {
        assert_eq!(area_tokens("Περιφέρεια Αττικής"), strings(&["αττικης"]));
        assert_eq!(area_tokens("Δήμος Αθηναίων"), strings(&["αθηναιων"]));
        assert_eq!(area_tokens("София град"), strings(&["софия"]));
        // NFD splits й into и plus a breve and the fold drops the breve; both
        // sides fold the same way, so the compare is unaffected.
        assert_eq!(area_tokens("Софийска област"), strings(&["софииска"]));
    }

    #[test]
    fn tokens_equal_genitive() {
        assert!(tokens_equal("αττικη", "αττικης"));
        assert!(tokens_equal("αττικης", "αττικη"));
        assert!(tokens_equal("κρητη", "κρητης"));
        assert!(!tokens_equal("αθηνα", "αθηναιων"));
        assert!(!tokens_equal("paris", "parise"));
        assert!(!tokens_equal("αττι", "αττικη"));
        assert!(!tokens_equal("софия", "софииска"));
    }

    #[test]
    fn match_area_athens_against_local_names() {
        // The first three terms miss (Athens is not a region); the state
        // "Περιφέρεια Αττικής" meets "Αττική" through the affix drop and the
        // genitive allowance.
        assert_eq!(
            match_area(&athens_terms(), &local_names(&greece_local_areas())),
            Some("Αττική".to_string())
        );
    }

    #[test]
    fn match_area_sofia_against_local_names() {
        // "София" fits "София град" on the first term. "Софийска област" does
        // not compete: "софия" is not a prefix of "софииска".
        assert_eq!(
            match_area(&sofia_terms(), &local_names(&bulgaria_local_areas())),
            Some("София град".to_string())
        );
    }

    #[test]
    fn local_areas_from_json_pairs_blocks() {
        // Two Greek warnings sharing a region, one Serbian-shaped warning with
        // two local blocks, and an area with no name in either language.
        let json = r#"{"warnings": [
            {"alert": {"info": [
                {"language": "en-GB", "area": [{"areaDesc": "Attiki"}]},
                {"language": "el-GR", "area": [{"areaDesc": "Αττική"}]}
            ]}},
            {"alert": {"info": [
                {"language": "el-GR", "area": [{"areaDesc": "Κρήτη"}]},
                {"language": "en-GB", "area": [{"areaDesc": "Kriti"}]}
            ]}},
            {"alert": {"info": [
                {"language": "en-GB", "area": [{"areaDesc": "Attiki"}]},
                {"language": "el-GR", "area": [{"areaDesc": "Αττική"}]}
            ]}},
            {"alert": {"info": [
                {"language": "sr-Latn", "area": [{"areaDesc": "Beograd"}]},
                {"language": "sr", "area": [{"areaDesc": "Београд"}]},
                {"language": "en-GB", "area": [{"areaDesc": "Belgrade"}]}
            ]}},
            {"alert": {"info": [
                {"language": "en-GB", "area": [{}]},
                {"language": "el-GR", "area": [{"areaDesc": ""}]}
            ]}},
            {"alert": {}}
        ]}"#;
        let feed: MeteoAlarmJsonFeed = serde_json::from_str(json).unwrap();

        assert_eq!(
            local_areas_from_json(feed),
            local_areas(&[
                ("Beograd", "Belgrade"),
                ("Αττική", "Attiki"),
                ("Κρήτη", "Kriti"),
                ("Београд", "Belgrade"),
            ])
        );
    }

    #[test]
    fn apply_local_area_match_filters_by_english_name() {
        let report = apply_local_area_match(
            greece_report(),
            &athens_terms(),
            &greece_local_areas(),
            "Ελλάς",
        );

        assert_eq!(report.alerts.len(), 1);
        assert_eq!(report.alerts[0].area_desc, "Attiki");
        assert!(report.region_filtered);
    }

    #[test]
    fn apply_local_area_match_compares_parsed_area_desc_raw() {
        // The atom source double-escapes the ampersand and quick_xml unescapes
        // one level, so the parsed entry equals the JSON English name byte for
        // byte. Terms that pick the Sterea region keep only that entry.
        let terms = strings(&["Ανατολική Στερεά"]);
        let report =
            apply_local_area_match(greece_report(), &terms, &greece_local_areas(), "Ελλάς");

        assert_eq!(report.alerts.len(), 1);
        assert_eq!(report.alerts[0].area_desc, "East Sterea &amp; Evvoia");
        assert!(report.region_filtered);
    }

    #[test]
    fn apply_local_area_match_keeps_city_not_region() {
        // "Sofia-city" and "Sofia-region" fold to the same tokens once the
        // affixes drop; the raw compare keeps them apart.
        let xml = format!(
            "<feed>{}{}{}</feed>",
            nuts3_entry("bg-1", "BG411", "Sofia-city"),
            nuts3_entry("bg-2", "BG412", "Sofia-region"),
            nuts3_entry("bg-3", "BG413", "Blagoevgrad")
        );
        let feed: MeteoAlarmFeed = quick_xml::de::from_str(&xml).unwrap();
        let report = meteoalarm_alerts_from_feed(feed, &None, &sofia_terms(), "България");
        assert!(!report.region_filtered);

        let report =
            apply_local_area_match(report, &sofia_terms(), &bulgaria_local_areas(), "България");

        assert_eq!(report.alerts.len(), 1);
        assert_eq!(report.alerts[0].area_desc, "Sofia-city");
        assert!(report.region_filtered);
    }

    #[test]
    fn apply_local_area_match_miss_leaves_report() {
        let terms = strings(&["Θεσσαλονίκη"]);
        let report =
            apply_local_area_match(greece_report(), &terms, &greece_local_areas(), "Ελλάς");

        assert_eq!(report.alerts.len(), 3);
        assert!(!report.region_filtered);
    }

    #[test]
    fn apply_local_area_match_skips_latin_only_inventory() {
        // Israel's he-IL block repeats the English names, so Hebrew terms can
        // never match; the report passes through untouched.
        let israel = local_areas(&[
            ("Judea Mountains", "Judea Mountains"),
            ("Gush Dan", "Gush Dan"),
        ]);
        let terms = strings(&["ירושלים", "מחוז ירושלים"]);
        let report = apply_local_area_match(greece_report(), &terms, &israel, "ישראל");

        assert_eq!(report.alerts.len(), 3);
        assert!(!report.region_filtered);
    }
}