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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
# EUR-Lex AI Chat — Full Implementation Plan

**Project:** EUR-Lex AI Chat — Ask questions about EU law in plain language, get answers with citations to real EUR-Lex documents.
**Build target:** ~15 hours total (one-time, laptop-based)
**Ongoing cost:** $0.00/month — runs 100% autonomously after deployment

---

## Overview

### Architecture

```
DATA FLOW (fully automated):

EUR-Lex Cellar SPARQL (public)
     │ GitHub Actions queries daily

Cellar REST RDF → XHTML (public, no auth)
     │ GitHub Actions downloads via RDF graph traversal

GitHub Actions Runner (free, 7GB RAM, 2-core CPU)
     │ pip install → chunk → embed (sentence-transformers ONNX) → merge

HuggingFace Hub Dataset (public, free storage)
     │ vectors.npy + chunks.json
     │ ▲                        │
     │ │                        ▼
     │ │               Render (512MB, free)
     │ │               ├── startup: download from HF Hub
     │ │               ├── hourly: check HF Hub for updates via /refresh
     │ │               └── live: FastAPI + numpy KNN (brute-force cosine similarity)
     │ │                        │
     │ │                        ▼
     │ │              ┌─────────────────┐
     │ └──────────────┤  Groq API        │
     │                │  (Llama 3.3 70B) │
     │                └────────┬─────────┘
     │                         │
USER FLOW:                     │
[Google Search]                │
     │ user finds FAQ/blog post

[Browser] ─► [Vercel: Astro site] ─► [Render: FastAPI API] ─► [Groq]
              Static HTML pages       /chat endpoint         answer
              + React chat island     numpy KNN + RAG

KEEP ALIVE:
[cron-job.org] ──► [Render /health] every 5 min
[cron-job.org] ──► [Render /refresh] every 60 min
```

### Files Layout

```
eur-lex-ai-chat/
├── backend/
│   ├── main.py                 # FastAPI: /chat, /health, /refresh
│   ├── search.py               # numpy KNN search over pre-loaded vectors
│   ├── rag.py                  # Build prompt, call Groq, parse citations
│   ├── data_loader.py          # Download index from HF Hub at startup
│   ├── rate_limit.py           # Per-IP + global rate limiting
│   ├── requirements.txt        # fastapi, uvicorn, numpy, huggingface_hub, httpx
│   └── startup.sh              # Render entry point
├── frontend/
│   ├── src/
│   │   ├── pages/
│   │   │   ├── index.astro         # Landing page (SEO + chat island)
│   │   │   ├── faq.astro           # FAQ page (JSON-LD)
│   │   │   └── blog/
│   │   │       ├── index.astro     # Blog listing
│   │   │       └── posts/          # Markdown blog posts
│   │   ├── components/
│   │   │   ├── ChatWidget.jsx      # React chat island
│   │   │   └── SeoHead.astro      # JSON-LD + OG tags
│   │   └── layouts/
│   │       └── Base.astro          # Main layout
│   ├── astro.config.mjs
│   ├── tailwind.config.mjs
│   └── package.json
├── scripts/
│   ├── build_index.py          # Laptop: FULL build from scratch (one-time)
│   └── update_index.py         # GitHub Actions: INCREMENTAL update (daily)
├── .github/
│   └── workflows/
│       └── update-index.yml    # GitHub Actions workflow
├── proposal.md
├── implementation-plan.md
└── README.md
```

---

## Phase 0: Pre-flight Checklist

**Goal:** Verify every tool, API key, and service is working before we start building.

### Step 0.1 — Verify Node.js (needs >=22.12.0 for Astro 5)

```bash
source ~/.nvm/nvm.sh
nvm use v22.22.3
node --version   # must show v22.22.3
npm --version    # must show 10.x or higher
```

If nvm is not found, install it:
```bash
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.5/install.sh | bash
source ~/.bashrc
nvm install v22.22.3
nvm use v22.22.3
```

### Step 0.2 — Verify Python venv + packages

```bash
source ~/Desktop/EUProjects/.venv/bin/activate
python3 --version   # must show 3.12.x
pip list | grep -E "fastapi|uvicorn|numpy|httpx|huggingface|polars|eurlxp|beautifulsoup4|pymupdf|tqdm|pydantic"
```

Expected: fastapi, uvicorn, numpy, httpx, huggingface_hub, polars, eurlxp, beautifulsoup4, pymupdf, tqdm, pydantic.

If any are missing:
```bash
pip install fastapi uvicorn numpy httpx huggingface_hub polars eurlxp[sparql] beautifulsoup4 pymupdf tqdm
```

### Step 0.3 — Install sentence-transformers (needed for Phase 1)

```bash
source ~/Desktop/EUProjects/.venv/bin/activate
pip install sentence-transformers
```

This installs torch (~2GB). It's a one-time install for the laptop build. The build script runs once.

### Step 0.4 — Verify GROQ_API_KEY

```bash
source ~/Desktop/EUProjects/.venv/bin/activate
python3 -c "
import os, httpx
key = os.environ.get('GROQ_API_KEY')
if not key: print('MISSING: GROQ_API_KEY not found in env')
else:
    r = httpx.get('https://api.groq.com/openai/v1/models',
        headers={'Authorization': f'Bearer {key}'}, timeout=10)
    assert r.status_code == 200, f'GROQ API returned {r.status_code}'
    models = [m['id'] for m in r.json()['data']]
    print(f'GROQ OK — {len(models)} models available')
    print(f'  Default: llama-3.3-70b-versatile')
"
```

If `GROQ_API_KEY` is missing, it should be in `/home/nedaktov/Desktop/NedCode3/.env`:
```bash
source /home/nedaktov/Desktop/NedCode3/.env
echo "GROQ_API_KEY is set: ${GROQ_API_KEY:0:10}..."
```

### Step 0.5 — Verify HuggingFace Hub access

```bash
source ~/Desktop/EUProjects/.venv/bin/activate
python3 -c "
from huggingface_hub import HfApi
api = HfApi()
# Test anonymous read access
try:
    api.dataset_info('hf-internal-testing/dummy_dataset')
    print('HF Hub accessible (anonymous)')
except Exception as e:
    print(f'HF Hub error: {e}')
"
```

### Step 0.6 — Create HuggingFace token and log in

We need a write token to upload the vector index. Create one at: https://huggingface.co/settings/tokens

Create a token with "write" permissions. Then:
```bash
source ~/Desktop/EUProjects/.venv/bin/activate
huggingface-cli login --token YOUR_HF_TOKEN
# Or use the Python API:
python3 -c "
from huggingface_hub import login
login(token='YOUR_HF_TOKEN', add_to_git_credential=True)
print('Logged in to HuggingFace')
"
```

### Step 0.7 — Create project directories

```bash
mkdir -p ~/Desktop/EUProjects/eur-lex-ai-chat/{backend,frontend/src/{pages,components,layouts,pages/blog/posts},scripts,.github/workflows,data}
```

### Step 0.8 — Verify EUR-Lex SPARQL endpoint + eurlxp

```bash
source ~/Desktop/EUProjects/.venv/bin/activate
python3 -c "
from eurlxp import get_documents
docs = get_documents(types=['REG'], limit=3)
print(f'SPARQL OK — got {len(docs)} documents')
for d in docs:
    print(f'  {d[\"celex\"]} ({d[\"type\"]}) — {d[\"date\"]}')
"
```

Expected output:
```
SPARQL OK — got 3 documents
  32025R1355R(02) (REG) — 2026-03-27
  ...
```

### Step 0.9 — Verify EUR-Lex HTML fetch + parse

⚠️ **Known issue:** `eurlxp.parse_html()` has a Polars schema bug — the `modifier` field is conditionally included, causing schema mismatch. Use the internal parser directly with a fixed schema instead.

```bash
source ~/Desktop/EUProjects/.venv/bin/activate
python3 -c "
from eurlxp import get_html_by_celex_id
from eurlxp.parser import _parse_html_with_beautifulsoup as internal_parse
import polars as pl

html = get_html_by_celex_id('32019R0947', language='en')
print(f'HTML fetched: {len(html)} bytes')

results = internal_parse(html)
print(f'Parsed: {len(results)} elements')

# Build records with fixed schema (workaround for eurlxp Polars bug)
records = []
for r in results:
    records.append({
        'text': r.text,
        'type': r.item_type,
        'ref': str(r.ref),
        'modifier': r.modifier,
        'document': r.context.document,
        'article': r.context.article,
        'article_subtitle': r.context.article_subtitle,
        'paragraph': r.context.paragraph,
        'group': r.context.group,
        'section': r.context.section,
    })

df = pl.DataFrame(records, schema={
    'text': pl.Utf8, 'type': pl.Utf8, 'ref': pl.Utf8,
    'modifier': pl.Utf8, 'document': pl.Utf8, 'article': pl.Utf8,
    'article_subtitle': pl.Utf8, 'paragraph': pl.Utf8,
    'group': pl.Utf8, 'section': pl.Utf8,
})
print(f'DataFrame: {len(df)} rows')
texts = df.filter(pl.col('type') == 'text')
print(f'Text elements: {len(texts)}')
print(texts.head(5))
"
```

### Step 0.10 — Pre-flight checklist summary

| # | Check | Status | Fix if failing |
|---|-------|--------|----------------|
| 1 | Node.js >=22.12.0 | | `nvm install v22.22.3` |
| 2 | Python venv active | | `source ~/Desktop/EUProjects/.venv/bin/activate` |
| 3 | All Python packages installed | | `pip install -r requirements.txt` |
| 4 | sentence-transformers installed | | `pip install sentence-transformers` |
| 5 | GROQ_API_KEY in env | | Add to .env and source it |
| 6 | HF Hub accessible | | Check internet, try again |
| 7 | HF write token + login | | Create token at huggingface.co/settings/tokens |
| 8 | Project directories exist | | Run mkdir command above |
| 9 | EUR-Lex SPARQL works | | Check internet, try later |
| 10 | EUR-Lex HTML fetch works | | Check eurlxp version, try again |

---

## Phase 1: Build the Data Index

**Goal:** Create the vector index of all EU legislative acts. This runs ONCE on your laptop (~3-5 hours). Output: vectors.npy + chunks.json uploaded to HuggingFace Hub.

**Scope:** All regulations (REG), directives (DIR), implementing regulations (REG_IMPL), and implementing directives (DIR_IMPL) with English titles, published from 2000-01-01 onwards. This covers ~25 years of EU legislation — the laws people actually search for.

### Step 1.1 — Write `scripts/build_index.py`

This is the main build script. Save it as `~/Desktop/EUProjects/eur-lex-ai-chat/scripts/build_index.py`:

```python
#!/usr/bin/env python3
"""
build_index.py — One-time full build of the EUR-Lex vector index.

Pipeline:
  1. SPARQL query → list of CELEX IDs with metadata
  2. For each CELEX ID: RDF graph traversal → XHTML content
  3. Parse HTML → structured text via eurlxp parser
  4. Chunk into passages (by article/paragraph)
  5. Embed with sentence-transformers (all-MiniLM-L6-v2, 384-dim)
  6. Upload vectors.npy + chunks.json to HuggingFace Hub

Usage:
  source ~/Desktop/EUProjects/.venv/bin/activate
  HF_TOKEN=hf_yourtoken python3 scripts/build_index.py

Output:
  data/vectors.npy     — numpy array of shape (N, 384), float32
  data/chunks.json     — list of dicts with text + metadata
  data/last_updated.txt — ISO timestamp of build
"""

import json
import logging
import os
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
from datetime import datetime, timezone

import numpy as np
import requests
from tqdm import tqdm

logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
logger = logging.getLogger(__name__)

DATA_DIR = os.path.join(os.path.dirname(os.path.dirname(__file__)), "data")
os.makedirs(DATA_DIR, exist_ok=True)

# ── Configuration ──────────────────────────────────────────────────────────

SPARQL_ENDPOINT = "https://publications.europa.eu/webapi/rdf/sparql"

# Document types to include
DOC_TYPES = [
    "REG",       # Regulations
    "DIR",       # Directives
    "REG_IMPL",  # Implementing regulations
    "DIR_IMPL",  # Implementing directives
]

# Date range: 2000-01-01 onwards (covers 25+ years of EU law)
FROM_DATE = "2000-01-01"

# How many documents to fetch per SPARQL page
SPARQL_PAGE_SIZE = 1000

# How many parallel download workers
DOWNLOAD_WORKERS = 20

# Embedding model
EMBEDDING_MODEL = "all-MiniLM-L6-v2"  # 384-dim, runs on CPU

# HuggingFace dataset name
HF_DATASET_NAME = "eurlex-chat-data"

# ── Step 1: SPARQL Query ───────────────────────────────────────────────────

def make_type_filter(types):
    """Build SPARQL FILTER for document types."""
    type_uris = [
        f"<http://publications.europa.eu/resource/authority/resource-type/{t}>"
        for t in types
    ]
    return " ||\n    ".join(f"?type = {uri}" for uri in type_uris)


def query_all_documents():
    """Query all documents matching our criteria via SPARQL with pagination."""
    logger.info("Querying SPARQL for documents...")

    all_docs = []
    offset = 0

    while True:
        type_filter = make_type_filter(DOC_TYPES)
        query = f"""
PREFIX cdm: <http://publications.europa.eu/ontology/cdm#>
PREFIX dc: <http://purl.org/dc/elements/1.1/>

SELECT DISTINCT ?doc ?type ?celex ?title ?date
WHERE {{
    ?doc cdm:work_has_resource-type ?type .
    ?doc cdm:resource_legal_id_celex ?celex .
    ?doc dc:title ?title .
    ?doc cdm:work_date_document ?date .
    FILTER({type_filter})
    FILTER(LANG(?title) = "en")
    FILTER(?date >= "{FROM_DATE}"^^xsd:date)
}}
ORDER BY DESC(?date)
OFFSET {offset}
LIMIT {SPARQL_PAGE_SIZE}
"""
        r = requests.get(
            SPARQL_ENDPOINT,
            params={"query": query, "format": "json"},
            timeout=60,
        )
        r.raise_for_status()
        data = r.json()
        bindings = data["results"]["bindings"]

        if not bindings:
            break

        for b in bindings:
            all_docs.append({
                "celex": b["celex"]["value"],
                "title": b["title"]["value"],
                "date": b["date"]["value"],
                "type": b["type"]["value"].split("/")[-1],
                "cellar_url": b["doc"]["value"],
            })

        offset += SPARQL_PAGE_SIZE
        logger.info(f"  Fetched {len(all_docs)} documents so far...")

        if len(bindings) < SPARQL_PAGE_SIZE:
            break

    logger.info(f"Total documents found: {len(all_docs)}")
    return all_docs


# ── Step 2: Download XHTML Content ─────────────────────────────────────────

def fetch_document_xhtml(doc):
    """Fetch a document's XHTML content via Cellar RDF graph traversal.

    Uses the same approach as eurlxp's _fetch_html_via_sparql:
    1. Get work RDF → find English expression
    2. Get expression RDF → find XHTML manifestation
    3. Download XHTML
    """
    celex = doc["celex"]
    try:
        # Step 1: Get work RDF graph
        work_url = f"http://publications.europa.eu/resource/celex/{celex}?language=eng"
        r = requests.get(work_url, timeout=30)
        r.raise_for_status()

        # Parse RDF/XML to find English expression
        from xml.etree import ElementTree as ET
        root = ET.fromstring(r.content)

        # Namespaces
        ns = {
            "rdf": "http://www.w3.org/1999/02/22-rdf-syntax-ns#",
            "cdm": "http://publications.europa.eu/ontology/cdm#",
        }

        # Find the English expression (ENG)
        expressions = root.findall(".//cdm:work_has_expression", ns)
        expression_url = None
        for expr in expressions:
            resource = expr.get("{http://www.w3.org/1999/02/22-rdf-syntax-ns#}resource")
            if resource and resource.endswith(".ENG"):
                expression_url = resource
                break

        if not expression_url and expressions:
            # Fallback to first expression
            resource = expressions[0].get(
                "{http://www.w3.org/1999/02/22-rdf-syntax-ns#}resource"
            )
            if resource:
                expression_url = resource

        if not expression_url:
            logger.warning(f"  No expression found for {celex}")
            return None

        # Step 2: Get expression RDF to find XHTML manifestation
        r2 = requests.get(expression_url, timeout=30)
        r2.raise_for_status()
        expr_root = ET.fromstring(r2.content)

        manifestations = expr_root.findall(
            ".//cdm:expression_manifested_by_manifestation", ns
        )
        xhtml_url = None
        for manif in manifestations:
            resource = manif.get(
                "{http://www.w3.org/1999/02/22-rdf-syntax-ns#}resource"
            )
            if resource and resource.endswith(".xhtml"):
                xhtml_url = resource
                break

        if not xhtml_url and manifestations:
            # Fallback to .fmx4 (Formex 4 format)
            for manif in manifestations:
                resource = manif.get(
                    "{http://www.w3.org/1999/02/22-rdf-syntax-ns#}resource"
                )
                if resource and resource.endswith(".fmx4"):
                    xhtml_url = resource
                    break

        if not xhtml_url:
            logger.warning(f"  No XHTML manifestation for {celex}")
            return None

        # Step 3: Download the XHTML content
        r3 = requests.get(
            xhtml_url,
            headers={"Accept": "application/xhtml+xml, text/html"},
            timeout=30,
        )
        r3.raise_for_status()
        html = r3.text

        if len(html) < 100:
            logger.warning(f"  Empty content for {celex}")
            return None

        return html

    except requests.RequestException as e:
        logger.warning(f"  HTTP error for {celex}: {e}")
        return None
    except ET.ParseError as e:
        logger.warning(f"  XML parse error for {celex}: {e}")
        return None
    except Exception as e:
        logger.warning(f"  Unexpected error for {celex}: {e}")
        return None


# ── Step 3: Parse HTML → Structured Text ───────────────────────────────────

def parse_html_to_chunks(html, celex_id, title):
    """Parse EUR-Lex HTML into text chunks using eurlxp internal parser.

    ⚠️ Uses _parse_html_with_beautifulsoup directly instead of parse_html()
    because eurlxp's parse_html() has a Polars schema bug (conditional modifier
    field causes schema mismatch). This workaround uses a fixed schema.
    """
    from eurlxp.parser import _parse_html_with_beautifulsoup as internal_parse
    import polars as pl

    try:
        results = internal_parse(html)
    except Exception as e:
        logger.warning(f"  Parse error for {celex_id}: {e}")
        return []

    if not results:
        return []

    # Convert to DataFrame with fixed schema (bypasses eurlxp bug)
    records = []
    for r in results:
        records.append({
            'text': r.text,
            'type': r.item_type,
            'ref': str(r.ref),
            'modifier': r.modifier,
            'document': r.context.document,
            'article': r.context.article,
            'article_subtitle': r.context.article_subtitle,
            'paragraph': r.context.paragraph,
            'group': r.context.group,
            'section': r.context.section,
        })

    df = pl.DataFrame(records, schema={
        'text': pl.Utf8, 'type': pl.Utf8, 'ref': pl.Utf8,
        'modifier': pl.Utf8, 'document': pl.Utf8, 'article': pl.Utf8,
        'article_subtitle': pl.Utf8, 'paragraph': pl.Utf8,
        'group': pl.Utf8, 'section': pl.Utf8,
    })

    if len(df) == 0:
        return []

    chunks = []
    current_article = None
    current_text = []

    # Process rows in order
    for row in df.to_dicts():
        text = row.get("text", "").strip()
        row_type = row.get("type", "")
        article = row.get("article", None)

        if not text:
            continue

        # Skip very short fragments (titles, headers)
        if len(text) < 40 and row_type in ("doc-title", "art-title", "art-subtitle", "group-title"):
            if row_type == "doc-title":
                pass  # We already have the title from SPARQL
            elif row_type == "art-title" and article:
                # Finalize previous article chunk
                if current_text:
                    chunk_text = " ".join(current_text)
                    if len(chunk_text) > 50:
                        chunks.append({
                            "text": chunk_text,
                            "celex": celex_id,
                            "title": title,
                            "article": current_article,
                            "type": "article",
                        })
                    current_text = []
                current_article = article
            continue

        # Skip pure metadata rows
        if row_type in ("doc-title", "art-subtitle", "group-title", "section-title"):
            continue

        # Skip notice/note rows
        if row.get("modifier") in ("note", "signatory"):
            continue

        current_text.append(text)

        # If text is a full paragraph and we have enough context, finalize
        if len(text) > 100 and current_text:
            # Check if this is a natural break (new article, new section)
            pass

    # Flush remaining text
    if current_text:
        chunk_text = " ".join(current_text)
        if len(chunk_text) > 50:
            chunks.append({
                "text": chunk_text,
                "celex": celex_id,
                "title": title,
                "article": current_article,
                "type": "article",
            })

    # If no article-based chunks found, fall back to paragraph splitting
    if not chunks:
        # Try to split by paragraphs (double newlines)
        paragraphs = [
            p.strip() for p in html.replace("</p>", "\n\n")
            .replace("</div>", "\n\n")
            .replace("<br/>", "\n")
            .split("\n\n")
            if len(p.strip()) > 80
        ]
        for i, para in enumerate(paragraphs):
            chunks.append({
                "text": para,
                "celex": celex_id,
                "title": title,
                "article": None,
                "type": "paragraph",
            })

    return chunks


# ── Step 4: Embed ──────────────────────────────────────────────────────────

def embed_chunks(all_chunks, batch_size=128):
    """Embed all chunks using sentence-transformers."""
    from sentence_transformers import SentenceTransformer

    logger.info(f"Loading embedding model: {EMBEDDING_MODEL}")
    model = SentenceTransformer(EMBEDDING_MODEL)
    logger.info("Model loaded")

    texts = [c["text"] for c in all_chunks]
    all_embeddings = []

    logger.info(f"Embedding {len(texts)} chunks in batches of {batch_size}...")
    for i in range(0, len(texts), batch_size):
        batch = texts[i : i + batch_size]
        embeddings = model.encode(batch, show_progress_bar=False, normalize_embeddings=True)
        all_embeddings.append(embeddings)

        if (i // batch_size) % 10 == 0:
            logger.info(f"  Embedded {min(i + batch_size, len(texts))}/{len(texts)}")

    return np.vstack(all_embeddings).astype(np.float32)


# ── Step 5: Upload to HuggingFace Hub ──────────────────────────────────────

def upload_to_hub(vectors, chunks, dataset_name, token):
    """Upload vectors.npy + chunks.json + last_updated.txt to HF Hub."""
    from huggingface_hub import HfApi, create_repo

    api = HfApi()
    repo_id = f"{api.whoami()['name']}/{dataset_name}"

    # Create repo if it doesn't exist
    try:
        create_repo(repo_id, repo_type="dataset", exist_ok=True, token=token)
        logger.info(f"HF dataset repo: {repo_id}")
    except Exception as e:
        logger.warning(f"Repo creation warning (may already exist): {e}")

    # Save vectors
    vectors_path = os.path.join(DATA_DIR, "vectors.npy")
    np.save(vectors_path, vectors)
    logger.info(f"Saved vectors: {vectors.shape} ({os.path.getsize(vectors_path) / 1e6:.1f} MB)")

    # Save chunks
    chunks_path = os.path.join(DATA_DIR, "chunks.json")
    with open(chunks_path, "w") as f:
        json.dump(chunks, f, indent=2)
    logger.info(f"Saved chunks: {len(chunks)} items ({os.path.getsize(chunks_path) / 1e6:.1f} MB)")

    # Save timestamp
    ts_path = os.path.join(DATA_DIR, "last_updated.txt")
    ts = datetime.now(timezone.utc).isoformat()
    with open(ts_path, "w") as f:
        f.write(ts)

    # Upload files
    api.upload_file(
        repo_id=repo_id,
        path_in_repo="vectors.npy",
        path_or_fileobj=vectors_path,
        repo_type="dataset",
        token=token,
    )
    api.upload_file(
        repo_id=repo_id,
        path_in_repo="chunks.json",
        path_or_fileobj=chunks_path,
        repo_type="dataset",
        token=token,
    )
    api.upload_file(
        repo_id=repo_id,
        path_in_repo="last_updated.txt",
        path_or_fileobj=ts_path,
        repo_type="dataset",
        token=token,
    )

    logger.info(f"Uploaded to HF Hub: {repo_id}")
    return repo_id


# ── Main Pipeline ──────────────────────────────────────────────────────────

def main():
    hf_token = os.environ.get("HF_TOKEN")
    if not hf_token:
        logger.error("HF_TOKEN environment variable required")
        logger.error("Usage: HF_TOKEN=hf_yourtoken python3 scripts/build_index.py")
        return

    total_start = time.time()

    # Step 1: Query SPARQL
    docs = query_all_documents()
    if not docs:
        logger.error("No documents found — SPARQL query returned empty")
        return
    logger.info(f"Documents to process: {len(docs)}")

    # Step 2: Download all documents in parallel
    logger.info(f"Downloading documents ({DOWNLOAD_WORKERS} workers)...")
    html_results = {}
    with ThreadPoolExecutor(max_workers=DOWNLOAD_WORKERS) as executor:
        future_map = {
            executor.submit(fetch_document_xhtml, doc): doc for doc in docs
        }
        for future in tqdm(as_completed(future_map), total=len(docs), desc="Downloading"):
            doc = future_map[future]
            try:
                html = future.result()
                if html:
                    html_results[doc["celex"]] = html
            except Exception as e:
                logger.debug(f"Failed {doc['celex']}: {e}")

    logger.info(f"Downloaded {len(html_results)}/{len(docs)} documents successfully")

    # Step 3: Parse all documents into chunks
    logger.info("Parsing HTML into chunks...")
    all_chunks = []
    for doc in tqdm(docs, desc="Parsing"):
        celex = doc["celex"]
        html = html_results.get(celex)
        if not html:
            continue
        chunks = parse_html_to_chunks(html, celex, doc["title"])
        all_chunks.extend(chunks)

    logger.info(f"Total chunks: {len(all_chunks)}")

    if not all_chunks:
        logger.error("No chunks produced — check parsing")
        return

    # Step 4: Embed all chunks
    vectors = embed_chunks(all_chunks)
    logger.info(f"Embedding complete: {vectors.shape}")

    # Step 5: Upload to HF Hub
    repo_id = upload_to_hub(vectors, all_chunks, HF_DATASET_NAME, hf_token)

    total_time = time.time() - total_start
    logger.info(f"Build complete in {total_time / 60:.1f} minutes")
    logger.info(f"Dataset: {repo_id}")
    logger.info(f"Documents: {len(html_results)} | Chunks: {len(all_chunks)} | Dims: {vectors.shape[1]}")


if __name__ == "__main__":
    main()
```

### Step 1.2 — Run the build

> **⏱ Estimated runtime: 3-5 hours.** This downloads ~30K-80K documents (depending on date filter) and embeds ~100K-200K chunks. You can leave it running overnight.

```bash
source ~/Desktop/EUProjects/.venv/bin/activate
cd ~/Desktop/EUProjects/eur-lex-ai-chat
HF_TOKEN=hf_your_write_token python3 scripts/build_index.py 2>&1 | tee build_log.txt
```

Expected output milestones:
```
Querying SPARQL for documents...
  Fetched 1000 documents so far...
  Fetched 2000 documents so far...
  ...
Total documents found: XXXX

Downloading documents (20 workers)...
Downloading: 100%|████████████| XXXX/XXXX [XX:XX<00:00]
Downloaded XXXX/XXXX documents successfully

Parsing HTML into chunks...
Total chunks: XXXX

Loading embedding model: all-MiniLM-L6-v2
Embedding XXXX chunks in batches of 128...
Embedding complete: (XXXX, 384)

Saved vectors: (XXXX, 384) (XX.X MB)
Saved chunks: XXXX items (XX.X MB)
Uploaded to HF Hub: yourusername/eurlex-chat-data

Build complete in XXX.X minutes
```

### Step 1.3 — Verify the upload

```bash
source ~/Desktop/EUProjects/.venv/bin/activate
python3 -c "
from huggingface_hub import hf_hub_download
import numpy as np, json

# Download vectors
vectors_path = hf_hub_download('yourusername/eurlex-chat-data', 'vectors.npy')
vectors = np.load(vectors_path)
print(f'Vectors: {vectors.shape}, dtype={vectors.dtype}')

# Download chunks
chunks_path = hf_hub_download('yourusername/eurlex-chat-data', 'chunks.json')
with open(chunks_path) as f:
    chunks = json.load(f)
print(f'Chunks: {len(chunks)}')
print(f'Sample: {chunks[0][\"text\"][:100]}...')
print(f'Source: CELEX {chunks[0][\"celex\"]} — {chunks[0][\"title\"][:60]}...')
"
```

If verification passes, **Phase 1 is complete.** The vector index is live on HuggingFace Hub.

---

## Phase 2: FastAPI Backend

**Goal:** A FastAPI server that loads the vector index from HF Hub at startup, accepts chat queries, finds relevant chunks via numpy KNN, calls Groq to generate answers with citations, and provides /health and /refresh endpoints.

### Step 2.1 — Write `backend/requirements.txt`

```
fastapi==0.136.1
uvicorn==0.47.0
numpy==2.4.6
httpx==0.28.1
huggingface_hub==1.15.0
```

### Step 2.2 — Write `backend/data_loader.py`

```python
"""Download and manage the vector index from HuggingFace Hub."""

import json
import logging
import os
import time
from datetime import datetime, timezone

import numpy as np
from huggingface_hub import hf_hub_download, HfApi

logger = logging.getLogger(__name__)

# HF dataset configuration
HF_USERNAME = os.environ.get("HF_USERNAME", "yourusername")
HF_DATASET = os.environ.get("HF_DATASET", "eurlex-chat-data")
HF_TOKEN = os.environ.get("HF_TOKEN", None)

REPO_ID = f"{HF_USERNAME}/{HF_DATASET}"

# Current index in memory
_index_data = {
    "vectors": None,
    "chunks": None,
    "last_updated": None,
    "loaded_at": None,
}


def download_index():
    """Download vectors.npy + chunks.json from HF Hub into memory."""
    logger.info(f"Downloading index from {REPO_ID}...")

    try:
        vectors_path = hf_hub_download(
            repo_id=REPO_ID,
            filename="vectors.npy",
            repo_type="dataset",
            token=HF_TOKEN,
        )
        chunks_path = hf_hub_download(
            repo_id=REPO_ID,
            filename="chunks.json",
            repo_type="dataset",
            token=HF_TOKEN,
        )
    except Exception as e:
        logger.error(f"Failed to download from HF Hub: {e}")
        raise

    vectors = np.load(vectors_path)
    with open(chunks_path, "r") as f:
        chunks = json.load(f)

    _index_data["vectors"] = vectors
    _index_data["chunks"] = chunks
    _index_data["last_updated"] = _get_last_updated()
    _index_data["loaded_at"] = datetime.now(timezone.utc).isoformat()

    logger.info(f"Index loaded: {vectors.shape[0]} vectors, {len(chunks)} chunks")
    return _index_data


def _get_last_updated():
    """Get the last_updated timestamp from HF Hub."""
    try:
        ts_path = hf_hub_download(
            repo_id=REPO_ID,
            filename="last_updated.txt",
            repo_type="dataset",
            token=HF_TOKEN,
        )
        with open(ts_path, "r") as f:
            return f.read().strip()
    except Exception:
        return None


def check_for_updates():
    """Check if the index has been updated on HF Hub since we loaded it."""
    current_remote = _get_last_updated()
    if current_remote and current_remote != _index_data["last_updated"]:
        logger.info(f"Remote index updated: {current_remote}")
        return True
    return False


def reload_index():
    """Re-download and reload the index."""
    return download_index()


def get_index():
    """Get the current in-memory index."""
    return _index_data


def get_stats():
    """Get index statistics."""
    data = get_index()
    return {
        "vectors": data["vectors"].shape if data["vectors"] is not None else None,
        "chunks": len(data["chunks"]) if data["chunks"] is not None else 0,
        "last_updated": data["last_updated"],
        "loaded_at": data["loaded_at"],
    }
```

### Step 2.3 — Write `backend/search.py`

```python
"""numpy KNN search over pre-loaded vectors."""

import logging

import numpy as np

logger = logging.getLogger(__name__)


def search(query_vector, top_k=10):
    """Find top-k most similar chunks using brute-force cosine similarity.

    Uses numpy dot product since vectors are L2-normalized.
    Returns list of dicts with chunk data and similarity score.
    """
    from data_loader import get_index

    index = get_index()
    vectors = index["vectors"]
    chunks = index["chunks"]

    if vectors is None or chunks is None:
        logger.error("Index not loaded")
        return []

    # Cosine similarity = dot product (vectors are normalized)
    if query_vector.ndim == 1:
        query_vector = query_vector.reshape(1, -1)

    similarities = np.dot(vectors, query_vector.T).flatten()

    # Get top-k indices
    top_indices = np.argpartition(similarities, -top_k)[-top_k:]
    top_indices = top_indices[np.argsort(-similarities[top_indices])]

    results = []
    for idx in top_indices:
        results.append({
            "score": float(similarities[idx]),
            "text": chunks[idx]["text"],
            "celex": chunks[idx]["celex"],
            "title": chunks[idx]["title"],
            "article": chunks[idx].get("article"),
        })

    return results
```

### Step 2.4 — Write `backend/rag.py`

```python
"""Build prompts and call Groq API for RAG."""

import json
import logging
import os
import re

import httpx

logger = logging.getLogger(__name__)

GROQ_API_KEY = os.environ.get("GROQ_API_KEY")
GROQ_MODEL = os.environ.get("GROQ_MODEL", "llama-3.3-70b-versatile")
GROQ_API_URL = "https://api.groq.com/openai/v1/chat/completions"

SYSTEM_PROMPT = """You are a legal AI assistant specialized in EU law. You help users understand EU legislation by answering their questions based on provided context from EUR-Lex documents.

Guidelines:
1. Answer based ONLY on the provided context. If the context doesn't contain enough information, say so.
2. Always cite the specific EUR-Lex document(s) you used with their CELEX numbers.
3. When citing articles, include the article number and CELEX number.
4. Keep answers clear and accessible — explain legal concepts in plain language.
5. If the user asks in a non-English language, respond in that language.
6. Do not make up legal citations or references. Only cite what's in the context.
7. Be honest about limitations — if you're unsure, say so."""


def build_prompt(query, context_chunks):
    """Build the prompt with context chunks and user query."""
    context_parts = []
    for i, chunk in enumerate(context_chunks):
        source = f"[{i+1}] CELEX {chunk['celex']}"
        if chunk.get("article"):
            source += f", Article {chunk['article']}"
        context_parts.append(f"Context {i+1} ({source}):\n{chunk['text']}")

    context_str = "\n\n---\n\n".join(context_parts)

    prompt = f"""Here are relevant excerpts from EU law documents:

{context_str}

Based on the above legal texts, please answer the following question:

{query}"""
    return prompt


def call_groq(prompt, max_retries=3):
    """Call Groq API with the prompt and return the response."""
    if not GROQ_API_KEY:
        logger.error("GROQ_API_KEY not set")
        return None

    headers = {
        "Authorization": f"Bearer {GROQ_API_KEY}",
        "Content-Type": "application/json",
    }

    payload = {
        "model": GROQ_MODEL,
        "messages": [
            {"role": "system", "content": SYSTEM_PROMPT},
            {"role": "user", "content": prompt},
        ],
        "temperature": 0.2,
        "max_tokens": 2048,
    }

    for attempt in range(max_retries):
        try:
            r = httpx.post(
                GROQ_API_URL,
                headers=headers,
                json=payload,
                timeout=30,
            )
            if r.status_code == 429:
                logger.warning(f"Groq rate limited (attempt {attempt + 1})")
                if attempt < max_retries - 1:
                    import time
                    time.sleep(2 ** attempt)
                    continue
            r.raise_for_status()
            data = r.json()
            return data["choices"][0]["message"]["content"]
        except httpx.HTTPStatusError as e:
            if e.response.status_code == 429 and attempt < max_retries - 1:
                import time
                time.sleep(2 ** attempt)
                continue
            logger.error(f"Groq API error: {e}")
            return None
        except Exception as e:
            logger.error(f"Groq API error: {e}")
            return None

    return None


def extract_citations(text):
    """Extract CELEX citations from the response text."""
    celex_pattern = r"CELEX\s+(\d{2,4}[A-Z0-9]+(?:\([A-Z0-9]+\))?(?:\([0-9]+\))?)"
    return re.findall(celex_pattern, text)


def answer_question(query, context_chunks):
    """Full RAG pipeline: build prompt → call Groq → return answer with citations."""
    prompt = build_prompt(query, context_chunks)
    answer = call_groq(prompt)

    if not answer:
        return {
            "answer": "Sorry, I couldn't generate an answer right now. Please try again.",
            "citations": [],
        }

    citations = extract_citations(answer)

    # Also add sources from our context
    source_citations = []
    seen = set()
    for chunk in context_chunks:
        if chunk["celex"] not in seen:
            seen.add(chunk["celex"])
            source_citations.append({
                "celex": chunk["celex"],
                "title": chunk["title"],
                "article": chunk.get("article"),
                "score": chunk["score"],
            })

    return {
        "answer": answer,
        "citations": citations,
        "sources": source_citations,
    }
```

### Step 2.5 — Write `backend/rate_limit.py`

```python
"""Per-IP rate limiting for the /chat endpoint."""

import time
from collections import defaultdict

# Rate limit configuration
MAX_REQUESTS_PER_IP = 20  # Max requests per window
WINDOW_SECONDS = 60       # Window size in seconds
MAX_GLOBAL_PER_MINUTE = 100  # Global max

_ip_counters = defaultdict(list)
_global_counters = []


def is_rate_limited(client_ip):
    """Check if a client IP has exceeded the rate limit.

    Returns True if rate limited, False if request is allowed.
    """
    now = time.time()
    window_start = now - WINDOW_SECONDS

    # Clean old entries
    _ip_counters[client_ip] = [
        t for t in _ip_counters[client_ip] if t > window_start
    ]

    # Check IP limit
    if len(_ip_counters[client_ip]) >= MAX_REQUESTS_PER_IP:
        return True

    # Check global limit
    global _global_counters
    _global_counters = [t for t in _global_counters if t > window_start]
    if len(_global_counters) >= MAX_GLOBAL_PER_MINUTE:
        return True

    # Record this request
    _ip_counters[client_ip].append(now)
    _global_counters.append(now)

    return False
```

### Step 2.6 — Write `backend/main.py`

```python
"""FastAPI application for EUR-Lex AI Chat."""

import logging
import os

from contextlib import asynccontextmanager

from fastapi import FastAPI, HTTPException, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse

logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
)
logger = logging.getLogger(__name__)


# Global model instance — loaded once at startup, reused for all requests
_embedding_model = None


def get_embedding_model():
    """Get the singleton embedding model instance."""
    global _embedding_model
    if _embedding_model is None:
        from sentence_transformers import SentenceTransformer
        logger.info("Loading embedding model: all-MiniLM-L6-v2")
        _embedding_model = SentenceTransformer("all-MiniLM-L6-v2")
    return _embedding_model


@asynccontextmanager
async def lifespan(app: FastAPI):
    """Load the vector index and embedding model on startup."""
    from data_loader import download_index

    logger.info("Starting up — loading index...")
    try:
        download_index()
        logger.info("Index loaded successfully")
    except Exception as e:
        logger.error(f"Failed to load index: {e}")

    # Pre-load embedding model
    logger.info("Pre-loading embedding model...")
    get_embedding_model()
    logger.info("Embedding model loaded")

    yield
    logger.info("Shutting down")


app = FastAPI(title="EUR-Lex AI Chat API", version="1.0.0", lifespan=lifespan)

# CORS — allow frontend on Vercel
app.add_middleware(
    CORSMiddleware,
    allow_origins=[
        "https://eurlex-chat.vercel.app",
        "http://localhost:4321",
        "http://localhost:3000",
    ],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


@app.get("/health")
async def health():
    """Health check endpoint — used by cron-job.org keepalive."""
    from data_loader import get_stats

    stats = get_stats()
    return {
        "status": "ok",
        "index_loaded": stats["vectors"] is not None,
        "vector_count": stats["vectors"][0] if stats["vectors"] else 0,
        "chunk_count": stats["chunks"],
        "last_updated": stats["last_updated"],
        "loaded_at": stats["loaded_at"],
    }


@app.get("/refresh")
async def refresh():
    """Check for index updates on HF Hub and reload if newer."""
    from data_loader import check_for_updates, reload_index, get_stats

    try:
        has_updates = check_for_updates()
        if has_updates:
            logger.info("New index available, reloading...")
            reload_index()
            return {"status": "reloaded", "message": "Index updated successfully"}
        else:
            stats = get_stats()
            return {"status": "current", "message": "Index is up to date"}
    except Exception as e:
        logger.error(f"Refresh failed: {e}")
        return JSONResponse(
            status_code=500,
            content={"status": "error", "message": str(e)},
        )


@app.post("/chat")
async def chat(request: Request):
    """Main chat endpoint. Accepts {query: string}, returns {answer, sources}."""
    from rate_limit import is_rate_limited
    from search import search
    from rag import answer_question

    # Get client IP
    client_ip = request.client.host if request.client else "unknown"

    # Rate limit check
    if is_rate_limited(client_ip):
        raise HTTPException(
            status_code=429,
            detail="Rate limit exceeded. Max 20 requests per minute per IP.",
        )

    # Parse request
    body = await request.json()
    query = body.get("query", "").strip()
    if not query:
        raise HTTPException(status_code=400, detail="Query is required")
    if len(query) > 2000:
        raise HTTPException(status_code=400, detail="Query too long (max 2000 chars)")

    # Embed query using the singleton model
    model = get_embedding_model()
    query_vector = model.encode(query, normalize_embeddings=True)

    # Search
    chunks = search(query_vector, top_k=10)
    if not chunks:
        return {
            "answer": "I don't have enough information to answer that question. Try asking about a specific EU regulation or directive.",
            "citations": [],
            "sources": [],
        }

    # Generate answer via RAG
    result = answer_question(query, chunks)
    return result


if __name__ == "__main__":
    import uvicorn
    port = int(os.environ.get("PORT", 8000))
    uvicorn.run("main:app", host="0.0.0.0", port=port, reload=False)
```

### Step 2.7 — Write `backend/startup.sh`

```bash
#!/bin/bash
# Render entry point — downloads index and starts uvicorn
set -e

cd "$(dirname "$0")"

echo "=== EUR-Lex AI Chat Backend Startup ==="
echo "Python: $(python3 --version)"

# The FastAPI app loads the index at startup via lifespan
echo "Starting uvicorn..."
exec uvicorn main:app --host 0.0.0.0 --port ${PORT:-8000} --workers 1
```

Make it executable:
```bash
chmod +x ~/Desktop/EUProjects/eur-lex-ai-chat/backend/startup.sh
```

### Step 2.8 — Test the backend locally

```bash
source ~/Desktop/EUProjects/.venv/bin/activate
cd ~/Desktop/EUProjects/eur-lex-ai-chat/backend

# Start server in background
uvicorn main:app --host 0.0.0.0 --port 8000 &
sleep 5

# Test health endpoint
curl -s http://localhost:8000/health | python3 -m json.tool

# Test chat endpoint
curl -s -X POST http://localhost:8000/chat \
  -H "Content-Type: application/json" \
  -d '{"query": "What are the requirements of the GDPR?"}' \
  | python3 -m json.tool

# Kill the server
kill %1 2>/dev/null
```

Expected `/health` response:
```json
{
  "status": "ok",
  "index_loaded": true,
  "vector_count": 123456,
  "chunk_count": 123456,
  "last_updated": "2026-05-20T12:00:00+00:00",
  "loaded_at": "2026-05-20T12:00:00+00:00"
}
```

### Step 2.9 — Create `backend/render.yaml` for Render deployment

```yaml
# render.yaml — Render Blueprint for EUR-Lex AI Chat backend
services:
  - type: web
    name: eurlex-chat-api
    runtime: python
    repo: https://github.com/yourusername/eur-lex-ai-chat
    branch: main
    buildCommand: pip install -r backend/requirements.txt
    startCommand: cd backend && ./startup.sh
    envVars:
      - key: GROQ_API_KEY
        sync: false
      - key: HF_TOKEN
        sync: false
      - key: HF_USERNAME
        value: yourusername
      - key: HF_DATASET
        value: eurlex-chat-data
      - key: PYTHON_VERSION
        value: 3.12.3
    healthCheckPath: /health
```

We'll set the environment variables in the Render dashboard (not in the yaml for security).

---

## Phase 3: Astro Frontend

**Goal:** A fully SEO-optimized Astro website with a React chat island. Ships zero-JS HTML by default. Chat widget is only interactive JS on the page.

### Step 3.1 — Scaffold Astro project

```bash
source ~/.nvm/nvm.sh
nvm use v22.22.3
cd ~/Desktop/EUProjects/eur-lex-ai-chat

# Create Astro project in frontend/ directory
npm create astro@latest frontend -- --template basics --typescript --no-install --no-git

cd frontend

# Install dependencies
npm install astro @astrojs/react @astrojs/tailwind @astrojs/sitemap tailwindcss react react-dom

# Add integrations
npx astro add react --yes
npx astro add tailwind --yes
npx astro add sitemap --yes
```

### Step 3.2 — Write `frontend/astro.config.mjs`

```javascript
import { defineConfig } from "astro/config";
import react from "@astrojs/react";
import tailwind from "@astrojs/tailwind";
import sitemap from "@astrojs/sitemap";

export default defineConfig({
  site: "https://eurlex-chat.vercel.app",
  integrations: [
    react(),
    tailwind(),
    sitemap({
      changefreq: "weekly",
      priority: 0.7,
      lastmod: new Date(),
    }),
  ],
});
```

### Step 3.3 — Write `frontend/tailwind.config.mjs`

```javascript
/** @type {import('tailwindcss').Config} */
export default {
  content: ["./src/**/*.{astro,html,js,jsx,mdx,tsx}"],
  theme: {
    extend: {
      colors: {
        eu: {
          blue: "#003399",
          gold: "#FFCC00",
          navy: "#002266",
          light: "#F0F4FF",
        },
      },
    },
  },
  plugins: [],
};
```

### Step 3.4 — Write `frontend/src/layouts/Base.astro`

```astro
---
// Base layout — used by all pages
// Includes: SEO meta tags, JSON-LD, nav, footer
export interface Props {
  title: string;
  description: string;
  canonical?: string;
  ogType?: string;
  jsonLd?: Record<string, any>;
}

const {
  title,
  description,
  canonical = "https://eurlex-chat.vercel.app",
  ogType = "website",
  jsonLd,
} = Astro.props;
---

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>{title} — EUR-Lex AI Chat</title>
    <meta name="description" content={description} />
    <link rel="canonical" href={canonical} />

    <!-- Open Graph -->
    <meta property="og:title" content={title} />
    <meta property="og:description" content={description} />
    <meta property="og:url" content={canonical} />
    <meta property="og:type" content={ogType} />
    <meta property="og:site_name" content="EUR-Lex AI Chat" />
    <meta property="og:locale" content="en_US" />

    <!-- Twitter Card -->
    <meta name="twitter:card" content="summary_large_image" />
    <meta name="twitter:title" content={title} />
    <meta name="twitter:description" content={description} />

    {/* JSON-LD */}
    {jsonLd && <script type="application/ld+json" set:html={JSON.stringify(jsonLd)} />}

    {/* Google Search Console verification */}
    <meta name="google-site-verification" content="YOUR_VERIFICATION_CODE" />
  </head>
  <body class="bg-white text-gray-900 min-h-screen flex flex-col">
    <!-- Navigation -->
    <nav class="bg-eu-blue text-white shadow-lg">
      <div class="max-w-6xl mx-auto px-4 py-3 flex items-center justify-between">
        <a href="/" class="text-xl font-bold tracking-tight">
          EUR-Lex AI Chat
        </a>
        <div class="flex gap-4 text-sm">
          <a href="/" class="hover:text-eu-gold transition">Home</a>
          <a href="/faq" class="hover:text-eu-gold transition">FAQ</a>
          <a href="/blog" class="hover:text-eu-gold transition">Blog</a>
        </div>
      </div>
    </nav>

    <!-- Main content -->
    <main class="flex-1">
      <slot />
    </main>

    <!-- Footer -->
    <footer class="bg-gray-50 border-t py-8 mt-12">
      <div class="max-w-6xl mx-auto px-4 text-center text-sm text-gray-600">
        <p class="mb-2">
          EUR-Lex AI Chat — An open-source tool for exploring EU law.
          Uses data from
          <a href="https://eur-lex.europa.eu/" class="text-eu-blue underline" target="_blank" rel="noopener">EUR-Lex</a>
          via the Cellar API.
        </p>
        <p>
          <a href="https://github.com/yourusername/eur-lex-ai-chat" class="text-eu-blue underline" target="_blank" rel="noopener">Source code (MIT)</a>
          &middot;
          <a href="/faq" class="text-eu-blue underline">FAQ</a>
          &middot;
          <a href="/blog" class="text-eu-blue underline">Blog</a>
        </p>
      </div>
    </footer>
  </body>
</html>
```

### Step 3.5 — Write `frontend/src/components/SeoHead.astro`

```astro
---
// Helper component for page-specific SEO metadata
export interface Props {
  pageTitle: string;
  pageDescription: string;
  pageUrl?: string;
  jsonLd?: Record<string, any>;
}

const {
  pageTitle,
  pageDescription,
  pageUrl = "https://eurlex-chat.vercel.app",
  jsonLd,
} = Astro.props;
---

<!-- Page title suffix -->
{pageTitle && <title>{pageTitle} — EUR-Lex AI Chat</title>}
{pageDescription && <meta name="description" content={pageDescription} />}
<link rel="canonical" href={pageUrl} />
<meta property="og:title" content={pageTitle} />
<meta property="og:description" content={pageDescription} />
<meta property="og:url" content={pageUrl} />

{jsonLd && <script type="application/ld+json" set:html={JSON.stringify(jsonLd)} />}
```

### Step 3.6 — Write `frontend/src/components/ChatWidget.jsx`

```jsx
import { useState, useRef, useEffect } from "react";

const API_URL = import.meta.env.PUBLIC_API_URL || "http://localhost:8000";

export default function ChatWidget() {
  const [messages, setMessages] = useState([
    {
      role: "assistant",
      content:
        "Hi! I'm an AI assistant specialized in EU law. Ask me anything about EU regulations, directives, or legislation.",
    },
  ]);
  const [input, setInput] = useState("");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const messagesEndRef = useRef(null);

  useEffect(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
  }, [messages]);

  const sendMessage = async () => {
    const query = input.trim();
    if (!query || loading) return;

    setInput("");
    setError(null);
    setMessages((prev) => [...prev, { role: "user", content: query }]);
    setLoading(true);

    try {
      const res = await fetch(`${API_URL}/chat`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ query }),
      });

      if (!res.ok) {
        const data = await res.json();
        throw new Error(data.detail || `Error ${res.status}`);
      }

      const data = await res.json();

      // Format answer with sources
      let answer = data.answer;
      if (data.sources && data.sources.length > 0) {
        answer += "\n\n**Sources:**";
        for (const s of data.sources) {
          answer += `\n- CELEX ${s.celex}: ${s.title}`;
          if (s.article) answer += ` (Article ${s.article})`;
        }
      }

      setMessages((prev) => [
        ...prev,
        { role: "assistant", content: answer },
      ]);
    } catch (err) {
      setError(err.message);
      setMessages((prev) => [
        ...prev,
        {
          role: "assistant",
          content: `Sorry, I encountered an error: ${err.message}. Please try again.`,
        },
      ]);
    } finally {
      setLoading(false);
    }
  };

  const handleKeyDown = (e) => {
    if (e.key === "Enter" && !e.shiftKey) {
      e.preventDefault();
      sendMessage();
    }
  };

  return (
    <div className="bg-white rounded-xl shadow-lg border border-gray-200 overflow-hidden max-w-2xl mx-auto">
      {/* Chat header */}
      <div className="bg-eu-blue text-white px-4 py-3 font-semibold">
        Ask about EU Law
      </div>

      {/* Messages */}
      <div className="h-96 overflow-y-auto p-4 space-y-3 bg-gray-50">
        {messages.map((msg, i) => (
          <div
            key={i}
            className={`flex ${msg.role === "user" ? "justify-end" : "justify-start"}`}
          >
            <div
              className={`max-w-[80%] rounded-lg px-4 py-2 text-sm whitespace-pre-wrap ${
                msg.role === "user"
                  ? "bg-eu-blue text-white"
                  : "bg-white border border-gray-200 text-gray-800"
              }`}
            >
              {msg.content}
            </div>
          </div>
        ))}
        {loading && (
          <div className="flex justify-start">
            <div className="bg-white border border-gray-200 rounded-lg px-4 py-2 text-sm text-gray-500 italic">
              Thinking...
            </div>
          </div>
        )}
        <div ref={messagesEndRef} />
      </div>

      {/* Input */}
      <div className="border-t border-gray-200 p-3 flex gap-2">
        <textarea
          value={input}
          onChange={(e) => setInput(e.target.value)}
          onKeyDown={handleKeyDown}
          placeholder="Ask about EU law..."
          rows={1}
          className="flex-1 border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-eu-blue resize-none"
          disabled={loading}
        />
        <button
          onClick={sendMessage}
          disabled={loading || !input.trim()}
          className="bg-eu-blue text-white px-4 py-2 rounded-lg text-sm font-medium hover:bg-eu-navy transition disabled:opacity-50 disabled:cursor-not-allowed"
        >
          Send
        </button>
      </div>

      {error && (
        <div className="bg-red-50 text-red-700 text-xs px-4 py-2 border-t border-red-200">
          {error}
        </div>
      )}
    </div>
  );
}
```

### Step 3.7 — Write `frontend/src/pages/index.astro`

```astro
---
import Base from "../layouts/Base.astro";
import ChatWidget from "../components/ChatWidget";

const jsonLd = {
  "@context": "https://schema.org",
  "@type": "SoftwareApplication",
  name: "EUR-Lex AI Chat",
  applicationCategory: "WebApplication",
  operatingSystem: "Web",
  description:
    "Chat about EU law in plain English. Get answers with citations to real EUR-Lex documents.",
  url: "https://eurlex-chat.vercel.app",
  offers: {
    "@type": "Offer",
    price: "0",
    priceCurrency: "EUR",
  },
};
---

<Base
  title="EUR-Lex AI Chat — Ask EU Law Questions in Plain English"
  description="Free AI-powered chat over EU legislation. Ask questions about GDPR, AI Act, Digital Markets Act, and thousands of other EU regulations and directives. Get answers with citations."
  jsonLd={jsonLd}
>
  <!-- Hero section -->
  <section class="bg-gradient-to-br from-eu-blue to-eu-navy text-white">
    <div class="max-w-4xl mx-auto px-4 py-16 text-center">
      <h1 class="text-3xl md:text-4xl font-bold mb-4">
        Ask EU Law Questions in Plain English
      </h1>
      <p class="text-lg text-blue-200 max-w-2xl mx-auto mb-8">
        EUR-Lex AI Chat helps you understand EU regulations, directives, and legislation.
        Ask any question and get answers with citations to real EUR-Lex documents.
      </p>
      <div class="flex justify-center gap-3 flex-wrap">
        <span class="bg-white/10 rounded-full px-4 py-1.5 text-sm">Free</span>
        <span class="bg-white/10 rounded-full px-4 py-1.5 text-sm">No account needed</span>
        <span class="bg-white/10 rounded-full px-4 py-1.5 text-sm">20 queries/day</span>
        <span class="bg-white/10 rounded-full px-4 py-1.5 text-sm">Open source</span>
      </div>
    </div>
  </section>

  <!-- Chat section -->
  <section class="max-w-4xl mx-auto px-4 py-12">
    <h2 class="text-2xl font-bold text-center mb-8">Try It Now</h2>
    <ChatWidget client:load />
  </section>

  <!-- Features section -->
  <section class="bg-gray-50 py-12">
    <div class="max-w-4xl mx-auto px-4">
      <h2 class="text-2xl font-bold text-center mb-8">How It Works</h2>
      <div class="grid md:grid-cols-3 gap-6">
        <div class="bg-white rounded-xl p-6 shadow-sm border border-gray-100">
          <div class="text-eu-blue text-2xl font-bold mb-2">1</div>
          <h3 class="font-semibold mb-2">Ask a Question</h3>
          <p class="text-sm text-gray-600">
            Type any question about EU law in plain language. No legal knowledge needed.
          </p>
        </div>
        <div class="bg-white rounded-xl p-6 shadow-sm border border-gray-100">
          <div class="text-eu-blue text-2xl font-bold mb-2">2</div>
          <h3 class="font-semibold mb-2">AI Searches EU Law</h3>
          <p class="text-sm text-gray-600">
            We search over 100,000 passages from EUR-Lex documents to find relevant legal texts.
          </p>
        </div>
        <div class="bg-white rounded-xl p-6 shadow-sm border border-gray-100">
          <div class="text-eu-blue text-2xl font-bold mb-2">3</div>
          <h3 class="font-semibold mb-2">Get Cited Answers</h3>
          <p class="text-sm text-gray-600">
            Receive clear answers with CELEX numbers and article references so you can verify the source.
          </p>
        </div>
      </div>
    </div>
  </section>

  <!-- Example questions section -->
  <section class="py-12">
    <div class="max-w-4xl mx-auto px-4">
      <h2 class="text-2xl font-bold text-center mb-8">Example Questions You Can Ask</h2>
      <div class="grid md:grid-cols-2 gap-4">
        <div class="bg-white border border-gray-200 rounded-lg p-4 text-sm text-gray-700">
          "What are the data protection requirements under the GDPR?"
        </div>
        <div class="bg-white border border-gray-200 rounded-lg p-4 text-sm text-gray-700">
          "When does the EU AI Act come into force?"
        </div>
        <div class="bg-white border border-gray-200 rounded-lg p-4 text-sm text-gray-700">
          "What are the obligations for gatekeepers under the DMA?"
        </div>
        <div class="bg-white border border-gray-200 rounded-lg p-4 text-sm text-gray-700">
          "What is a CELEX number and how do I use it?"
        </div>
      </div>
    </div>
  </section>
</Base>
```

### Step 3.8 — Write `frontend/src/pages/faq.astro`

```astro
---
import Base from "../layouts/Base.astro";

const faqQuestions = [
  {
    question: "What is EUR-Lex?",
    answer:
      "EUR-Lex is the official online portal for European Union law. It provides access to the Official Journal of the EU, treaties, legislation, case law, and other legal documents. EUR-Lex AI Chat uses data from EUR-Lex via the Cellar API.",
  },
  {
    question: "What is a CELEX number?",
    answer:
      "A CELEX number is a unique identifier assigned to every document in EUR-Lex. It follows a specific format: for example, 32019R0947 breaks down as 3 (sector: legislation), 2019 (year), R (regulation), 0947 (document number). CELEX numbers are used to cite and locate EU legal documents precisely.",
  },
  {
    question: "How accurate is the AI?",
    answer:
      "The AI searches over actual EUR-Lex documents and cites its sources with CELEX numbers. However, you should always verify important legal information by checking the official documents on EUR-Lex. The AI can make mistakes and should not be used as a substitute for professional legal advice.",
  },
  {
    question: "Is this service free?",
    answer:
      "Yes, completely free. You can make up to 20 queries per day per IP address. There are no accounts, no subscriptions, and no hidden costs. This is an open-source project built with free cloud services.",
  },
  {
    question: "What documents are included?",
    answer:
      "The index includes EU regulations, directives, and implementing acts published since 2000, available in English. This covers over 25 years of EU legislation, including major laws like the GDPR, AI Act, Digital Markets Act, and thousands more.",
  },
  {
    question: "How often is the data updated?",
    answer:
      "The index is refreshed daily via automated GitHub Actions workflows. New regulations and amendments are picked up within 24 hours of publication in the Official Journal.",
  },
  {
    question: "What is the Cellar API?",
    answer:
      "The Cellar API is the official Semantic Web interface for EUR-Lex. It provides structured access to EU legal documents via SPARQL queries and REST endpoints. This project uses Cellar APIs exclusively, not web scraping.",
  },
  {
    question: "What does a CELEX number look like?",
    answer:
      "CELEX numbers have a standard format: 32019R0947 (a regulation from 2019), 32016R0679 (the GDPR), or 32024R1689 (the AI Act). The first digit indicates the sector, the next four digits are the year, followed by a document type code and number.",
  },
  {
    question: "Can I cite answers from this tool in legal documents?",
    answer:
      "No. This tool is for informational purposes only. Always verify legal information against the official text published in the Official Journal of the EU (OJEU). The AI-generated answers should not be used as legal authority.",
  },
  {
    question: "What is the difference between a regulation and a directive?",
    answer:
      "A regulation is a binding legislative act that must be applied in its entirety across all EU member states. A directive is a legislative act that sets a goal that all EU countries must achieve, but it's up to the individual countries to devise their own laws to reach that goal.",
  },
  {
    question: "What is the GDPR?",
    answer:
      "The General Data Protection Regulation (GDPR, Regulation 2016/679) is the EU's primary data protection law. It governs how personal data must be collected, processed, stored, and protected by organizations operating in the EU.",
  },
  {
    question: "What is the EU AI Act?",
    answer:
      "The EU AI Act (Regulation 2024/1689) is the world's first comprehensive legal framework for artificial intelligence. It categorizes AI systems by risk level and imposes requirements ranging from transparency obligations for minimal-risk AI to bans on unacceptable-risk AI.",
  },
  {
    question: "What is the Digital Markets Act (DMA)?",
    answer:
      "The Digital Markets Act (Regulation 2022/1925) is an EU law that aims to make digital markets fairer and more contestable. It sets obligations for large online platforms designated as 'gatekeepers' to prevent anti-competitive practices.",
  },
  {
    question: "What is the Digital Services Act (DSA)?",
    answer:
      "The Digital Services Act (Regulation 2022/2065) is an EU law that regulates online intermediary platforms. It sets rules for content moderation, transparency, and accountability of platforms from the largest social networks to small online marketplaces.",
  },
  {
    question: "Where can I find the official text of an EU regulation?",
    answer:
      "The official text is published in the Official Journal of the EU (OJEU) and is available on EUR-Lex at eur-lex.europa.eu. You can search by CELEX number, title, or date. The OJ L series contains legislation, while the OJ C series contains information and notices.",
  },
  {
    question: "Can I search for documents from a specific year?",
    answer:
      "Yes. The index covers documents from 2000 onwards. You can ask questions like 'What regulations were passed in 2023 regarding digital platforms?' and the AI will search the relevant documents.",
  },
  {
    question: "How do I find the CELEX number for a specific law?",
    answer:
      "You can search directly on this chat by asking 'What is the CELEX number for the GDPR?' or 'Find CELEX for the AI Act.' The AI will return the CELEX number along with the title and other metadata.",
  },
  {
    question: "What languages are supported?",
    answer:
      "The index currently contains documents in English. However, you can ask questions in any language, and the AI will respond in the language you used. The underlying legal texts are in English.",
  },
  {
    question: "Can I download or export the results?",
    answer:
      "Currently, the chat provides answers with citations on screen. You can copy the text directly. We're working on adding export functionality in future updates.",
  },
  {
    question: "Is this project open source?",
    answer:
      "Yes! The full source code is available on GitHub under the MIT license. You can view, fork, and contribute to the project. The data pipeline, AI backend, and frontend are all open source.",
  },
  {
    question: "What happens if I reach the daily limit?",
    answer:
      "After 20 queries in a minute, you'll see a rate limit message. Wait a minute and try again. This limit helps keep the service free and available for everyone.",
  },
];

const faqJsonLd = {
  "@context": "https://schema.org",
  "@type": "FAQPage",
  mainEntity: faqQuestions.map((q) => ({
    "@type": "Question",
    name: q.question,
    acceptedAnswer: {
      "@type": "Answer",
      text: q.answer,
    },
  })),
};
---

<Base
  title="Frequently Asked Questions"
  description="Answers to common questions about EUR-Lex AI Chat, CELEX numbers, EU regulations, directives, GDPR, AI Act, DMA, DSA, and how to use the service."
  canonical="https://eurlex-chat.vercel.app/faq"
  jsonLd={faqJsonLd}
>
  <div class="max-w-3xl mx-auto px-4 py-12">
    <h1 class="text-3xl font-bold mb-2">Frequently Asked Questions</h1>
    <p class="text-gray-600 mb-8">
      Everything you need to know about EUR-Lex AI Chat and EU law.
    </p>

    <div class="space-y-4">
      {faqQuestions.map((item) => (
        <details class="bg-white border border-gray-200 rounded-lg overflow-hidden">
          <summary class="px-4 py-3 cursor-pointer font-medium hover:bg-gray-50 transition">
            {item.question}
          </summary>
          <div class="px-4 py-3 text-sm text-gray-700 border-t border-gray-100">
            {item.answer}
          </div>
        </details>
      ))}
    </div>
  </div>
</Base>
```

### Step 3.9 — Write blog listing page `frontend/src/pages/blog/index.astro`

```astro
---
import Base from "../../layouts/Base.astro";

const posts = await Astro.glob("./posts/*.md");
// Sort by date descending
posts.sort((a, b) => new Date(b.frontmatter.date) - new Date(a.frontmatter.date));
---

<Base
  title="Blog"
  description="Articles about EU law, including guides to GDPR, AI Act, CELEX numbers, and other European legislation topics."
  canonical="https://eurlex-chat.vercel.app/blog"
>
  <div class="max-w-3xl mx-auto px-4 py-12">
    <h1 class="text-3xl font-bold mb-2">Blog</h1>
    <p class="text-gray-600 mb-8">Articles about EU law and how to use EUR-Lex AI Chat.</p>

    <div class="space-y-6">
      {posts.map((post) => (
        <article class="bg-white border border-gray-200 rounded-lg p-6 hover:shadow-md transition">
          <time class="text-xs text-gray-500">{post.frontmatter.date}</time>
          <h2 class="text-xl font-semibold mt-1 mb-2">
            <a href={post.url} class="text-eu-blue hover:underline">{post.frontmatter.title}</a>
          </h2>
          <p class="text-sm text-gray-600">{post.frontmatter.description}</p>
        </article>
      ))}
    </div>
  </div>
</Base>
```

### Step 3.10 — Create blog post directory and write first post

```bash
mkdir -p ~/Desktop/EUProjects/eur-lex-ai-chat/frontend/src/pages/blog/posts
```

Write blog posts in Markdown. Save each as `.md` in `frontend/src/pages/blog/posts/`. Each needs frontmatter with `title`, `description`, `date`, and optionally `tags`.

### Step 3.11 — Test the frontend locally

```bash
source ~/.nvm/nvm.sh
nvm use v22.22.3
cd ~/Desktop/EUProjects/eur-lex-ai-chat/frontend
npm run dev
```

Open http://localhost:4321 in a browser. Verify:
- Landing page renders with chat widget
- FAQ page loads with all 20 questions expandable
- Blog index lists posts
- Test the chat widget (it will try to connect to local backend)

### Step 3.12 — Create `vercel.json` (optional)

For custom Vercel config:
```json
{
  "buildCommand": "npm run build",
  "outputDirectory": "dist",
  "framework": "astro"
}
```

---

## Phase 4: SEO Content

**Goal:** Write the FAQ content (already done in Phase 3 — 20 questions) and 3 blog posts. This is pure content writing with Markdown.

### Step 4.1 — Blog Post 1: eu-ai-act-explained.md

```markdown
---
title: "EU AI Act Explained: What You Need to Know"
description: "A comprehensive guide to the EU AI Act (Regulation 2024/1689) — the world's first legal framework for artificial intelligence. Learn about risk categories, requirements, and timelines."
date: "2026-05-20"
tags: ["AI Act", "artificial intelligence", "regulation"]
---

The EU AI Act (Regulation 2024/1689) entered into force on August 1, 2024, marking a historic moment in technology regulation. It is the world's first comprehensive legal framework for artificial intelligence.

## What Is the AI Act?

The AI Act establishes a risk-based classification system for AI systems:

- **Unacceptable risk** — AI systems that pose a clear threat to safety, livelihoods, or rights (banned)
- **High risk** — AI systems in critical areas like healthcare, law enforcement, employment (strict requirements)
- **Limited risk** — AI systems with specific transparency obligations (e.g., chatbots must disclose they are AI)
- **Minimal risk** — All other AI systems (no additional obligations)

## Key Requirements

High-risk AI systems must comply with:

1. **Risk management system** (Article 9)
2. **Data governance** — training data must be relevant, representative, and free from errors (Article 10)
3. **Technical documentation** — detailed description of the system's development and capabilities (Article 11)
4. **Record-keeping** — automatic logging of system events (Article 12)
5. **Transparency** — users must be informed they are interacting with AI (Article 13)
6. **Human oversight** — humans must be able to override or stop the system (Article 14)
7. **Accuracy, robustness, and cybersecurity** (Article 15)

## Timeline

- **August 2024**: AI Act enters into force
- **February 2025**: Prohibitions on unacceptable risk AI apply
- **August 2025**: Rules for general-purpose AI models apply
- **August 2026**: Most rules apply (including high-risk AI systems)
- **August 2027**: Rules for high-risk AI systems in certain product categories apply

## CELEX Number

The AI Act has CELEX number **32024R1689**. You can find the full text on EUR-Lex at this CELEX identifier.

## How EUR-Lex AI Chat Can Help

Use EUR-Lex AI Chat to ask specific questions about the AI Act, such as:
- "What are the transparency obligations for chatbots under the AI Act?"
- "Which AI systems are banned under the AI Act?"
- "What are the penalties for non-compliance with the AI Act?"
```

### Step 4.2 — Blog Post 2: gdpr-guide.md

```markdown
---
title: "GDPR Explained: A Practical Guide to EU Data Protection Law"
description: "Everything you need to know about the General Data Protection Regulation (GDPR, Regulation 2016/679). Covers data subject rights, obligations for controllers and processors, and key requirements."
date: "2026-05-20"
tags: ["GDPR", "data protection", "privacy", "regulation"]
---

The General Data Protection Regulation (GDPR, Regulation 2016/679) is the European Union's flagship data protection law. Since its application on May 25, 2018, it has become the global benchmark for privacy regulation.

## Scope

The GDPR applies to:

- Organizations established in the EU that process personal data
- Organizations outside the EU that offer goods or services to individuals in the EU
- Organizations outside the EU that monitor the behavior of individuals in the EU

## Key Principles (Article 5)

Personal data must be:

1. **Lawfulness, fairness, and transparency** — processed lawfully, fairly, and transparently
2. **Purpose limitation** — collected for specified, explicit, and legitimate purposes
3. **Data minimization** — adequate, relevant, and limited to what is necessary
4. **Accuracy** — accurate and kept up to date
5. **Storage limitation** — kept no longer than necessary
6. **Integrity and confidentiality** — processed securely
7. **Accountability** — the controller is responsible for compliance

## Data Subject Rights (Chapter III)

Individuals have the right to:

- **Access** their personal data (Article 15)
- **Rectification** of inaccurate data (Article 16)
- **Erasure** ('right to be forgotten') (Article 17)
- **Restriction of processing** (Article 18)
- **Data portability** (Article 20)
- **Object** to processing (Article 21)

## CELEX Number

The GDPR has CELEX number **32016R0679**. You can find the full text on EUR-Lex at this CELEX identifier.

## Use EUR-Lex AI Chat

Ask questions like:
- "What are the requirements for data protection impact assessments under the GDPR?"
- "When can personal data be transferred outside the EU?"
- "What are the penalties for GDPR violations?"
```

### Step 4.3 — Blog Post 3: what-is-celex.md

```markdown
---
title: "What Is a CELEX Number? A Complete Guide to EUR-Lex Document Identifiers"
description: "Learn what CELEX numbers are, how to read them, and how to use them to find EU legal documents on EUR-Lex. Includes examples for GDPR, AI Act, and more."
date: "2026-05-20"
tags: ["CELEX", "EUR-Lex", "document identifiers", "guide"]
---

If you've ever tried to cite an EU legal document precisely, you've probably encountered CELEX numbers. This guide explains what they are, how they work, and how to use them.

## What Is a CELEX Number?

A CELEX number is a unique identifier assigned to every document in EUR-Lex, the official online portal for EU law. Think of it as a digital fingerprint for EU legal documents — no two documents share the same CELEX number.

## How to Read a CELEX Number

A CELEX number follows a specific format. Let's break down the GDPR's CELEX number: **32016R0679**

| Digit(s) | Meaning | Example |
|----------|---------|---------|
| 1st digit | Sector | 3 = Legislation |
| 2nd-5th digits | Year | 2016 |
| Letter(s) | Document type | R = Regulation |
| Remaining digits | Document number | 0679 |

### Sector Codes

- **1**: Treaties
- **2**: International agreements
- **3**: Legislation (most common for our purposes)
- **4**: Complementary legislation
- **5**: Preparatory acts
- **6**: Case law
- **7**: National transposition measures
- **8**: References
- **9**: Parliamentary questions
- **0**: Consolidated texts

### Document Type Letters

- **R**: Regulation
- **L**: Directive
- **D**: Decision
- **H**: Recommendation
- **A**: Opinion
- **C**: Cost of the Treaties

## Examples of Common CELEX Numbers

| Law | CELEX Number |
|-----|-------------|
| GDPR | 32016R0679 |
| EU AI Act | 32024R1689 |
| Digital Markets Act | 32022R1925 |
| Digital Services Act | 32022R2065 |
| Uber ruling (ECJ) | 62017CJ0434 |

## How to Use CELEX Numbers

1. **Search**: Go to eur-lex.europa.eu and paste a CELEX number into the search box
2. **Cite**: Use CELEX numbers in legal citations for precision
3. **API**: Developers can use CELEX numbers to retrieve documents programmatically via the Cellar API

## Use EUR-Lex AI Chat

Ask questions like:
- "What is the CELEX number for the GDPR?"
- "Find the CELEX number for the Digital Markets Act"
- "How do I search for documents by CELEX number?"
```

### Step 4.4 — Create `frontend/public/robots.txt`

```
User-agent: *
Allow: /
Sitemap: https://eurlex-chat.vercel.app/sitemap-index.xml
```

---

## Phase 5: GitHub Actions Automation

**Goal:** A daily GitHub Actions workflow that scrapes EUR-Lex for new/changed documents, processes them incrementally, and uploads the updated index to HuggingFace Hub.

### Step 5.1 — Write `scripts/update_index.py`

This incremental update script:
1. Gets the current last_updated timestamp from HF Hub
2. Queries SPARQL for documents modified since that timestamp
3. Downloads and processes only new/changed documents
4. Merges with existing index
5. Re-embeds (only new vectors)
6. Uploads updated index

```python
#!/usr/bin/env python3
"""
update_index.py — Incremental daily update of the EUR-Lex vector index.
Runs in GitHub Actions on a schedule.

Pipeline:
  1. Download current index from HF Hub
  2. Query SPARQL for documents modified since last update
  3. Only process new/changed documents
  4. Merge with existing index (replace changed, append new)
  5. Upload updated index to HF Hub

Usage:
  HF_TOKEN=hf_yourtoken python3 scripts/update_index.py
"""

import json
import logging
import os
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
from datetime import datetime, timezone

import numpy as np
import requests
from huggingface_hub import hf_hub_download, HfApi, upload_file
from tqdm import tqdm

logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
logger = logging.getLogger(__name__)

SPARQL_ENDPOINT = "https://publications.europa.eu/webapi/rdf/sparql"
DOWNLOAD_WORKERS = 10
EMBEDDING_MODEL = "all-MiniLM-L6-v2"
HF_USERNAME = os.environ.get("HF_USERNAME", "yourusername")
HF_DATASET = os.environ.get("HF_DATASET", "eurlex-chat-data")
HF_TOKEN = os.environ.get("HF_TOKEN")
REPO_ID = f"{HF_USERNAME}/{HF_DATASET}"


def download_current_index():
    """Download the current vectors.npy and chunks.json from HF Hub."""
    logger.info("Downloading current index from HF Hub...")
    vectors_path = hf_hub_download(REPO_ID, "vectors.npy", repo_type="dataset", token=HF_TOKEN)
    chunks_path = hf_hub_download(REPO_ID, "chunks.json", repo_type="dataset", token=HF_TOKEN)
    ts_path = hf_hub_download(REPO_ID, "last_updated.txt", repo_type="dataset", token=HF_TOKEN)

    vectors = np.load(vectors_path)
    with open(chunks_path, "r") as f:
        chunks = json.load(f)
    with open(ts_path, "r") as f:
        last_updated = f.read().strip()

    logger.info(f"Current index: {vectors.shape[0]} vectors, {len(chunks)} chunks")
    logger.info(f"Last updated: {last_updated}")
    return vectors, chunks, last_updated


def query_modified_documents(since_date):
    """Query SPARQL for documents modified since the given date."""
    query = f"""
PREFIX cdm: <http://publications.europa.eu/ontology/cdm#>
PREFIX dc: <http://purl.org/dc/elements/1.1/>

SELECT DISTINCT ?doc ?type ?celex ?title ?date
WHERE {{
    ?doc cdm:work_has_resource-type ?type .
    ?doc cdm:resource_legal_id_celex ?celex .
    ?doc dc:title ?title .
    ?doc cdm:work_date_lastUpdate ?date .
    FILTER(LANG(?title) = "en")
    FILTER(?date >= "{since_date}"^^xsd:dateTime)
}}
ORDER BY DESC(?date)
"""
    r = requests.get(
        SPARQL_ENDPOINT,
        params={"query": query, "format": "json"},
        timeout=60,
    )
    r.raise_for_status()
    data = r.json()
    docs = []
    for b in data["results"]["bindings"]:
        docs.append({
            "celex": b["celex"]["value"],
            "title": b["title"]["value"],
            "date": b["date"]["value"],
            "type": b["type"]["value"].split("/")[-1],
        })
    logger.info(f"Modified documents since {since_date}: {len(docs)}")
    return docs


def fetch_document_html(celex):
    """Fetch XHTML content via Cellar RDF graph traversal."""
    try:
        from xml.etree import ElementTree as ET
        ns = {
            "rdf": "http://www.w3.org/1999/02/22-rdf-syntax-ns#",
            "cdm": "http://publications.europa.eu/ontology/cdm#",
        }

        work_url = f"http://publications.europa.eu/resource/celex/{celex}?language=eng"
        r = requests.get(work_url, timeout=30)
        r.raise_for_status()
        root = ET.fromstring(r.content)

        expressions = root.findall(".//cdm:work_has_expression", ns)
        expression_url = None
        for expr in expressions:
            resource = expr.get("{http://www.w3.org/1999/02/22-rdf-syntax-ns#}resource")
            if resource and resource.endswith(".ENG"):
                expression_url = resource
                break
        if not expression_url and expressions:
            resource = expressions[0].get("{http://www.w3.org/1999/02/22-rdf-syntax-ns#}resource")
            if resource:
                expression_url = resource
        if not expression_url:
            return None

        r2 = requests.get(expression_url, timeout=30)
        r2.raise_for_status()
        expr_root = ET.fromstring(r2.content)

        manifestations = expr_root.findall(".//cdm:expression_manifested_by_manifestation", ns)
        xhtml_url = None
        for manif in manifestations:
            resource = manif.get("{http://www.w3.org/1999/02/22-rdf-syntax-ns#}resource")
            if resource and (resource.endswith(".xhtml") or resource.endswith(".fmx4")):
                xhtml_url = resource
                break

        if not xhtml_url:
            return None

        r3 = requests.get(xhtml_url, headers={"Accept": "application/xhtml+xml, text/html"}, timeout=30)
        r3.raise_for_status()
        return r3.text
    except Exception as e:
        logger.warning(f"Failed to fetch {celex}: {e}")
        return None


def parse_to_chunks(html, celex, title):
    """Parse HTML into text chunks.

    ⚠️ Uses _parse_html_with_beautifulsoup directly (eurlxp parse_html has
    a Polars schema bug with conditional modifier field).
    """
    try:
        from eurlxp.parser import _parse_html_with_beautifulsoup as internal_parse
        import polars as pl
        results = internal_parse(html)
    except Exception:
        return []

    if not results:
        return []

    # Fixed-schema conversion (bypasses eurlxp parse_html bug)
    records = []
    for r in results:
        records.append({
            'text': r.text, 'type': r.item_type, 'ref': str(r.ref),
            'modifier': r.modifier, 'document': r.context.document,
            'article': r.context.article, 'article_subtitle': r.context.article_subtitle,
            'paragraph': r.context.paragraph, 'group': r.context.group,
            'section': r.context.section,
        })

    df = pl.DataFrame(records, schema={
        'text': pl.Utf8, 'type': pl.Utf8, 'ref': pl.Utf8,
        'modifier': pl.Utf8, 'document': pl.Utf8, 'article': pl.Utf8,
        'article_subtitle': pl.Utf8, 'paragraph': pl.Utf8,
        'group': pl.Utf8, 'section': pl.Utf8,
    })

    if len(df) == 0:
        return []

    chunks = []
    current_article = None
    current_text = []

    for row in df.to_dicts():
        text = row.get("text", "").strip()
        row_type = row.get("type", "")
        article = row.get("article")

        if not text or len(text) < 40:
            continue

        if row_type in ("doc-title", "art-subtitle", "group-title", "section-title"):
            continue
        if row.get("modifier") in ("note", "signatory"):
            continue

        current_text.append(text)

    if current_text:
        chunk_text = " ".join(current_text)
        if len(chunk_text) > 50:
            chunks.append({
                "text": chunk_text,
                "celex": celex,
                "title": title,
                "article": current_article,
                "type": "article",
            })

    if not chunks:
        paragraphs = [p.strip() for p in html.split("\n\n") if len(p.strip()) > 80]
        for para in paragraphs:
            chunks.append({
                "text": para,
                "celex": celex,
                "title": title,
                "article": None,
                "type": "paragraph",
            })

    return chunks


def embed_chunks(chunks, batch_size=128):
    """Embed chunks using sentence-transformers."""
    from sentence_transformers import SentenceTransformer
    model = SentenceTransformer(EMBEDDING_MODEL)
    texts = [c["text"] for c in chunks]
    all_embeddings = []
    for i in range(0, len(texts), batch_size):
        batch = texts[i : i + batch_size]
        embeddings = model.encode(batch, show_progress_bar=False, normalize_embeddings=True)
        all_embeddings.append(embeddings)
    return np.vstack(all_embeddings).astype(np.float32)


def upload_index(vectors, chunks):
    """Upload updated index to HF Hub."""
    api = HfApi()
    import tempfile
    with tempfile.NamedTemporaryFile(suffix=".npy", delete=False) as vf:
        np.save(vf.name, vectors)
        api.upload_file(
            repo_id=REPO_ID,
            path_in_repo="vectors.npy",
            path_or_fileobj=vf.name,
            repo_type="dataset",
            token=HF_TOKEN,
        )
    with tempfile.NamedTemporaryFile(suffix=".json", mode="w", delete=False) as cf:
        json.dump(chunks, cf, indent=2)
        cf.flush()
        api.upload_file(
            repo_id=REPO_ID,
            path_in_repo="chunks.json",
            path_or_fileobj=cf.name,
            repo_type="dataset",
            token=HF_TOKEN,
        )
    with tempfile.NamedTemporaryFile(suffix=".txt", mode="w", delete=False) as tf:
        tf.write(datetime.now(timezone.utc).isoformat())
        tf.flush()
        api.upload_file(
            repo_id=REPO_ID,
            path_in_repo="last_updated.txt",
            path_or_fileobj=tf.name,
            repo_type="dataset",
            token=HF_TOKEN,
        )
    logger.info("Index uploaded to HF Hub")


def main():
    if not HF_TOKEN:
        logger.error("HF_TOKEN environment variable required")
        return

    # Step 1: Download current index
    vectors, chunks, last_updated = download_current_index()

    # Build CELEX → chunk mapping for dedup
    existing_celex_set = set(c["celex"] for c in chunks)

    # Step 2: Query modified documents
    docs = query_modified_documents(last_updated)
    if not docs:
        logger.info("No new/changed documents")
        return

    # Step 3: Download and process only new docs
    logger.info("Downloading new/changed documents...")
    html_map = {}
    new_celex_ids = [d["celex"] for d in docs if d["celex"] not in existing_celex_set]
    changed_celex_ids = [d["celex"] for d in docs if d["celex"] in existing_celex_set]

    logger.info(f"New: {len(new_celex_ids)}, Changed: {len(changed_celex_ids)}")

    all_to_process = docs
    with ThreadPoolExecutor(max_workers=DOWNLOAD_WORKERS) as executor:
        future_map = {executor.submit(fetch_document_html, d["celex"]): d for d in all_to_process}
        for future in tqdm(as_completed(future_map), total=len(all_to_process), desc="Downloading"):
            doc = future_map[future]
            try:
                html = future.result()
                if html:
                    html_map[doc["celex"]] = html
            except Exception:
                pass

    # Step 4: Parse and chunk new docs
    logger.info("Parsing new documents...")
    new_chunks = []
    for doc in tqdm(all_to_process, desc="Parsing"):
        html = html_map.get(doc["celex"])
        if html:
            parsed = parse_to_chunks(html, doc["celex"], doc["title"])
            new_chunks.extend(parsed)

    if not new_chunks:
        logger.info("No new chunks to add")
        return

    # Step 5: Remove changed docs from existing, add new ones
    celexes_to_remove = set(changed_celex_ids)
    filtered_chunks = [c for c in chunks if c["celex"] not in celexes_to_remove]
    updated_chunks = filtered_chunks + new_chunks

    # Step 6: Embed new chunks only
    logger.info(f"Embedding {len(new_chunks)} new chunks...")
    new_vectors = embed_chunks(new_chunks)

    # Step 7: Merge vectors
    # For changed docs: need to figure out which vector indices to remove
    # Simple approach: re-embed everything (safer but slower for large changes)
    # For small daily updates: just append new vectors
    if celexes_to_remove:
        # Re-embed all chunks to keep vectors in sync
        logger.info("Changed docs detected — re-embedding all chunks...")
        updated_vectors = embed_chunks(updated_chunks)
    else:
        # Just append new vectors
        updated_vectors = np.vstack([vectors, new_vectors])

    logger.info(f"Updated index: {updated_vectors.shape[0]} vectors, {len(updated_chunks)} chunks")

    # Step 8: Upload
    upload_index(updated_vectors, updated_chunks)
    logger.info("Daily update complete")


if __name__ == "__main__":
    main()
```

### Step 5.2 — Write `.github/workflows/update-index.yml`

```yaml
name: Daily EUR-Lex Index Update

on:
  schedule:
    - cron: "0 6 * * *"  # Every day at 06:00 UTC
  workflow_dispatch:       # Allow manual trigger

jobs:
  update:
    runs-on: ubuntu-latest
    timeout-minutes: 30

    steps:
      - uses: actions/checkout@v4

      - uses: actions/setup-python@v5
        with:
          python-version: "3.12"
          cache: pip

      - name: Install dependencies
        run: |
          pip install --upgrade pip
          pip install numpy huggingface_hub sentence-transformers requests tqdm eurlxp[sparql] polars

      - name: Run incremental update
        env:
          HF_TOKEN: ${{ secrets.HF_TOKEN }}
          HF_USERNAME: ${{ secrets.HF_USERNAME }}
          HF_DATASET: "eurlex-chat-data"
        run: python scripts/update_index.py
```

### Step 5.3 — Create the `.github/workflows/` directory

```bash
mkdir -p ~/Desktop/EUProjects/eur-lex-ai-chat/.github/workflows
```

### Step 5.4 — Set up GitHub secrets

After pushing to GitHub, add these secrets in the repository Settings → Secrets and variables → Actions:

| Secret | Value |
|--------|-------|
| `HF_TOKEN` | Your HuggingFace write token |
| `HF_USERNAME` | Your HuggingFace username |

---

## Phase 6: Deployment

**Goal:** Deploy the backend to Render, frontend to Vercel, set up cron-job.org keepalives, and submit to Google Search Console.

### Step 6.1 — Push code to GitHub

```bash
cd ~/Desktop/EUProjects/eur-lex-ai-chat

# Initialize git repo
git init
git add -A
git commit -m "Initial commit: EUR-Lex AI Chat — full implementation"

# Create GitHub repo and push
gh repo create eur-lex-ai-chat --public --push --source=.
# If gh isn't authenticated:
# 1. Go to https://github.com/new
# 2. Create repo named "eur-lex-ai-chat"
# 3. Run:
#    git remote add origin https://github.com/YOUR_USERNAME/eur-lex-ai-chat.git
#    git branch -M main
#    git push -u origin main
```

### Step 6.2 — Deploy backend to Render

1. Go to https://dashboard.render.com
2. Click **New +****Web Service**
3. Connect your GitHub repository
4. Configure:
   - **Name**: `eurlex-chat-api`
   - **Runtime**: Python 3
   - **Region**: Frankfurt (EU) — for low latency in Europe
   - **Branch**: `main`
   - **Build Command**: `pip install -r backend/requirements.txt`
   - **Start Command**: `cd backend && ./startup.sh`
   - **Instance Type**: Free ($0/month, 512MB RAM)
5. Add environment variables:
   - `GROQ_API_KEY`: your_groq_key
   - `HF_TOKEN`: your_hf_token
   - `HF_USERNAME`: your_hf_username
   - `HF_DATASET`: eurlex-chat-data
6. Click **Deploy Web Service**

The deploy takes ~2-3 minutes. Render will:
- Clone the repo
- Install dependencies
- Start the FastAPI server
- Load the vector index from HF Hub at startup

### Step 6.3 — Note the Render URL

After deployment, Render assigns a URL like: `https://eurlex-chat-api.onrender.com`

Test it:
```bash
curl https://eurlex-chat-api.onrender.com/health
```

Expected response:
```json
{"status": "ok", "index_loaded": true, "vector_count": ..., "chunk_count": ...}
```

### Step 6.4 — Configure frontend API URL

Before deploying frontend, set the API URL:

```bash
cd ~/Desktop/EUProjects/eur-lex-ai-chat/frontend

# Set the production API URL
echo "PUBLIC_API_URL=https://eurlex-chat-api.onrender.com" > .env.production
```

### Step 6.5 — Deploy frontend to Vercel

1. Go to https://vercel.com/new
2. Import your GitHub repository
3. Configure:
   - **Framework Preset**: Astro
   - **Root Directory**: `frontend`
   - **Build Command**: `npm run build` (default)
   - **Output Directory**: `dist` (default)
4. Add environment variables:
   - `PUBLIC_API_URL`: `https://eurlex-chat-api.onrender.com`
5. Click **Deploy**

Vercel auto-deploys on every push to `main`.

### Step 6.6 — Configure custom domain (optional)

1. Buy a domain (e.g., `eurlex-chat.com` from Namecheap, Cloudflare, etc.) — this is the ONLY potential cost
   - OR use Vercel's free subdomain: `eurlex-chat.vercel.app` (free, no domain needed)
2. In Vercel dashboard → Project → Settings → Domains → Add your domain
3. Add the DNS records provided by Vercel to your domain registrar
4. Wait for DNS propagation (5 min to 48 hours)

For $0 hosting, skip the custom domain. Use `eurlex-chat.vercel.app` — it's free, HTTPS by default, and performs equally well in SEO.

### Step 6.7 — Update the sitemap URL

If using a custom domain, update `astro.config.mjs`:
```javascript
site: "https://yourdomain.com",
```

Also update `robots.txt` and `Base.astro` canonical URLs.

### Step 6.8 — Set up cron-job.org

1. Go to https://cron-job.org
2. Create account (free, no credit card)
3. Create two cron jobs:

**Job 1: Keep-alive** (prevents Render from sleeping)
- **URL**: `https://eurlex-chat-api.onrender.com/health`
- **Interval**: Every 5 minutes
- **Method**: GET

**Job 2: Data refresh** (hourly check for new index)
- **URL**: `https://eurlex-chat-api.onrender.com/refresh`
- **Interval**: Every 60 minutes
- **Method**: GET

Render free tier sleeps after 15 minutes of inactivity. Cron-job.org pings every 5 minutes to prevent sleep. The /refresh endpoint checks HF Hub for a newer index and reloads if available.

### Step 6.9 — Submit to Google Search Console

1. Go to https://search.google.com/search-console
2. Add your property:
   - URL prefix: `https://eurlex-chat.vercel.app`
3. Verify ownership:
   - **Recommended**: Add DNS TXT record at your domain registrar (if using custom domain)
   - **Alternative**: HTML file upload — download the verification HTML file and add it to `frontend/public/`
4. After verification, submit sitemap:
   - Go to Sitemaps section
   - Enter: `https://eurlex-chat.vercel.app/sitemap-index.xml`
   - Click Submit

The sitemap tells Google about all pages on the site:
- `/` (landing page)
- `/faq` (FAQ with 20 questions)
- `/blog` (blog listing)
- `/blog/eu-ai-act-explained`
- `/blog/gdpr-guide`
- `/blog/what-is-celex`

### Step 6.10 — Verify deployments

**Frontend check:**
```bash
curl -s https://eurlex-chat.vercel.app | head -50
```
Should return HTML content (not blank JS shell).

**FAQ rich snippets check:**
Go to https://search.google.com/test/rich-results
Enter: `https://eurlex-chat.vercel.app/faq`
Should detect FAQPage schema with 20 questions.

**Backend health check:**
```bash
curl -s https://eurlex-chat-api.onrender.com/health
```

**Chat endpoint check:**
```bash
curl -s -X POST https://eurlex-chat-api.onrender.com/chat \
  -H "Content-Type: application/json" \
  -d '{"query": "What is the GDPR?"}'
```

---

## Phase 7: Go Live Checklist

**Goal:** Verify everything works end-to-end and the system runs autonomously.

### Step 7.1 — Run SEO audit with seofor.dev

```bash
# Start the dev server
cd ~/Desktop/EUProjects/eur-lex-ai-chat/frontend
npm run dev &

# Run SEO audit
seo audit run --port 4321

# Or audit the live site
seo audit run --url https://eurlex-chat.vercel.app
```

Check for:
- ✅ All pages have `<title>` and `<meta description>`
- ✅ No broken links
- ✅ Proper heading hierarchy (H1 → H2 → H3)
- ✅ Canonical URLs set correctly
- ✅ Open Graph + Twitter Card tags present
- ✅ Sitemap is valid and reachable
- ✅ robots.txt is valid

### Step 7.2 — Verify cron-job.org keepalive

Wait 5 minutes after setting up cron-job.org jobs. Check Render logs:
```bash
curl -s https://eurlex-chat-api.onrender.com/health
```

The `loaded_at` field should show the server has been up continuously (not sleeping).

### Step 7.3 — Test full user flow

1. Open `https://eurlex-chat.vercel.app` in a browser
2. Verify landing page loads with chat widget visible
3. Send a test query: "What is the GDPR?"
4. Verify response includes CELEX number citations
5. Navigate to FAQ page — verify all 20 questions expand
6. Navigate to Blog — verify all 3 posts listed
7. Open blog post — verify Article JSON-LD renders
8. Test on mobile — verify responsive design

### Step 7.4 — Verify Google Search Console indexing

1. In Search Console, go to **URL Inspection**
2. Enter `https://eurlex-chat.vercel.app/`
3. Click **Request Indexing**
4. Repeat for `/faq` and `/blog`
5. Check back in 24-48 hours for index status

### Step 7.5 — Verify GitHub Actions runs

1. Go to GitHub → Actions tab
2. Verify the first scheduled run happens at 06:00 UTC next day
3. Or trigger manually: click **Run workflow****Daily EUR-Lex Index Update**
4. Monitor the run — check logs for errors

### Step 7.6 — Final autonomy checklist

| # | Check | Verified |
|---|-------|----------|
| 1 | Frontend serves from Vercel (no laptop needed) | |
| 2 | Backend serves from Render (no laptop needed) | |
| 3 | cron-job.org pings /health every 5 min | |
| 4 | cron-job.org pings /refresh every 60 min | |
| 5 | GitHub Actions runs daily at 06:00 UTC | |
| 6 | Google Search Console has sitemap submitted | |
| 7 | SEO structured data validates (JSON-LD) | |
| 8 | Chat widget works with production backend | |
| 9 | All pages return 200, no broken links | |
| 10 | Rate limiting active (20 req/min/IP) | |

When all 10 are verified, **the system is fully autonomous.**

**Your laptop can power off. The project runs itself forever at $0/month.**

### Step 7.7 — What to monitor

| What | How | Frequency |
|------|-----|-----------|
| Render logs | Render dashboard → Logs | Weekly (5 min) |
| GitHub Actions runs | GitHub → Actions tab | Daily (2 min) |
| Google Search Console | Search Console → Performance | Weekly (5 min) |
| cron-job.org stats | cron-job.org dashboard | Monthly (2 min) |
| Groq API usage | Groq console | Monthly (2 min) |
| HF Hub dataset size | HF Hub → dataset | Monthly (2 min) |

### Step 7.8 — Future improvements

After the system is live, possible enhancements:

1. **More document types**: Add decisions, international agreements, case law
2. **More languages**: Process documents in French, German, Spanish, etc.
3. **Multi-query expansion**: Send 3-5 related queries to retrieve more relevant context
4. **Citation highlighting**: Highlight exact cited paragraphs in the answer
5. **Conversation history**: Multi-turn chat with context
6. **Related documents**: "What other regulations are related to this topic?"
7. **PDF export**: Download chat conversations as PDF
8. **Advanced search**: Filter by year, document type, CELEX number
9. **Rate limit per user**: Token bucket algorithm instead of fixed window
10. **Backlinks**: List on awesome-opensource, GitHub topics, product hunt

---

## Appendix: Troubleshooting

### SPARQL query returns 0 results

If the SPARQL query in build_index.py returns 0 documents:
```bash
# Test with a minimal query
python3 -c "
import requests
r = requests.get('https://publications.europa.eu/webapi/rdf/sparql',
    params={'query': 'SELECT * WHERE { ?s ?p ?o } LIMIT 1', 'format': 'json'},
    timeout=30)
print(r.status_code, len(r.json()['results']['bindings']))
"
```
If this also fails, the endpoint might be temporarily down. Retry later.

### eurlxp HTML fetch fails with WAF

The build_index.py uses Cellar RDF graph traversal (not the EUR-Lex website), so WAF should not be triggered. If it fails:
```bash
# Test with eurlxp directly (which has SPARQL fallback)
python3 -c "
from eurlxp import get_html_by_celex_id
html = get_html_by_celex_id('32019R0947')
print('Success:', len(html), 'bytes')
"
```

### Render won't start / out of memory

The index size should fit in 512MB RAM (~150MB vectors + ~50MB chunks.json + ~100MB overhead = ~300MB). If Render runs out of memory:
1. Reduce index size by filtering fewer document types
2. Or upgrade to Render's $7/month Starter plan (512MB → 1GB RAM)

### Frontend can't reach backend (CORS error)

Check:
1. `PUBLIC_API_URL` env var is set correctly in Vercel
2. Backend CORS `allow_origins` includes the Vercel domain
3. Backend is not sleeping (cron-job.org /health ping working)

### Groq API returns 429 rate limited

The backend has 20 req/min/IP limit. If Groq itself rate-limits:
```bash
# Check remaining rate limit
curl -s -I https://api.groq.com/openai/v1/models \
  -H "Authorization: Bearer $GROQ_API_KEY" \
  | grep -i ratelimit
```
Free tier: 1,000 requests/day, 20 requests/min. Backend rate limiting prevents hitting Groq limits.

---

## Appendix: Key Links

| Service | URL | Purpose |
|---------|-----|---------|
| Render dashboard | https://dashboard.render.com | Backend hosting |
| Vercel dashboard | https://vercel.com | Frontend hosting |
| cron-job.org | https://cron-job.org | Keepalive + refresh |
| Google Search Console | https://search.google.com/search-console | SEO monitoring |
| HuggingFace Hub | https://huggingface.co/ | Vector index storage |
| Groq Console | https://console.groq.com | AI API key + usage |
| GitHub repo | https://github.com/YOUR_USERNAME/eur-lex-ai-chat | Source code |
| seofor.dev | npx seo audit | SEO auditing |
| EUR-Lex SPARQL | https://publications.europa.eu/webapi/rdf/sparql | Document querying |
| EUR-Lex Cellar | https://publications.europa.eu/resource/ | Document fetching |
| Rich Results Test | https://search.google.com/test/rich-results | JSON-LD validation |
| PageSpeed Insights | https://pagespeed.web.dev/ | Performance testing |