File size: 72,491 Bytes
d15f07c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
FastAPI application for the CommunityOne Open Navigator system.

Provides REST API endpoints for:
- Initiating policy analysis workflows
- Querying advocacy opportunities
- Retrieving generated materials
- Accessing visualizations
- System status and monitoring
"""
from typing import List, Dict, Any, Optional
from datetime import datetime, date
import sys
import time
from pathlib import Path
from fastapi import FastAPI, HTTPException, Query, BackgroundTasks, Request, Response
from fastapi.responses import HTMLResponse, JSONResponse
from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware.gzip import GZipMiddleware
from fastapi.staticfiles import StaticFiles
from fastapi.openapi.docs import get_swagger_ui_html
from api.static_cache import CachedStaticFiles
from pydantic import BaseModel, Field
from loguru import logger
import os

from agents.orchestrator import OrchestratorAgent
from agents.scraper import ScraperAgent
from agents.parser import ParserAgent
from agents.classifier import ClassifierAgent
from agents.sentiment import SentimentAnalyzerAgent
from agents.advocacy import AdvocacyWriterAgent
from ingestion.delta_lake import DeltaLakePipeline
from scripts.visualization.heatmap import AdvocacyHeatmap
from config import settings

# Configure logging with rotation and retention
# Output to both file (with rotation) and stderr (for HuggingFace container logs)
logger.remove()  # Remove default handler

# Add console output (shows in HuggingFace container logs)
logger.add(
    sys.stderr,
    format="<green>{time:YYYY-MM-DD HH:mm:ss}</green> | <level>{level: <8}</level> | <cyan>{name}</cyan>:<cyan>{function}</cyan> - <level>{message}</level>",
    level=settings.log_level
)

# Add file output with rotation and retention
logger.add(
    settings.log_file,
    rotation="500 MB",      # Create new file when size exceeds 500MB
    retention="10 days",    # Delete logs older than 10 days
    level=settings.log_level,
    format="{time:YYYY-MM-DD HH:mm:ss} | {level: <8} | {name}:{function} - {message}"
)

# Initialize FastAPI app
app = FastAPI(
    title="Open Navigator API",
    description="Multi-agent system for analyzing local government oral health policy discussions",
    version="1.0.0",
    docs_url=None,  # Disable default docs to use custom
    redoc_url="/redoc",  # Keep ReDoc at /redoc
    openapi_tags=[
        {
            "name": "auth",
            "description": "Authentication and user management"
        },
        {
            "name": "social",
            "description": "Social features - follow users, leaders, organizations, and causes"
        },
        {
            "name": "workflows",
            "description": "Policy analysis workflows"
        },
        {
            "name": "opportunities",
            "description": "Advocacy opportunities"
        }
    ]
)

# Custom OpenAPI schema with logo
def custom_openapi():
    if app.openapi_schema:
        return app.openapi_schema
    
    from fastapi.openapi.utils import get_openapi
    
    openapi_schema = get_openapi(
        title=app.title,
        version=app.version,
        description=app.description,
        routes=app.routes,
    )
    
    # Add custom logo
    openapi_schema["info"]["x-logo"] = {
        "url": "/static/communityone_logo.svg",
        "altText": "CommunityOne Logo"
    }
    
    app.openapi_schema = openapi_schema
    return app.openapi_schema

app.openapi = custom_openapi

# Bootstrap OpenTelemetry: instrument the app at startup and configure the
# exporter (OTLP collector if OTEL_EXPORTER_OTLP_ENDPOINT is set, else a console
# exporter for dev). Idempotent. Spans for the search DB path are opened in
# api/routes/search*.py via the shared `tracer`.
from api.telemetry import setup_telemetry

setup_telemetry(app)

# Add CORS middleware. Origins come from an explicit env-driven allowlist
# (api/origins.py), never "*": with allow_credentials=True, Starlette reflects
# the caller's Origin, so "*" would trust every site on the internet.
from api.origins import allowed_origins

app.add_middleware(
    CORSMiddleware,
    allow_origins=list(allowed_origins()),
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Compress responses (notably the large /data JSON marts β€” county_metrics is
# ~2.6MB, jurisdiction_mapping_quality ~6.6MB; both compress ~5-10x).
app.add_middleware(GZipMiddleware, minimum_size=1000)

# Request logging middleware
@app.middleware("http")
async def log_requests(request: Request, call_next):
    """Log all API requests with timing and response info"""
    start_time = time.time()
    
    # Get client info
    client_host = request.client.host if request.client else "unknown"
    
    # Log incoming request
    logger.info(f"➑️  {request.method} {request.url.path} - Client: {client_host}")
    
    # Process request
    try:
        response = await call_next(request)
        
        # Calculate duration
        duration_ms = (time.time() - start_time) * 1000
        
        # Get response size if available
        response_size = response.headers.get("content-length", "unknown")
        
        # Log response with appropriate emoji based on status
        if response.status_code < 400:
            logger.info(
                f"βœ… {request.method} {request.url.path} - "
                f"Status: {response.status_code} - "
                f"Duration: {duration_ms:.2f}ms - "
                f"Size: {response_size} bytes"
            )
        elif response.status_code < 500:
            logger.warning(
                f"⚠️  {request.method} {request.url.path} - "
                f"Status: {response.status_code} - "
                f"Duration: {duration_ms:.2f}ms"
            )
        else:
            logger.error(
                f"❌ {request.method} {request.url.path} - "
                f"Status: {response.status_code} - "
                f"Duration: {duration_ms:.2f}ms"
            )
        
        return response
        
    except Exception as e:
        duration_ms = (time.time() - start_time) * 1000

        # A client that disconnects mid-flight (e.g. the frontend's
        # AbortController timing out a slow request) cancels the downstream
        # task, so Starlette's BaseHTTPMiddleware reports
        # "No response returned." That's a normal client abort, not a server
        # fault β€” log it quietly and return 499 (Client Closed Request) instead
        # of re-raising a 500 with a noisy traceback.
        if (
            isinstance(e, RuntimeError)
            and str(e) == "No response returned."
            and await request.is_disconnected()
        ):
            logger.info(
                f"🚫 {request.method} {request.url.path} - "
                f"Client disconnected - Duration: {duration_ms:.2f}ms"
            )
            return Response(status_code=499)

        logger.error(
            f"πŸ’₯ {request.method} {request.url.path} - "
            f"Error: {str(e)} - "
            f"Duration: {duration_ms:.2f}ms"
        )
        raise

# Mount static files for logo
static_dir = os.path.join(os.path.dirname(os.path.dirname(__file__)), "web_app", "public")
if os.path.exists(static_dir):
    app.mount("/static", StaticFiles(directory=static_dir), name="static")
    # Serve the whole public /data tree the way Vite does in dev. Besides the
    # census-map marts this covers the per-state ZCTA (ZIP) tiles under
    # /data/zctas (the lowest drilldown tier) and the jurisdiction-quality
    # snapshot β€” mounting only /data/census-map left those paths 404ing.
    data_dir = Path(static_dir) / "data"
    if data_dir.is_dir():
        app.mount("/data", CachedStaticFiles(directory=data_dir), name="public_data")
    else:
        logger.warning(f"Public data bundle missing (expected {data_dir})")
else:
    logger.warning(f"Static directory not found: {static_dir}")

# Serve favicon at root
@app.get("/favicon.ico", include_in_schema=False)
async def favicon():
    """Serve favicon β€” HF deploy strips binary assets, so fall back to PNG/SVG."""
    from fastapi.responses import FileResponse

    candidates = [
        (Path(__file__).parent / "static" / "favicon.ico", "image/x-icon"),
        (Path(static_dir) / "favicon.ico", "image/x-icon"),
        (Path(__file__).parent / "static" / "communityone_logo_64.png", "image/png"),
        (Path(static_dir) / "communityone_logo_64.png", "image/png"),
        (Path(__file__).parent / "static" / "communityone_logo.svg", "image/svg+xml"),
        (Path(static_dir) / "communityone_logo.svg", "image/svg+xml"),
    ]
    for path, media_type in candidates:
        if path.exists():
            return FileResponse(path, media_type=media_type)
    raise HTTPException(status_code=404, detail="Favicon not found")


# Custom Exception Handlers for better error messages
from fastapi.exceptions import RequestValidationError
from starlette.exceptions import HTTPException as StarletteHTTPException
from api.error_pages import error_response

@app.exception_handler(StarletteHTTPException)
async def http_exception_handler(request: Request, exc: StarletteHTTPException):
    """Handle HTTP exceptions with user-friendly, content-negotiated messages."""
    if exc.status_code == 404:
        return error_response(
            request,
            status_code=404,
            title="Page not found",
            message=f"We couldn't find '{request.url.path}'.",
            suggestion="Check the link and try again, or head back to the homepage.",
            extra={"documentation": "/api/docs"},
        )
    elif exc.status_code == 401:
        return error_response(
            request,
            status_code=401,
            title="Sign-in required",
            message=exc.detail or "You need to be signed in to access this.",
            suggestion="Please sign in and try again.",
            extra={"login": "/api/auth/login/google"},
        )
    elif exc.status_code == 403:
        return error_response(
            request,
            status_code=403,
            title="Access denied",
            message=exc.detail or "You don't have permission to access this.",
            suggestion="Contact support if you believe this is a mistake.",
        )
    elif exc.status_code == 503:
        return error_response(
            request,
            status_code=503,
            title="Temporarily unavailable",
            message=exc.detail or "This service is temporarily unavailable.",
            suggestion="Please try again in a few minutes.",
        )
    else:
        return error_response(
            request,
            status_code=exc.status_code,
            title=str(exc.detail) if exc.detail else "Something went wrong",
            message=str(exc.detail) if exc.detail else "An error occurred while processing your request.",
        )

@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError):
    """Handle validation errors with detailed, user-friendly messages"""
    errors = []
    for error in exc.errors():
        field = " -> ".join(str(loc) for loc in error["loc"])
        errors.append({
            "field": field,
            "message": error["msg"],
            "type": error["type"]
        })

    return error_response(
        request,
        status_code=422,
        title="Validation Error",
        message="The request data is invalid. Please check the fields and try again.",
        suggestion="Review the error details and correct the invalid fields.",
        extra={"errors": errors, "documentation": "/api/docs"},
    )

@app.exception_handler(500)
async def internal_server_error_handler(request: Request, exc: Exception):
    """Handle internal server errors with a generic message (hide details from users)."""
    logger.error(f"Internal server error on {request.url.path}: {exc}")
    return error_response(
        request,
        status_code=500,
        title="Something went wrong",
        message="Something went wrong on our end. We've been notified and are working to fix it.",
        suggestion="Please try again in a little while. If it keeps happening, email support and we'll help.",
    )


# Include authentication routes
from api.routes import auth as auth_routes
from api.routes import social as social_routes
from api.routes import search as search_routes
from api.routes import people as people_routes
from api.routes import decisions as decisions_routes
from api.routes import policy_questions as policy_questions_routes
from api.routes import documents as documents_routes
from api.routes import jurisdiction_documents as jurisdiction_documents_routes
from api.routes import jurisdiction_meeting_documents as jurisdiction_meeting_documents_routes
from api.routes import governing_bodies as governing_bodies_routes
from api.routes import event_bills as event_bills_routes
from api.routes import meetings as meetings_routes
from api.routes import meeting_comparison as meeting_comparison_routes
# Use Neon database for fast stats queries (500x faster than parquet)
from api.routes import stats_neon as stats_routes  # Was: stats
from api.routes import contact as contact_routes
from api.routes import chat_meetings as chat_meetings_routes
from api.routes import stance as stance_routes
# Use hybrid approach for bills: Neon for map, parquet for drill-down (saves space)
from api.routes import bills_neon as bills_routes  # Was: bills
from api.routes import data_deletion as data_deletion_routes
from api.routes import trending as trending_routes
from api.routes import lighthouse_reports as lighthouse_reports_routes
from api.routes import jurisdiction_mapping as jurisdiction_mapping_routes
from api.routes import batch_jobs as batch_jobs_routes
from api.routes import deployments as deployments_routes
from api.routes import locations as locations_routes
from api.routes import addresses as addresses_routes
from api.routes import geocode as geocode_routes
from api.routes import cpi as cpi_routes
from api.routes import grants as grants_routes
from api.routes import efile990 as efile990_routes
from api.routes import lenses as lenses_routes
from api.routes import money_flow as money_flow_routes
from api.routes import topics as topics_routes
from api.routes import seo as seo_routes
from api.routes import short_term_rentals as short_term_rentals_routes
from api.routes import topic_companies as topic_companies_routes
from api.routes import topic_timeline as topic_timeline_routes
from api.routes import topic_yoy as topic_yoy_routes
from api.routes import rankings as rankings_routes
from api.routes import topic_policy as topic_policy_routes
from api.routes import topic_upcoming as topic_upcoming_routes
from api.routes import topic_organizations as topic_organizations_routes
from api.routes import topic_outcomes as topic_outcomes_routes
from api.routes import topic_caption_facts as topic_caption_facts_routes
from api.routes import organizations as organizations_routes
from api.routes import money_and_talk as money_and_talk_routes
from api.routes import grandkid_outlook as grandkid_outlook_routes
from api.routes import local_finance as local_finance_routes
from api.routes import benchmark as benchmark_routes
from api.routes import browse as browse_routes
from api.routes import decision_browse as decision_browse_routes
from api.routes import meeting_browse as meeting_browse_routes
from api.routes import feed as feed_routes
from api.routes import alerts as alerts_routes
from api.routes import data_centers as data_centers_routes
from api.routes import data_center_comments as data_center_comments_routes
from api.routes import data_center_drill as data_center_drill_routes
from api.database import init_db

app.include_router(auth_routes.router, prefix="/api")
app.include_router(social_routes.router, prefix="/api")
app.include_router(search_routes.router, prefix="/api")
app.include_router(people_routes.router, prefix="/api")
app.include_router(decisions_routes.router, prefix="/api")
app.include_router(policy_questions_routes.router, prefix="/api")
app.include_router(jurisdiction_documents_routes.router, prefix="/api")
app.include_router(jurisdiction_meeting_documents_routes.router, prefix="/api")
app.include_router(governing_bodies_routes.router, prefix="/api")
app.include_router(documents_routes.router, prefix="/api")
app.include_router(event_bills_routes.router, prefix="/api")
app.include_router(meetings_routes.router, prefix="/api")
app.include_router(meeting_comparison_routes.router, prefix="/api")
app.include_router(stats_routes.router, prefix="/api", tags=["stats"])
app.include_router(contact_routes.router, prefix="/api")
app.include_router(chat_meetings_routes.router, prefix="/api")
app.include_router(stance_routes.router, prefix="/api")
app.include_router(bills_routes.router, prefix="/api")
app.include_router(data_deletion_routes.router, prefix="/api", tags=["privacy"])
app.include_router(trending_routes.router)
app.include_router(lighthouse_reports_routes.router, prefix="/api")
app.include_router(jurisdiction_mapping_routes.router, prefix="/api")
app.include_router(batch_jobs_routes.router, prefix="/api")
app.include_router(deployments_routes.router, prefix="/api")
app.include_router(locations_routes.router, prefix="/api")
app.include_router(addresses_routes.router, prefix="/api")
app.include_router(geocode_routes.router, prefix="/api")
app.include_router(cpi_routes.router, prefix="/api", tags=["cpi"])
app.include_router(grants_routes.router, prefix="/api")
app.include_router(efile990_routes.router, prefix="/api")
# Prefix ("/api/lenses") is baked into the router β€” include with NO extra prefix
# (mirrors how trending_routes is registered).
app.include_router(lenses_routes.router)
# Prefix ("/api/money-flow") baked into the router β€” include with NO extra prefix.
app.include_router(money_flow_routes.router)
# Prefix ("/api/topics") baked into the router β€” include with NO extra prefix.
app.include_router(topics_routes.router)
# Sitemaps + the server-rendered SPA shell with per-route <head> meta (#1430); registered before the catch-all.
app.include_router(seo_routes.router)
# Prefix ("/api/short-term-rentals") baked into the router (#1015).
app.include_router(short_term_rentals_routes.router)
app.include_router(topic_companies_routes.router)
# Topic timeline + period dumbbell (#1140); prefix /api/topics baked in.
app.include_router(topic_timeline_routes.router)
# Every main topic, last year vs this year (#1343); prefix /api/topics baked in.
app.include_router(topic_yoy_routes.router)
# Where places stand on a topic (#1437); prefix /api/rankings baked in.
app.include_router(rankings_routes.router)
# State bills, local actions and public positions on a topic (#1274); prefix /api/topics baked in.
app.include_router(topic_policy_routes.router)
app.include_router(topic_upcoming_routes.router)
# The nonprofits tied to a topic, ranked by evidence (#1345).
app.include_router(topic_organizations_routes.router)
app.include_router(topic_outcomes_routes.router)
# Prefix ("/api/topics") baked into the router (#1125): the facts behind a topic caption.
app.include_router(topic_caption_facts_routes.router)
# Prefix ("/api/organizations") baked into the router (#1015): the organization page.
app.include_router(organizations_routes.router)
# Prefix ("/api/money-and-talk") baked into the router β€” include with NO extra prefix.
app.include_router(money_and_talk_routes.router)
# Prefix ("/api/grandkid-outlook") baked into the router β€” include with NO extra prefix.
app.include_router(grandkid_outlook_routes.router)
# Prefix ("/api/local-finance") baked into the router β€” include with NO extra prefix.
app.include_router(local_finance_routes.router)
app.include_router(benchmark_routes.router)
# Prefix ("/api/browse") baked into the router β€” include with NO extra prefix.
app.include_router(browse_routes.router)
# Flat decision-browse list. Router prefix is "/decisions"; add the shared "/api"
# prefix the other routers use (distinct from decisions_routes' "/decision" detail).
app.include_router(decision_browse_routes.router, prefix="/api")
# Flat meeting-browse list. Router prefix is "/meetings"; add the shared "/api"
# prefix (meeting-grain analogue of decision_browse_routes).
app.include_router(meeting_browse_routes.router, prefix="/api")
app.include_router(alerts_routes.router, prefix="/api")
app.include_router(feed_routes.router, prefix="/api")
# Data-center job claims by phase (#246). Router prefix is "/data-centers".
app.include_router(data_centers_routes.router, prefix="/api")
app.include_router(data_center_comments_routes.router, prefix="/api")
app.include_router(data_center_drill_routes.router, prefix="/api")
# Data center sites over time and recording coverage (#1348).
from api.routes import data_center_sites_timeline as data_center_sites_timeline_routes
from api.routes import recorded_coverage as recorded_coverage_routes

app.include_router(data_center_sites_timeline_routes.router, prefix="/api")
app.include_router(recorded_coverage_routes.router, prefix="/api")
# Data-center job-application links (#248): public list + admin screen.
from api.routes import application_links as application_links_routes

app.include_router(application_links_routes.public_router, prefix="/api")
app.include_router(application_links_routes.admin_router, prefix="/api")
# Jev meeting-kind review / override (#668).
from api.routes import meeting_kind_reviews as meeting_kind_reviews_routes

app.include_router(meeting_kind_reviews_routes.admin_router, prefix="/api")
# Official profile claims + pending edits (#1062). Router prefix is "/people".
from api.routes import person_claims as person_claims_routes

app.include_router(person_claims_routes.router, prefix="/api")

# Custom Swagger UI with logo.
# Served at /api/docs (not /docs) so the /docs/ path is free for the Docusaurus
# documentation bundle in single-process deployments (Databricks Apps) and to
# match the HuggingFace layout where nginx owns /docs/. ReDoc stays at /redoc.
@app.get("/api/docs", include_in_schema=False)
async def custom_swagger_ui_html():
    """Custom Swagger UI with CommunityOne logo"""
    return get_swagger_ui_html(
        openapi_url=app.openapi_url,
        title=f"{app.title} - API Documentation",
        swagger_favicon_url="/static/communityone_logo_64.png",
        swagger_ui_parameters={
            "defaultModelsExpandDepth": -1,
            "docExpansion": "list",
            "filter": True,
            "syntaxHighlight.theme": "monokai"
        }
    )

# Initialize database on startup
@app.on_event("startup")
async def init_database():
    """Initialize authentication database"""
    try:
        init_db()
        logger.info("βœ… Authentication database initialized")
    except Exception as e:
        logger.warning(f"⚠️  Database initialization skipped: {e}")

# Initialize components
orchestrator = OrchestratorAgent()
pipeline = DeltaLakePipeline()
heatmap_generator = AdvocacyHeatmap()


# Pydantic models for API
class ScrapeTarget(BaseModel):
    """Configuration for a scraping target."""
    url: str
    municipality: str
    state: str
    platform: str = "generic"


class WorkflowRequest(BaseModel):
    """Request to start a new analysis workflow."""
    scrape_targets: List[ScrapeTarget]
    date_range: Optional[Dict[str, str]] = None
    description: Optional[str] = None


class WorkflowResponse(BaseModel):
    """Response for workflow operations."""
    workflow_id: str
    status: str
    message: str


class OpportunityFilter(BaseModel):
    """Filters for querying opportunities."""
    state: Optional[str] = None
    municipality: Optional[str] = None
    topic: Optional[str] = None
    urgency: Optional[str] = None
    min_date: Optional[date] = None
    max_date: Optional[date] = None


class OpportunityResponse(BaseModel):
    """Response containing advocacy opportunities."""
    opportunities: List[Dict[str, Any]]
    total_count: int
    filters_applied: Dict[str, Any]


class SystemStatus(BaseModel):
    """System status information."""
    status: str
    active_workflows: int
    agent_status: Dict[str, Any]
    last_update: datetime


class StatesResponse(BaseModel):
    """Response containing US state codes with active opportunities."""
    states: List[str] = Field(..., description="List of 2-letter US state codes")
    count: int = Field(..., description="Total count of states")


# API Endpoints

@app.get("/", response_class=HTMLResponse)
async def root(request: Request):
    """Root endpoint.

    Single-process deployments (Databricks Apps) have no nginx in front to serve
    the built React SPA, so when the Vite build is present (``api/static/index.html``)
    we serve it here. Without a build (e.g. an API-only container) we fall back to
    the informational API landing page below.
    """
    spa_index = Path(__file__).parent / "static" / "index.html"
    if spa_index.is_file():
        # The home page's own <head> meta (#1430), the same shell every SPA path gets.
        return await seo_routes.spa_response(spa_index, str(request.url.path) + (f"?{request.url.query}" if request.url.query else ""))
    html_content = """
    <!DOCTYPE html>
    <html>
        <head>
            <title>Open Navigator API</title>
            <style>
                body { 
                    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
                    max-width: 900px; 
                    margin: 50px auto; 
                    padding: 20px;
                    line-height: 1.6;
                }
                .header {
                    display: flex;
                    align-items: center;
                    gap: 20px;
                    margin-bottom: 30px;
                    border-bottom: 2px solid #1976d2;
                    padding-bottom: 20px;
                }
                .logo {
                    width: 80px;
                    height: 80px;
                }
                h1 { 
                    color: #1976d2;
                    margin: 0;
                }
                .tagline {
                    color: #666;
                    font-size: 1.1em;
                }
                .endpoint { 
                    background: linear-gradient(135deg, #f5f5f5 0%, #e8f4f8 100%);
                    padding: 15px;
                    margin: 10px 0;
                    border-radius: 8px;
                    border-left: 4px solid #1976d2;
                }
                .endpoint strong {
                    color: #1976d2;
                }
                code { 
                    background: #e0e0e0;
                    padding: 3px 8px;
                    border-radius: 4px;
                    font-family: 'Courier New', monospace;
                }
                .docs-link {
                    display: inline-block;
                    background: #1976d2;
                    color: white;
                    padding: 12px 24px;
                    text-decoration: none;
                    border-radius: 6px;
                    margin-top: 20px;
                    transition: background 0.3s;
                }
                .docs-link:hover {
                    background: #1565c0;
                }
            </style>
        </head>
        <body>
            <div class="header">
                <img src="/static/communityone_logo.svg" alt="CommunityOne Logo" class="logo">
                <div>
                    <h1>Open Navigator API</h1>
                    <p class="tagline">CommunityOne: The open path to everything local</p>
                </div>
            </div>
            
            <h2>πŸ”‘ Key Endpoints:</h2>
            <div class="endpoint">
                <strong>POST /workflow/start</strong> - Start a new analysis workflow
            </div>
            <div class="endpoint">
                <strong>GET /opportunities</strong> - Query advocacy opportunities
            </div>
            <div class="endpoint">
                <strong>GET /heatmap</strong> - Get advocacy heatmap visualization
            </div>
            <div class="endpoint">
                <strong>GET /status</strong> - System status and health
            </div>
            <div class="endpoint">
                <strong>POST /auth/login/{provider}</strong> - OAuth login (HuggingFace, Google, Facebook, GitHub)
            </div>
            
            <a href="/api/docs" class="docs-link">πŸ“š View Full API Documentation</a>
        </body>
    </html>
    """
    return HTMLResponse(content=html_content)


@app.post("/workflow/start", response_model=WorkflowResponse)
async def start_workflow(
    request: WorkflowRequest,
    background_tasks: BackgroundTasks
):
    """
    Start a new policy analysis workflow.
    
    This initiates the full multi-agent pipeline:
    1. Scrape meeting minutes from specified sources
    2. Parse and structure the data
    3. Classify by oral health topics
    4. Analyze sentiment and policy stance
    5. Generate advocacy materials
    """
    try:
        # Register agents with orchestrator
        orchestrator.register_agent(ScraperAgent())
        orchestrator.register_agent(ParserAgent())
        orchestrator.register_agent(ClassifierAgent())
        orchestrator.register_agent(SentimentAnalyzerAgent())
        orchestrator.register_agent(AdvocacyWriterAgent())
        
        # Convert targets to dict format
        targets = [target.dict() for target in request.scrape_targets]
        
        # Start workflow in background
        background_tasks.add_task(
            orchestrator.execute_pipeline,
            targets,
            request.date_range
        )
        
        return WorkflowResponse(
            workflow_id="wf-" + datetime.utcnow().strftime("%Y%m%d-%H%M%S"),
            status="started",
            message=f"Workflow started with {len(targets)} targets"
        )
        
    except Exception as e:
        logger.error(f"Error starting workflow: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@app.get("/workflow/{workflow_id}/status")
async def get_workflow_status(workflow_id: str):
    """Get the status of a specific workflow."""
    # Query workflow status from orchestrator
    # This is a placeholder - would query actual workflow state
    return {
        "workflow_id": workflow_id,
        "status": "running",
        "stage": "classification",
        "progress": 0.6
    }


@app.get("/opportunities", response_model=OpportunityResponse)
async def get_opportunities(
    state: Optional[str] = Query(None, description="Filter by state code"),
    municipality: Optional[str] = Query(None, description="Filter by municipality"),
    topic: Optional[str] = Query(None, description="Filter by policy topic"),
    urgency: Optional[str] = Query(None, description="Filter by urgency level"),
    limit: int = Query(100, ge=1, le=1000, description="Maximum results to return")
):
    """
    Query advocacy opportunities.
    
    Returns a list of identified opportunities for advocacy action
    based on the specified filters.
    """
    try:
        # Query from Delta Lake
        opportunities = pipeline.query_opportunities_by_state(state, urgency)
        
        # Apply additional filters
        if municipality:
            opportunities = [
                opp for opp in opportunities
                if opp.get("municipality", "").lower() == municipality.lower()
            ]
        
        if topic:
            opportunities = [
                opp for opp in opportunities
                if opp.get("topic") == topic
            ]
        
        # Limit results
        opportunities = opportunities[:limit]
        
        return OpportunityResponse(
            opportunities=opportunities,
            total_count=len(opportunities),
            filters_applied={
                "state": state,
                "municipality": municipality,
                "topic": topic,
                "urgency": urgency
            }
        )
        
    except Exception as e:
        logger.error(f"Error querying opportunities: {e}")
        raise HTTPException(status_code=500, detail=str(e))


# Deterministic state center coordinates (WGS84) used as a fallback when a bill's
# linked jurisdiction row does not provide explicit latitude/longitude coordinates.
STATE_COORDS: Dict[str, tuple[float, float]] = {
    "AL": (32.806671, -86.791130),
    "AK": (61.370716, -152.404419),
    "AZ": (33.729759, -111.431221),
    "AR": (34.969704, -92.373123),
    "CA": (36.116203, -119.681564),
    "CO": (39.059811, -105.311104),
    "CT": (41.597782, -72.755371),
    "DE": (39.318523, -75.507141),
    "DC": (38.897438, -77.026817),
    "FL": (27.766279, -81.686783),
    "GA": (33.040619, -83.643074),
    "HI": (21.094318, -157.498337),
    "ID": (44.240459, -114.478828),
    "IL": (40.349457, -88.986137),
    "IN": (39.849426, -86.258278),
    "IA": (42.011539, -93.210526),
    "KS": (38.526600, -96.726486),
    "KY": (37.668140, -84.670067),
    "LA": (31.169546, -91.867805),
    "ME": (44.693947, -69.381927),
    "MD": (39.063946, -76.802101),
    "MA": (42.230171, -71.530106),
    "MI": (43.326618, -84.536095),
    "MN": (45.694454, -93.900192),
    "MS": (32.741646, -89.678696),
    "MO": (38.456085, -92.288368),
    "MT": (46.921925, -110.454353),
    "NE": (41.125370, -98.268082),
    "NV": (38.313515, -117.055374),
    "NH": (43.452492, -71.563896),
    "NJ": (40.298904, -74.521011),
    "NM": (34.840515, -106.248482),
    "NY": (42.165726, -74.948051),
    "NC": (35.630066, -79.806419),
    "ND": (47.528912, -99.784012),
    "OH": (40.388783, -82.764915),
    "OK": (35.565342, -96.928917),
    "OR": (44.572021, -122.070938),
    "PA": (40.590752, -77.209755),
    "RI": (41.680893, -71.511780),
    "SC": (33.856892, -80.945007),
    "SD": (44.299782, -99.438828),
    "TN": (35.747845, -86.692345),
    "TX": (31.054487, -97.563461),
    "UT": (40.150032, -111.862434),
    "VT": (44.045876, -72.710686),
    "VA": (37.769337, -78.169968),
    "WA": (47.400902, -121.490494),
    "WV": (38.491226, -80.954453),
    "WI": (44.268543, -89.616508),
    "WY": (42.755966, -107.302490),
}

DEFAULT_OPPORTUNITY_STATES: tuple[str, ...] = ("AL", "GA", "IN", "MA", "WA", "WI")

_OPPORTUNITY_TOPIC_ALIASES: Dict[str, str] = {
    "fluoride": "water_fluoridation",
    "water_fluoridation": "water_fluoridation",
    "dental": "school_dental_screening",
    "school_dental_screening": "school_dental_screening",
    "medicaid": "medicaid_dental_expansion",
    "medicaid_dental_expansion": "medicaid_dental_expansion",
}


# React frontend endpoints with /api/ prefix
@app.get("/api/opportunities")
async def get_api_opportunities(
    state: Optional[str] = Query(None),
    topic: Optional[str] = Query(None),
    urgency: Optional[str] = Query(None),
    limit: int = Query(100, ge=1, le=1000)
):
    """API endpoint for React frontend opportunities page - returns fluoridation bills as advocacy opportunities."""
    try:
        from api.routes.bills_neon import get_pool

        if state is not None:
            state_norm = state.strip().upper()
            if state_norm not in STATE_COORDS:
                return {"opportunities": [], "total": 0}
            states = [state_norm]
        else:
            states = list(DEFAULT_OPPORTUNITY_STATES)

        topic_norm: Optional[str] = None
        if topic is not None and topic.strip():
            raw_topic = topic.strip().lower()
            topic_norm = _OPPORTUNITY_TOPIC_ALIASES.get(raw_topic, raw_topic)

        urgency_norm: Optional[str] = (
            urgency.strip().lower() if urgency is not None and urgency.strip() else None
        )

        pool = await get_pool()
        if pool is None:
            return {"opportunities": [], "total": 0}

        sql_limit = min(max(limit * 5, limit), 1000) if (topic_norm or urgency_norm) else limit

        # Query the Postgres `bills` mart joined to `jurisdictions` so real
        # jurisdiction coordinates are used when available, with deterministic
        # fallback to STATE_COORDS.
        query_with_jurisdictions = """
            SELECT
                b.state_code,
                b.title,
                b.identifier,
                b.session_identifier,
                b.latest_action_description,
                b.latest_action_date,
                j.latitude::float8 AS jurisdiction_latitude,
                j.longitude::float8 AS jurisdiction_longitude
            FROM bills b
            LEFT JOIN jurisdictions j
                ON j.jurisdiction_id = b.jurisdiction_id
            WHERE b.state_code = ANY($1::text[])
                AND (LOWER(b.title) LIKE '%fluorid%'
                   OR LOWER(b.title) LIKE '%dental%'
                   OR LOWER(b.title) LIKE '%oral health%'
                   OR LOWER(b.title) LIKE '%water treat%')
            ORDER BY b.latest_action_date DESC NULLS LAST, b.identifier ASC
            LIMIT $2
        """
        fallback_query = """
            SELECT
                state_code,
                title,
                identifier,
                session_identifier,
                latest_action_description,
                latest_action_date
            FROM bills
            WHERE state_code = ANY($1::text[])
                AND (LOWER(title) LIKE '%fluorid%'
                   OR LOWER(title) LIKE '%dental%'
                   OR LOWER(title) LIKE '%oral health%'
                   OR LOWER(title) LIKE '%water treat%')
            ORDER BY latest_action_date DESC NULLS LAST, identifier ASC
            LIMIT $2
        """

        async with pool.acquire() as conn:
            try:
                result = await conn.fetch(query_with_jurisdictions, states, sql_limit)
            except Exception:
                result = await conn.fetch(fallback_query, states, sql_limit)

        opportunities = []
        for row in result:
            row_dict = dict(row)
            state_code = (row_dict.get("state_code") or "").strip().upper()
            title = row_dict.get("title")
            identifier = row_dict.get("identifier")
            session = row_dict.get("session_identifier")
            latest_action = row_dict.get("latest_action_description")
            latest_action_date = row_dict.get("latest_action_date")

            title_lower = title.lower() if title else ""
            if "fluoride" in title_lower or "fluorin" in title_lower or "water" in title_lower:
                urgency_level = "critical"
                confidence = 0.9
                topic_type = "water_fluoridation"
            elif "dental" in title_lower:
                urgency_level = "high"
                confidence = 0.75
                topic_type = "school_dental_screening"
            else:
                urgency_level = "medium"
                confidence = 0.6
                topic_type = "medicaid_dental_expansion"

            if topic_norm and topic_type != topic_norm:
                continue

            if urgency_norm and urgency_level != urgency_norm:
                continue

            juris_lat = row_dict.get("jurisdiction_latitude")
            juris_lon = row_dict.get("jurisdiction_longitude")
            if juris_lat is not None and juris_lon is not None:
                latitude = float(juris_lat)
                longitude = float(juris_lon)
            elif state_code in STATE_COORDS:
                latitude, longitude = STATE_COORDS[state_code]
            else:
                continue

            opportunities.append({
                "state": state_code,
                "municipality": f"{state_code} Legislature",
                "latitude": latitude,
                "longitude": longitude,
                "topic": topic_type,
                "urgency": urgency_level,
                "confidence": confidence,
                "meeting_date": latest_action_date.isoformat() if hasattr(latest_action_date, "isoformat") else (str(latest_action_date) if latest_action_date else None),
                "title": title,
                "bill_id": identifier,
                "session": session,
                "latest_action": latest_action,
            })

            if len(opportunities) >= limit:
                break

        return {"opportunities": opportunities, "total": len(opportunities)}
    except Exception as e:
        logger.error(f"Error: {e}")
        return {"opportunities": [], "total": 0}


@app.get("/api/documents")
async def get_api_documents(
    search: Optional[str] = Query(None),
    page: int = Query(1),
    limit: int = Query(20)
):
    """API endpoint for React frontend documents page."""
    try:
        # Get all opportunities (documents)
        documents = pipeline.query_opportunities_by_state(None, None)
        
        # Apply search filter
        if search:
            search_lower = search.lower()
            documents = [
                d for d in documents
                if search_lower in d.get("title", "").lower() or
                   search_lower in d.get("municipality", "").lower() or
                   search_lower in d.get("content", "").lower()
            ]
        
        # Paginate
        start = (page - 1) * limit
        end = start + limit
        
        return {
            "documents": documents[start:end],
            "total": len(documents),
            "page": page,
            "limit": limit
        }
    except Exception as e:
        logger.error(f"Error: {e}")
        return {"documents": [], "total": 0}


@app.get("/opportunities/{opportunity_id}")
async def get_opportunity_detail(opportunity_id: str):
    """Get detailed information about a specific opportunity."""
    # Query specific opportunity
    document = pipeline.get_document_by_id(opportunity_id)
    
    if not document:
        raise HTTPException(status_code=404, detail="Opportunity not found")
    
    return document


@app.get("/opportunities/{opportunity_id}/materials")
async def get_advocacy_materials(opportunity_id: str):
    """Get generated advocacy materials for an opportunity."""
    # Query materials from Delta Lake
    # This is a placeholder
    return {
        "opportunity_id": opportunity_id,
        "materials": {
            "email": {
                "subject": "Support Oral Health Policy",
                "body": "..."
            },
            "talking_points": [],
            "social_media": {}
        }
    }


@app.get("/heatmap", response_class=HTMLResponse)
async def get_heatmap(
    urgency: Optional[str] = Query(None, description="Filter by urgency level")
):
    """
    Get interactive heatmap visualization.
    
    Returns an HTML page with an interactive map showing
    advocacy opportunities across the country.
    """
    try:
        # Query opportunities
        opportunities = pipeline.query_opportunities_by_state(None, urgency)
        
        # Generate map
        m = heatmap_generator.create_folium_map(
            opportunities,
            title="Open Navigator - Advocacy Heatmap"
        )
        
        # Return HTML
        return HTMLResponse(content=m._repr_html_())
        
    except Exception as e:
        logger.error(f"Error generating heatmap: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@app.get("/dashboard")
async def get_dashboard():
    """
    Get complete dashboard data including statistics and visualizations.
    """
    try:
        # Query all opportunities
        opportunities = pipeline.query_opportunities_by_state(None, None)
        
        # Generate dashboard
        dashboard = heatmap_generator.create_dashboard(opportunities)
        
        # Convert visualizations to JSON-serializable format
        return {
            "statistics": dashboard["statistics"],
            "topic_distribution": dashboard["topic_distribution"].to_json(),
            "timeline": dashboard["timeline"].to_json()
        }
        
    except Exception as e:
        logger.error(f"Error generating dashboard: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@app.get("/api/dashboard")
async def get_api_dashboard():
    """
    Get dashboard statistics for React frontend.
    Returns data in format expected by frontend Dashboard component.
    """
    try:
        # Query all opportunities
        opportunities = pipeline.query_opportunities_by_state(None, None)
        
        # Count topics
        topics_count = {}
        for opp in opportunities:
            topic = opp.get("topic", "unknown")
            topics_count[topic] = topics_count.get(topic, 0) + 1
        
        # Get unique states
        states = set(opp.get("state") for opp in opportunities if opp.get("state"))
        
        # Get recent opportunities (last 10)
        recent = sorted(
            opportunities,
            key=lambda x: x.get("meeting_date", ""),
            reverse=True
        )[:10]
        
        return {
            "total_documents": len(opportunities),
            "total_opportunities": len(opportunities),
            "states_monitored": len(states),
            "topics": topics_count,
            "recent_opportunities": recent
        }
        
    except Exception as e:
        logger.error(f"Error generating API dashboard: {e}")
        # Return mock data if there's an error
        return {
            "total_documents": 0,
            "total_opportunities": 0,
            "states_monitored": 0,
            "topics": {},
            "recent_opportunities": []
        }


@app.get("/topics")
async def get_topics():
    """Get list of all policy topics being tracked."""
    return {
        "topics": settings.policy_topics,
        "count": len(settings.policy_topics)
    }


@app.get("/states", response_model=StatesResponse, tags=["opportunities"])
@app.get("/api/states", response_model=StatesResponse, tags=["opportunities"])
async def get_states() -> StatesResponse:
    """Get list of all states with active opportunities.

    Queries distinct state codes from active bills in the database if available.
    When the query fails or returns nothing, uses the configured
    `settings.target_states` (real configuration). If that is not set either,
    returns an empty list rather than inventing states.
    """
    try:
        from api.routes.bills_neon import get_pool
        pool = await get_pool()
        if pool is not None:
            query = """
                SELECT DISTINCT UPPER(state_code) AS state_code
                FROM bills
                WHERE state_code IS NOT NULL
                  AND state_code != ''
                  AND (
                      LOWER(title) LIKE '%fluorid%'
                      OR LOWER(title) LIKE '%dental%'
                      OR LOWER(title) LIKE '%oral health%'
                      OR LOWER(title) LIKE '%water treat%'
                  )
                ORDER BY UPPER(state_code)
            """
            async with pool.acquire() as conn:
                rows = await conn.fetch(query)
            db_states = sorted(set(str(row["state_code"]).strip().upper() for row in rows if row.get("state_code")))
            if db_states:
                return StatesResponse(states=db_states, count=len(db_states))
    except Exception as e:
        logger.warning(f"Failed to query active opportunity states from bills database: {e}")

    # No database result: use configured target states (real configuration), never an invented list.
    configured_states = settings.target_states
    if configured_states:
        resolved = sorted(set(st.strip().upper() for st in configured_states if st and st.strip()))
    else:
        resolved = []
        logger.warning("No active opportunity states from the database and settings.target_states is not set; returning an empty list")

    return StatesResponse(states=resolved, count=len(resolved))


@app.get("/status", response_model=SystemStatus)
async def get_system_status():
    """Get current system status and health."""
    try:
        agent_status = orchestrator.get_all_agent_states()
        
        return SystemStatus(
            status="operational",
            active_workflows=len(orchestrator.active_workflows),
            agent_status=agent_status,
            last_update=datetime.utcnow()
        )
        
    except Exception as e:
        logger.error(f"Error getting system status: {e}")
        return SystemStatus(
            status="error",
            active_workflows=0,
            agent_status={},
            last_update=datetime.utcnow()
        )


@app.get("/nonprofits")
async def search_nonprofits(
    location: str = Query("Tuscaloosa, AL", description="City, State format"),
    keyword: Optional[str] = Query(None, description="Service keyword (e.g., 'dental', 'health')"),
    state: Optional[str] = Query(None, description="2-letter state code (e.g., 'AL')"),
    ntee_code: Optional[str] = Query(None, description="NTEE code (e.g., 'E' for health)"),
    source: Optional[str] = Query(None, description="Data source: 'propublica', 'everyorg', 'all'")
):
    """
    Search for nonprofits using free open data APIs.
    
    Integrates data from:
    - ProPublica Nonprofit Explorer (financial data, NTEE codes)
    - Every.org (mission statements, logos)
    - IRS TEOS (official tax-exempt status)
    
    Example: /nonprofits?location=Tuscaloosa,AL&keyword=dental&ntee_code=E
    """
    try:
        from scrapers.irs.nonprofit_discovery import NonprofitDiscovery
        
        discovery = NonprofitDiscovery()
        results = []
        
        # Parse location for state/city
        location_parts = location.split(',')
        city = location_parts[0].strip() if len(location_parts) > 0 else None
        state_from_location = location_parts[1].strip() if len(location_parts) > 1 else None
        state_code = state or state_from_location or "AL"
        
        # Determine which sources to query
        sources_to_query = ['propublica', 'everyorg'] if source == 'all' or not source else [source]
        
        # Query ProPublica
        if 'propublica' in sources_to_query:
            try:
                propublica_results = discovery.search_propublica(
                    state=state_code,
                    city=city,
                    ntee_code=ntee_code
                )
                results.extend(propublica_results)
                logger.info(f"ProPublica: Found {len(propublica_results)} organizations")
            except Exception as e:
                logger.warning(f"ProPublica search failed: {e}")
        
        # Query Every.org
        if 'everyorg' in sources_to_query:
            try:
                causes = []
                if keyword:
                    # Map keywords to causes
                    keyword_lower = keyword.lower()
                    if 'health' in keyword_lower or 'dental' in keyword_lower or 'medical' in keyword_lower:
                        causes.append('health')
                    if 'education' in keyword_lower or 'school' in keyword_lower:
                        causes.append('education')
                
                everyorg_results = discovery.search_everyorg(
                    location=location,
                    causes=causes if causes else None
                )
                results.extend(everyorg_results)
                logger.info(f"Every.org: Found {len(everyorg_results)} organizations")
            except Exception as e:
                logger.warning(f"Every.org search failed: {e}")
        
        # Filter by keyword if provided
        if keyword and results:
            keyword_lower = keyword.lower()
            filtered_results = []
            for org in results:
                # Search in name, description, mission, ntee_description
                searchable_text = ' '.join([
                    str(org.get('name', '')),
                    str(org.get('description', '')),
                    str(org.get('mission', '')),
                    str(org.get('ntee_description', ''))
                ]).lower()
                
                if keyword_lower in searchable_text:
                    filtered_results.append(org)
            
            results = filtered_results
        
        return {
            "location": location,
            "keyword": keyword,
            "state": state_code,
            "ntee_code": ntee_code,
            "count": len(results),
            "nonprofits": results,
            "data_sources": {
                "propublica": "https://projects.propublica.org/nonprofits/api",
                "everyorg": "https://www.every.org/nonprofit-api",
                "irs_teos": "https://www.irs.gov/charities-non-profits/tax-exempt-organization-search-bulk-data-downloads"
            }
        }
        
    except Exception as e:
        logger.error(f"Nonprofit search error: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@app.get("/api/nonprofits")
async def search_nonprofits_api(
    location: str = Query("Tuscaloosa, AL", description="City, State format"),
    keyword: Optional[str] = Query(None, description="Service keyword (e.g., 'dental', 'health')"),
    state: Optional[str] = Query(None, description="2-letter state code (e.g., 'AL')"),
    ntee_code: Optional[str] = Query(None, description="NTEE code (e.g., 'E' for health)"),
    source: Optional[str] = Query(None, description="Data source: 'propublica', 'everyorg', 'all'")
):
    """
    Search for nonprofits using free open data APIs (API-prefixed endpoint for frontend).
    
    This is a duplicate of /nonprofits with /api prefix for frontend routing.
    """
    return await search_nonprofits(location, keyword, state, ntee_code, source)


@app.get("/data/status")
async def get_data_ingestion_status():
    """
    Get status of reference data ingestions.
    
    Shows Census jurisdictions, NCES school districts, and nonprofit cache status.

    Every count is a real warehouse value (see
    ``stats_neon.fetch_national_reference_counts``) or ``null`` when it can't be
    computed β€” never a hard-coded estimate (CLAUDE.md, "No Fabricated Data").
    """
    try:
        from pathlib import Path

        from api.routes.stats_neon import fetch_national_reference_counts

        counts = await fetch_national_reference_counts()
        status = {
            "census": {
                "jurisdictions": counts["jurisdictions"],
                "counties": counts["counties"],
                "municipalities": counts["municipalities"],
                "status": "public.jurisdiction_state_aggregate (national) + public.civic_jurisdiction",
            },
            "nces": {
                "school_districts": counts["school_districts"],
                "status": "public.jurisdiction_state_aggregate (national)",
            },
            "nonprofits": {
                "total_available": counts["nonprofits"],
                "cached_searches": 0,
                "cache_path": "data/cache/nonprofits"
            },
            # Per-source meeting counts (MeetingBank, City Scrapers, Open States)
            # are not modeled in `public`; unavailable rather than guessed.
            "meetings": {
                "meetingbank": None,
                "city_scrapers": None,
                "open_states": None,
            }
        }
        
        # Check cache directories
        cache_dir = Path("data/cache/nonprofits")
        if cache_dir.exists():
            cached_files = list(cache_dir.glob("*.json"))
            status["nonprofits"]["cached_searches"] = len(cached_files)
        
        return status
        
    except Exception as e:
        logger.error(f"Data status error: {e}")
        return {"error": str(e)}


@app.post("/data/ingest/nonprofits")
async def bulk_ingest_nonprofits(
    state: str = Query(..., description="State code (e.g., AL)"),
    ntee_code: Optional[str] = Query("E", description="NTEE code (default: E for Health)")
):
    """
    Bulk ingest nonprofit data for a state.
    
    Caches ProPublica API results for offline use.
    """
    try:
        from scrapers.irs.nonprofit_discovery import NonprofitDiscovery
        
        discovery = NonprofitDiscovery()
        orgs = discovery.search_propublica(state=state, ntee_code=ntee_code)
        
        return {
            "message": f"Ingested {len(orgs)} nonprofits for {state}",
            "state": state,
            "ntee_code": ntee_code,
            "count": len(orgs),
            "cache_location": "data/cache/nonprofits"
        }
        
    except Exception as e:
        logger.error(f"Nonprofit ingestion error: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@app.get("/health")
async def health_check():
    """Health check endpoint for monitoring."""
    return {
        "status": "healthy",
        "timestamp": datetime.utcnow().isoformat(),
        "version": "1.0.0"
    }


@app.get("/api/health")
async def api_health_check():
    """Health check endpoint for monitoring (API path)."""
    return {
        "status": "healthy",
        "timestamp": datetime.utcnow().isoformat(),
        "version": "1.0.0"
    }


@app.post("/admin/initialize")
async def initialize_system():
    """Initialize Delta Lake tables and system components."""
    try:
        pipeline.initialize_tables()
        
        return {
            "status": "success",
            "message": "System initialized successfully"
        }
        
    except Exception as e:
        logger.error(f"Error initializing system: {e}")
        raise HTTPException(status_code=500, detail=str(e))


# Startup event
@app.post("/api/debate-grade")
async def grade_decision_with_debate_framework(
    document_id: Optional[str] = Query(None, description="Document ID to grade"),
    text: Optional[str] = Query(None, description="Text to grade directly"),
    title: Optional[str] = Query("", description="Document title")
):
    """
    Grade a government decision using debate framework (Harms/Solvency/Topicality).
    
    Translates debate concepts for laypeople:
    - Harms β†’ "The Problem": Why is this a crisis?
    - Solvency β†’ "The Fix": How does this solution work?
    - Topicality β†’ "The Scope": Does the government have authority?
    
    Example: /api/debate-grade?text=The city council approved funding for dental screening...
    """
    try:
        from agents.debate_grader import DebateGraderAgent
        
        grader = DebateGraderAgent()
        
        # Get document content
        if document_id:
            document = pipeline.get_document_by_id(document_id)
            if not document:
                raise HTTPException(status_code=404, detail="Document not found")
        elif text:
            document = {
                "content": text,
                "title": title,
                "id": "custom_text"
            }
        else:
            raise HTTPException(status_code=400, detail="Provide either document_id or text")
        
        # Grade the document
        grade = await grader._grade_document(document)
        
        return {
            "document_id": document.get("id"),
            "title": document.get("title", ""),
            "debate_grade": grade,
            "explanation": {
                "harms": "This measures how well the decision identifies and documents the problem using data and evidence",
                "solvency": "This measures how clearly the solution is defined and whether it will actually fix the problem",
                "topicality": "This measures whether the government body has the legal authority to take this action"
            }
        }
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Debate grading error: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@app.post("/api/debate-grade/batch")
async def grade_decisions_batch(
    state: Optional[str] = Query(None, description="Filter by state"),
    topic: Optional[str] = Query(None, description="Filter by topic"),
    limit: int = Query(50, description="Number of documents to grade")
):
    """
    Grade multiple government decisions using debate framework.
    
    Returns aggregate insights about decision quality across dimensions.
    """
    try:
        from agents.debate_grader import DebateGraderAgent
        from agents.base import AgentMessage, MessageType, AgentRole
        
        grader = DebateGraderAgent()
        
        # Get documents to grade
        documents = pipeline.query_opportunities_by_state(state, None)
        
        if topic:
            documents = [d for d in documents if d.get("topic") == topic]
        
        documents = documents[:limit]
        
        # Create message and process
        message = AgentMessage(
            message_id=f"batch_grade_{datetime.utcnow().timestamp()}",
            sender=AgentRole.ORCHESTRATOR,
            recipient=AgentRole.DEBATE_GRADER,
            message_type=MessageType.COMMAND,
            payload={"documents": documents}
        )
        
        result = await grader.process(message)
        graded_documents = result[0].payload.get("documents", [])
        insights = result[0].payload.get("insights", {})
        
        return {
            "graded_count": len(graded_documents),
            "documents": graded_documents,
            "insights": insights,
            "explanation": {
                "average_scores": "Average scores across all three debate dimensions (out of 5)",
                "strongest_dimension": "Which dimension governments perform best on",
                "weakest_dimension": "Which dimension needs the most improvement"
            }
        }
        
    except Exception as e:
        logger.error(f"Batch debate grading error: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@app.on_event("startup")
async def startup_event():
    """Initialize system on startup with data validation."""
    logger.info("="*80)
    logger.info("πŸš€ STARTING Open Navigator API")
    logger.info("="*80)
    logger.info(f"Configuration: {settings.catalog_name}.{settings.schema_name}")
    logger.info(f"Log Level: {settings.log_level}")
    logger.info(f"Log File: {settings.log_file}")
    
    # Check if running on HuggingFace Spaces
    IS_HF_SPACES = os.getenv("HF_SPACES") == "1"
    if IS_HF_SPACES:
        logger.info(f"πŸ€— Running on HuggingFace Spaces")
    else:
        logger.info(f"πŸ’» Running in local/standard environment")
    
    # Validate critical data files
    logger.info("")
    logger.info("πŸ“Š VALIDATING DATA AVAILABILITY...")
    logger.info("-" * 80)
    
    data_dir = Path("data/gold")
    critical_files = []
    optional_files = []
    
    # Check reference data (critical). These now come from the Postgres `public`
    # schema rather than local parquet (CLAUDE.md: API must read `public`).
    # Each probe reports its live row count via SELECT count(*).
    import psycopg2
    _ref_dsn = os.getenv(
        "NEON_DATABASE_URL_DEV",
        "postgresql://postgres:password@localhost:5433/open_navigator",
    )
    # label -> SQL count query against public schema
    reference_db_checks = [
        ("jurisdictions (city/town/county)",
         "SELECT count(*) FROM public.jurisdictions "
         "WHERE jurisdiction_type IN ('city','town','county')"),
        ("jurisdictions (counties)",
         "SELECT count(*) FROM public.jurisdictions "
         "WHERE jurisdiction_type = 'county'"),
        ("causes (public.tag)", "SELECT count(*) FROM public.tag"),
    ]
    try:
        _ref_conn = psycopg2.connect(_ref_dsn)
        _ref_cur = _ref_conn.cursor()
        for label, query in reference_db_checks:
            try:
                _ref_cur.execute(query)
                _count = _ref_cur.fetchone()[0]
                logger.info(f"  βœ… {label}: {_count:,} records (public schema)")
                critical_files.append(label)
            except Exception as e:
                logger.error(f"  ❌ {label}: ERROR - {e}")
        _ref_cur.close()
        _ref_conn.close()
    except Exception as e:
        logger.error(f"  ❌ reference counts: could not connect to public schema - {e}")
    
    # State data availability β€” served from the Postgres `public` schema.
    # events -> public.event grouped by state_code (NOT per-state parquet dirs).
    # NOTE: nonprofits (public.mdm_organization_nonprofit) has no state_code and
    # no usable org->location join, so a per-state nonprofit count is not
    # available here; only the national count is logged below.
    logger.info("")
    logger.info("πŸ“ STATE DATA AVAILABILITY:")
    try:
        _state_conn = psycopg2.connect(_ref_dsn)
        _state_cur = _state_conn.cursor()
        _state_cur.execute(
            "SELECT state_code, count(*) FROM public.event "
            "WHERE state_code IS NOT NULL GROUP BY state_code ORDER BY state_code"
        )
        _state_rows = _state_cur.fetchall()

        _state_cur.execute("SELECT count(*) FROM public.mdm_organization_nonprofit")
        _np_national = _state_cur.fetchone()[0]

        _state_cur.close()
        _state_conn.close()

        for sc, cnt in _state_rows[:10]:  # Show first 10 states
            logger.info(f"  βœ… {sc}: {cnt:,} events")
        total_states = len(_state_rows)
        if total_states > 10:
            logger.info(f"  ... and {total_states - 10} more states")
        logger.info(f"")
        logger.info(f"  πŸ“Š Total states with events: {total_states}")
        logger.info(f"  🏒 public.mdm_organization_nonprofit: {_np_national:,} nonprofits (national)")
    except Exception as e:
        logger.warning(f"  ⚠️  Could not read per-state event counts from public schema: {e}")

    # Officials are served from contact_official (not parquet). Log the
    # live row count once so the startup banner still reports officials volume.
    try:
        import psycopg2
        _officials_dsn = os.getenv(
            "NEON_DATABASE_URL_DEV",
            "postgresql://postgres:password@localhost:5433/open_navigator",
        )
        _conn = psycopg2.connect(_officials_dsn)
        _cur = _conn.cursor()
        _cur.execute("SELECT count(*) FROM contact_official")
        _officials_count = _cur.fetchone()[0]
        _cur.close()
        _conn.close()
        logger.info(f"  πŸ›οΈ  contact_official: {_officials_count:,} officials")
    except Exception as e:
        logger.warning(f"  ⚠️  Could not count contact_official: {e}")

    # Validate HuggingFace datasets if running on HF Spaces
    if IS_HF_SPACES:
        logger.info("")
        logger.info("πŸ€— VALIDATING HUGGINGFACE DATASETS...")
        logger.info("-" * 80)
        
        # Check a sample of critical datasets (using new consolidated datasets)
        import requests
        
        test_datasets = [
            ("https://huggingface.co/datasets/CommunityOne/one-bills/resolve/main/data/train-00000-of-00001.parquet", "Bills (Consolidated)"),
            ("https://huggingface.co/datasets/CommunityOne/one-local-officials/resolve/main/data/train-00000-of-00001.parquet", "Local Officials (Consolidated)"),
            ("https://huggingface.co/datasets/CommunityOne/one-nonprofits-organizations/resolve/main/data/train-00000-of-00001.parquet", "Nonprofits (Consolidated)"),
        ]
        
        hf_datasets_ok = 0
        for url, display_name in test_datasets:
            try:
                response = requests.head(url, timeout=10, allow_redirects=True)
                if response.status_code == 200:
                    logger.info(f"  βœ… {display_name}: Accessible")
                    hf_datasets_ok += 1
                else:
                    logger.error(f"  ❌ {display_name}: HTTP {response.status_code}")
                    logger.error(f"     URL: {url}")
            except Exception as e:
                logger.error(f"  ❌ {display_name}: {type(e).__name__} - {e}")
                logger.error(f"     URL: {url}")
        
        logger.info("")
        logger.info(f"  πŸ“Š HuggingFace datasets validated: {hf_datasets_ok}/{len(test_datasets)}")
        
        if hf_datasets_ok < len(test_datasets):
            logger.warning("  ⚠️  Some datasets are not accessible - API may have limited functionality")
    
    logger.info("")
    logger.info("="*80)
    logger.info(f"βœ… API READY - {len(critical_files)}/{len(reference_db_checks)} critical files available")
    if IS_HF_SPACES:
        logger.info(f"βœ… HuggingFace datasets validated")
    logger.info("="*80)
    logger.info("")


# Shutdown event
@app.on_event("shutdown")
async def shutdown_event():
    """Cleanup on shutdown."""
    logger.info("Shutting down CommunityOne Open Navigator API")


# ---------------------------------------------------------------------------
# Built frontend (React/Vite) + docs (Docusaurus) β€” single-process serving
# ---------------------------------------------------------------------------
# In the HuggingFace deployment nginx serves these static bundles and proxies
# only /api to uvicorn. Databricks Apps run ONE process with no fronting proxy,
# so FastAPI itself must serve the SPA and the docs. These routes are registered
# LAST (after every API router) so the greedy ``/{full_path:path}`` catch-all
# cannot shadow a real API route. The whole block is a no-op when no build is
# present (api/static/index.html missing), e.g. an API-only container.
_spa_static_dir = Path(__file__).parent / "static"
if (_spa_static_dir / "index.html").is_file():
    from fastapi.responses import FileResponse

    # Hashed JS/CSS produced by Vite (build outDir = api/static, so /assets here).
    _assets_dir = _spa_static_dir / "assets"
    if _assets_dir.is_dir():
        app.mount("/assets", StaticFiles(directory=_assets_dir), name="spa_assets")

    logger.info(f"Serving built SPA + docs from {_spa_static_dir}")

    @app.get("/{full_path:path}", include_in_schema=False)
    async def serve_spa_and_docs(full_path: str, request: Request):
        """Serve the built docs / SPA for any non-API path.

        Resolution order:
          1. /api/* that fell through the routers -> 404 (never serve the SPA for
             a missing API endpoint, which would mask bugs with a 200 HTML body).
          2. A concrete static file inside api/static (assets handled by the mount
             above; this covers /docs/*, /robots.txt, /pdf/*, favicon, etc.).
          3. A directory request that has an index.html (e.g. /docs/ -> docs/index.html).
          4. Otherwise the React index.html (client-side routing).
        Path traversal is guarded via ``relative_to``.
        """
        if full_path == "api" or full_path.startswith("api/"):
            raise HTTPException(status_code=404, detail="API endpoint not found")

        if full_path:
            candidate = (_spa_static_dir / full_path).resolve()
            try:
                candidate.relative_to(_spa_static_dir.resolve())
            except ValueError:
                candidate = None
            if candidate is not None:
                if candidate.is_file():
                    return FileResponse(candidate)
                # Directory (e.g. /docs/) -> its index.html if present.
                index_in_dir = candidate / "index.html"
                if candidate.is_dir() and index_in_dir.is_file():
                    return FileResponse(index_in_dir)

        # The React shell, with this path's own title, description, canonical and OpenGraph tags (#1430).
        query = f"?{request.url.query}" if request.url.query else ""
        return await seo_routes.spa_response(_spa_static_dir / "index.html", f"/{full_path}{query}")


if __name__ == "__main__":
    import uvicorn

    # Honor DATABRICKS_APP_PORT when running this module directly so a local
    # `python api/main.py` mirrors the platform launch. The app.yaml command is
    # the authoritative entry point in production.
    _port = int(os.getenv("DATABRICKS_APP_PORT", str(settings.api_port)))
    uvicorn.run(
        app,
        host="0.0.0.0",
        port=_port,
        workers=settings.api_workers,
    )