kg-cli 0.2.15

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

// Re-export the core graph types for embedding (e.g. kg-mcp).
pub use cache_paths::cache_root_for_cwd;
pub use graph::{Edge, EdgeProperties, GraphFile, Metadata, Node, NodeProperties, Note};
pub use graph_lock::acquire_for_graph as acquire_graph_write_lock;
pub use output::FindMode;

// Re-export validation constants for schema tools.
pub use validate::{
    EDGE_TYPE_RULES, TYPE_TO_PREFIX, VALID_RELATIONS, VALID_TYPES, canonicalize_node_id_for_type,
    edge_type_rule, format_edge_source_type_error, format_edge_target_type_error,
    is_valid_node_type, is_valid_relation, normalize_node_id,
};

// Re-export BM25 index for embedding and benchmarks.
pub use index::Bm25Index;

use std::ffi::OsString;
use std::fmt::Write as _;
use std::io::IsTerminal;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU8, Ordering};

use anyhow::{Context, Result, anyhow, bail};
use clap::Parser;
use cli::{
    AsOfArgs, AuditArgs, BaselineArgs, CheckArgs, Cli, ClusterSkill, ClustersArgs, Command,
    DiffAsOfArgs, EdgeCommand, ExportDotArgs, ExportGraphmlArgs, ExportMdArgs, ExportMermaidArgs,
    FeedbackLogArgs, FeedbackSummaryArgs, FindMode as CliFindMode, GraphCommand, HistoryArgs,
    ImportCsvArgs, ImportMarkdownArgs, MergeStrategy, NodeCommand, NoteAddArgs, NoteCommand,
    NoteListArgs, ScoreAllArgs, SplitArgs, TemporalSource, TimelineArgs, VectorCommand,
};
use serde::{Deserialize, Serialize};
use serde_json::Value;
// (graph types are re-exported above)
use storage::{GraphStore, graph_store};

use app::graph_node_edge::{GraphCommandContext, execute_edge, execute_node};
use app::graph_note::{GraphNoteContext, execute_note};
use app::graph_query_quality::{
    execute_audit, execute_baseline, execute_check, execute_duplicates, execute_edge_gaps,
    execute_feedback_log, execute_feedback_summary, execute_kql, execute_missing_descriptions,
    execute_missing_facts, execute_quality, execute_stats,
};
use app::graph_transfer_temporal::{
    GraphTransferContext, execute_access_log, execute_access_stats, execute_as_of,
    execute_diff_as_of, execute_export_dot, execute_export_graphml, execute_export_html,
    execute_export_json, execute_export_md, execute_export_mermaid, execute_history,
    execute_import_csv, execute_import_json, execute_import_markdown, execute_split,
    execute_timeline, execute_vector,
};

use schema::{GraphSchema, SchemaViolation};
use validate::validate_graph;

static EVENT_LOG_MODE: AtomicU8 = AtomicU8::new(0);

// ---------------------------------------------------------------------------
// Schema validation helpers
// ---------------------------------------------------------------------------

fn format_schema_violations(violations: &[SchemaViolation]) -> String {
    let mut lines = Vec::new();
    lines.push("schema violations:".to_owned());
    for v in violations {
        lines.push(format!("  - {}", v.message));
    }
    lines.join("\n")
}

pub(crate) fn bail_on_schema_violations(violations: &[SchemaViolation]) -> Result<()> {
    if !violations.is_empty() {
        anyhow::bail!("{}", format_schema_violations(violations));
    }
    Ok(())
}

pub fn validate_node_add_with_schema(cwd: &Path, node: &Node) -> Result<()> {
    let schema = GraphSchema::discover(cwd)
        .with_context(|| format!("failed to discover schema from {}", cwd.display()))?
        .map(|(_, schema)| schema);
    if let Some(schema) = schema.as_ref() {
        let violations = schema.validate_node_add(node);
        bail_on_schema_violations(&violations)?;
    }
    Ok(())
}

fn validate_graph_with_schema(graph: &GraphFile, schema: &GraphSchema) -> Vec<SchemaViolation> {
    let mut all_violations = Vec::new();
    for node in &graph.nodes {
        all_violations.extend(schema.validate_node_add(node));
    }
    let node_type_map: std::collections::HashMap<&str, &str> = graph
        .nodes
        .iter()
        .map(|n| (n.id.as_str(), n.r#type.as_str()))
        .collect();
    for edge in &graph.edges {
        if let (Some(src_type), Some(tgt_type)) = (
            node_type_map.get(edge.source_id.as_str()),
            node_type_map.get(edge.target_id.as_str()),
        ) {
            all_violations.extend(schema.validate_edge_add(
                &edge.source_id,
                src_type,
                &edge.relation,
                &edge.target_id,
                tgt_type,
            ));
        }
    }
    all_violations.extend(schema.validate_uniqueness(&graph.nodes));
    all_violations
}

// ---------------------------------------------------------------------------
// Public entry point
// ---------------------------------------------------------------------------

/// Run kg with CLI arguments, printing the result to stdout.
///
/// This is the main entry point for the kg binary.
pub fn run<I>(args: I, cwd: &Path) -> Result<()>
where
    I: IntoIterator<Item = OsString>,
{
    let rendered = run_args(args, cwd)?;
    if should_colorize_stdout() {
        print!("{}", colorize_cli_output(&rendered));
    } else {
        print!("{rendered}");
    }
    Ok(())
}

fn should_colorize_stdout() -> bool {
    let force = std::env::var("CLICOLOR_FORCE")
        .map(|value| value != "0")
        .unwrap_or(false);
    if force {
        return true;
    }
    if !std::io::stdout().is_terminal() {
        return false;
    }
    if std::env::var_os("NO_COLOR").is_some() {
        return false;
    }
    std::env::var("CLICOLOR")
        .map(|value| value != "0")
        .unwrap_or(true)
}

fn colorize_cli_output(rendered: &str) -> String {
    if looks_like_json(rendered) {
        return rendered.to_owned();
    }
    rendered
        .lines()
        .map(colorize_line)
        .collect::<Vec<_>>()
        .join("\n")
}

fn looks_like_json(rendered: &str) -> bool {
    let trimmed = rendered.trim_start();
    trimmed.starts_with('{') || trimmed.starts_with('[')
}

fn colorize_line(line: &str) -> String {
    const RESET: &str = "\x1b[0m";
    const BOLD_CYAN: &str = "\x1b[1;36m";
    const BOLD_YELLOW: &str = "\x1b[1;33m";
    const BOLD_GREEN: &str = "\x1b[1;32m";
    const BOLD_MAGENTA: &str = "\x1b[1;35m";
    const BLUE: &str = "\x1b[34m";

    if line.starts_with("# ") {
        return format!("{BOLD_CYAN}{line}{RESET}");
    }
    if line.starts_with("? ") {
        return format!("{BOLD_YELLOW}{line}{RESET}");
    }
    if line.starts_with("= ") || line.starts_with("+ ") {
        return format!("{BOLD_GREEN}{line}{RESET}");
    }
    if line.starts_with("score:") {
        return format!("{BOLD_MAGENTA}{line}{RESET}");
    }
    if line.starts_with("-> ") || line.starts_with("<- ") {
        return format!("{BLUE}{line}{RESET}");
    }
    line.to_owned()
}

pub fn format_error_chain(err: &anyhow::Error) -> String {
    let mut rendered = err.to_string();
    let mut causes = err.chain().skip(1).peekable();
    if causes.peek().is_some() {
        rendered.push_str("\ncaused by:");
        for cause in causes {
            let _ = write!(rendered, "\n  - {cause}");
        }
    }
    rendered
}

/// Run kg with CLI arguments, returning the rendered output as a string.
///
/// This is useful for embedding kg in other applications.
pub fn run_args<I>(args: I, cwd: &Path) -> Result<String>
where
    I: IntoIterator<Item = OsString>,
{
    let cli = Cli::parse_from(normalize_args(args));
    let graph_root = default_graph_root(cwd);
    execute(cli, cwd, &graph_root)
}

/// Run kg with CLI arguments, returning errors as Result instead of exiting.
///
/// Unlike `run_args`, this does not exit on parse errors - it returns them
/// as `Err` results. Useful for testing and embedding scenarios.
pub fn run_args_safe<I>(args: I, cwd: &Path) -> Result<String>
where
    I: IntoIterator<Item = OsString>,
{
    let cli = Cli::try_parse_from(normalize_args(args)).map_err(|err| anyhow!(err.to_string()))?;
    let graph_root = default_graph_root(cwd);
    execute(cli, cwd, &graph_root)
}

// ---------------------------------------------------------------------------
// Arg normalisation: `kg fridge ...` -> `kg graph fridge ...`
// ---------------------------------------------------------------------------

fn normalize_args<I>(args: I) -> Vec<OsString>
where
    I: IntoIterator<Item = OsString>,
{
    let collected: Vec<OsString> = args.into_iter().collect();
    if collected.len() <= 1 {
        return collected;
    }
    let first = collected[1].to_string_lossy();
    if first.starts_with('-')
        || first == "init"
        || first == "create"
        || first == "diff"
        || first == "merge"
        || first == "graph"
        || first == "list"
        || first == "feedback-log"
        || first == "feedback-summary"
    {
        return collected;
    }
    let mut normalized = Vec::with_capacity(collected.len() + 1);
    normalized.push(collected[0].clone());
    normalized.push(OsString::from("graph"));
    normalized.extend(collected.into_iter().skip(1));
    normalized
}

// ---------------------------------------------------------------------------
// Command dispatch
// ---------------------------------------------------------------------------

fn execute(cli: Cli, cwd: &Path, graph_root: &Path) -> Result<String> {
    configure_event_log_mode(cli.event_log);
    match cli.command {
        Command::Init(args) => Ok(init::render_init(&args)),
        Command::Create { graph_name } => {
            let store = graph_store(cwd, graph_root, false)?;
            let path = store.create_graph(&graph_name)?;
            let graph_file = store.load_graph(&path)?;
            append_event_snapshot(&path, "graph.create", Some(graph_name.clone()), &graph_file)?;
            Ok(format!("+ created {}\n", path.display()))
        }
        Command::Diff { left, right, json } => {
            let store = graph_store(cwd, graph_root, false)?;
            if json {
                render_graph_diff_json(store.as_ref(), &left, &right)
            } else {
                render_graph_diff(store.as_ref(), &left, &right)
            }
        }
        Command::Merge {
            target,
            source,
            strategy,
        } => {
            let store = graph_store(cwd, graph_root, false)?;
            merge_graphs(store.as_ref(), &target, &source, strategy)
        }
        Command::List(args) => {
            let store = graph_store(cwd, graph_root, false)?;
            if args.json {
                render_graph_list_json(store.as_ref())
            } else {
                render_graph_list(store.as_ref(), args.full)
            }
        }
        Command::FeedbackLog(args) => execute_feedback_log(cwd, &args),
        Command::Graph {
            graph,
            legacy,
            command,
        } => {
            let store = graph_store(cwd, graph_root, legacy)?;
            let path = store.resolve_graph_path(&graph)?;
            let _graph_write_lock = if graph_command_mutates(&command) {
                Some(graph_lock::acquire_for_graph(&path)?)
            } else {
                None
            };
            let mut graph_file = store.load_graph(&path)?;
            let schema = GraphSchema::discover(cwd).ok().flatten().map(|(_, s)| s);
            let user_short_uid = config::ensure_user_short_uid(cwd);

            match command {
                GraphCommand::Node { command } => execute_node(
                    command,
                    GraphCommandContext {
                        graph_name: &graph,
                        path: &path,
                        user_short_uid: &user_short_uid,
                        graph_file: &mut graph_file,
                        schema: schema.as_ref(),
                        store: store.as_ref(),
                    },
                ),

                GraphCommand::Edge { command } => execute_edge(
                    command,
                    GraphCommandContext {
                        graph_name: &graph,
                        path: &path,
                        user_short_uid: &user_short_uid,
                        graph_file: &mut graph_file,
                        schema: schema.as_ref(),
                        store: store.as_ref(),
                    },
                ),

                GraphCommand::Note { command } => execute_note(
                    command,
                    GraphNoteContext {
                        path: &path,
                        graph_file: &mut graph_file,
                        store: store.as_ref(),
                        _schema: schema.as_ref(),
                    },
                ),

                GraphCommand::Stats(args) => Ok(execute_stats(&graph_file, &args)),
                GraphCommand::Check(args) => Ok(execute_check(&graph_file, cwd, &args)),
                GraphCommand::Audit(args) => Ok(execute_audit(&graph_file, cwd, &args)),

                GraphCommand::Quality { command } => Ok(execute_quality(command, &graph_file)),

                // Short aliases (e.g. `kg graph fridge missing-descriptions`)
                GraphCommand::MissingDescriptions(args) => {
                    Ok(execute_missing_descriptions(&graph_file, &args))
                }
                GraphCommand::MissingFacts(args) => Ok(execute_missing_facts(&graph_file, &args)),
                GraphCommand::Duplicates(args) => Ok(execute_duplicates(&graph_file, &args)),
                GraphCommand::EdgeGaps(args) => Ok(execute_edge_gaps(&graph_file, &args)),
                GraphCommand::Clusters(args) => execute_clusters(&graph_file, &path, &args),

                GraphCommand::ExportHtml(args) => execute_export_html(&graph, &graph_file, args),

                GraphCommand::AccessLog(args) => execute_access_log(&path, args),

                GraphCommand::AccessStats(_) => execute_access_stats(&path),
                GraphCommand::ImportCsv(args) => execute_import_csv(
                    GraphTransferContext {
                        cwd,
                        graph_name: &graph,
                        path: &path,
                        graph_file: &mut graph_file,
                        schema: schema.as_ref(),
                        store: store.as_ref(),
                    },
                    args,
                ),
                GraphCommand::ImportMarkdown(args) => execute_import_markdown(
                    GraphTransferContext {
                        cwd,
                        graph_name: &graph,
                        path: &path,
                        graph_file: &mut graph_file,
                        schema: schema.as_ref(),
                        store: store.as_ref(),
                    },
                    args,
                ),
                GraphCommand::Kql(args) => execute_kql(&graph_file, args),
                GraphCommand::ExportJson(args) => execute_export_json(&graph, &graph_file, args),
                GraphCommand::ImportJson(args) => {
                    execute_import_json(&path, &graph, store.as_ref(), args)
                }
                GraphCommand::ExportDot(args) => execute_export_dot(&graph, &graph_file, args),
                GraphCommand::ExportMermaid(args) => {
                    execute_export_mermaid(&graph, &graph_file, args)
                }
                GraphCommand::ExportGraphml(args) => {
                    execute_export_graphml(&graph, &graph_file, args)
                }
                GraphCommand::ExportMd(args) => execute_export_md(
                    GraphTransferContext {
                        cwd,
                        graph_name: &graph,
                        path: &path,
                        graph_file: &mut graph_file,
                        schema: schema.as_ref(),
                        store: store.as_ref(),
                    },
                    args,
                ),
                GraphCommand::Split(args) => execute_split(&graph, &graph_file, args),
                GraphCommand::Vector { command } => execute_vector(
                    GraphTransferContext {
                        cwd,
                        graph_name: &graph,
                        path: &path,
                        graph_file: &mut graph_file,
                        schema: schema.as_ref(),
                        store: store.as_ref(),
                    },
                    command,
                ),
                GraphCommand::AsOf(args) => execute_as_of(&path, &graph, args),
                GraphCommand::History(args) => execute_history(&path, &graph, args),
                GraphCommand::Timeline(args) => execute_timeline(&path, &graph, args),
                GraphCommand::DiffAsOf(args) => execute_diff_as_of(&path, &graph, args),
                GraphCommand::FeedbackSummary(args) => {
                    Ok(execute_feedback_summary(cwd, &graph, &args)?)
                }
                GraphCommand::Baseline(args) => {
                    Ok(execute_baseline(cwd, &graph, &graph_file, &args)?)
                }
                GraphCommand::ScoreAll(args) => execute_score_all(&graph_file, &path, &args),
            }
        }
    }
}

fn render_graph_list(store: &dyn GraphStore, full: bool) -> Result<String> {
    let graphs = store.list_graphs()?;

    let mut lines = vec![format!("= graphs ({})", graphs.len())];
    for (name, path) in graphs {
        if full {
            lines.push(format!("- {name} | {}", path.display()));
        } else {
            lines.push(format!("- {name}"));
        }
    }
    Ok(format!("{}\n", lines.join("\n")))
}

fn graph_command_mutates(command: &GraphCommand) -> bool {
    match command {
        GraphCommand::Node { command } => node_command_mutates(command),
        GraphCommand::Edge { command } => edge_command_mutates(command),
        GraphCommand::Note { command } => note_command_mutates(command),
        GraphCommand::ImportCsv(_)
        | GraphCommand::ImportMarkdown(_)
        | GraphCommand::ImportJson(_)
        | GraphCommand::Vector {
            command: VectorCommand::Import(_),
        } => true,
        GraphCommand::Stats(_)
        | GraphCommand::Check(_)
        | GraphCommand::Audit(_)
        | GraphCommand::Quality { .. }
        | GraphCommand::MissingDescriptions(_)
        | GraphCommand::MissingFacts(_)
        | GraphCommand::Duplicates(_)
        | GraphCommand::EdgeGaps(_)
        | GraphCommand::Clusters(_)
        | GraphCommand::ExportHtml(_)
        | GraphCommand::AccessLog(_)
        | GraphCommand::AccessStats(_)
        | GraphCommand::Kql(_)
        | GraphCommand::ExportJson(_)
        | GraphCommand::ExportDot(_)
        | GraphCommand::ExportMermaid(_)
        | GraphCommand::ExportGraphml(_)
        | GraphCommand::ExportMd(_)
        | GraphCommand::Split(_)
        | GraphCommand::Vector {
            command: VectorCommand::Stats(_),
        }
        | GraphCommand::AsOf(_)
        | GraphCommand::History(_)
        | GraphCommand::Timeline(_)
        | GraphCommand::DiffAsOf(_)
        | GraphCommand::FeedbackSummary(_)
        | GraphCommand::Baseline(_)
        | GraphCommand::ScoreAll(_) => false,
    }
}

fn execute_score_all(graph: &GraphFile, path: &Path, args: &ScoreAllArgs) -> Result<String> {
    let outcome = scoring::compute_all_pair_scores_to_cache(
        graph,
        path,
        &scoring::ScoreAllConfig {
            min_desc_len: args.min_desc_len,
            desc_weight: args.desc_weight,
            bundle_weight: args.bundle_weight,
            cluster_seed: args.cluster_seed,
            cluster_resolution: args.cluster_resolution,
            membership_top_k: args.membership_top_k,
        },
    )?;

    Ok(format!(
        "= score-all\n- pairs: {}\n- edges: {}\n- clusters: {}\n- output: {}\n",
        outcome.pairs,
        outcome.edges,
        outcome.clusters,
        outcome.path.display()
    ))
}

fn execute_clusters(graph: &GraphFile, path: &Path, args: &ClustersArgs) -> Result<String> {
    let source_graph = resolve_cluster_source_graph(graph, path)?;
    Ok(render_clusters(&source_graph, args))
}

fn resolve_cluster_source_graph(graph: &GraphFile, path: &Path) -> Result<GraphFile> {
    let filename = path
        .file_name()
        .and_then(|value| value.to_str())
        .unwrap_or_default();
    if filename.contains(".score.") {
        return Ok(graph.clone());
    }

    let latest = find_latest_score_snapshot(path)?.ok_or_else(|| {
        anyhow!(
            "no score cache found for '{}'; run `kg graph {} score-all` first",
            path.display(),
            graph.metadata.name
        )
    })?;
    GraphFile::load(&latest)
}

fn find_latest_score_snapshot(path: &Path) -> Result<Option<PathBuf>> {
    let stem = path
        .file_stem()
        .and_then(|value| value.to_str())
        .ok_or_else(|| anyhow!("invalid graph filename"))?;
    let prefix = format!("{stem}.score.");
    let suffix = ".kg";
    let mut latest: Option<(u128, PathBuf)> = None;

    let cache_dir = cache_paths::cache_root_for_graph(path);
    let Ok(entries) = std::fs::read_dir(&cache_dir) else {
        return Ok(None);
    };

    for entry in entries.flatten() {
        let name = entry.file_name();
        let name = name.to_string_lossy();
        if !name.starts_with(&prefix) || !name.ends_with(suffix) {
            continue;
        }
        let ts_part = &name[prefix.len()..name.len() - suffix.len()];
        let Ok(ts) = ts_part.parse::<u128>() else {
            continue;
        };
        if latest.as_ref().map(|(curr, _)| ts > *curr).unwrap_or(true) {
            latest = Some((ts, entry.path()));
        }
    }

    Ok(latest.map(|(_, path)| path))
}

#[derive(Debug, Serialize)]
struct ClusterView {
    id: String,
    size: usize,
    relevance: f64,
    members: Vec<(String, f64)>,
}

fn render_clusters(graph: &GraphFile, args: &ClustersArgs) -> String {
    let mut clusters: Vec<ClusterView> = graph
        .nodes
        .iter()
        .filter(|node| node.r#type == "@" && node.id.starts_with("@:cluster_"))
        .map(|cluster| {
            let mut members: Vec<(String, f64)> = graph
                .edges
                .iter()
                .filter(|edge| edge.source_id == cluster.id && edge.relation == "HAS")
                .map(|edge| {
                    (
                        edge.target_id.clone(),
                        edge.properties.detail.parse::<f64>().unwrap_or(0.0),
                    )
                })
                .collect();
            members.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));
            let relevance = if members.is_empty() {
                0.0
            } else {
                members.iter().map(|(_, v)| *v).sum::<f64>() / members.len() as f64
            };
            ClusterView {
                id: cluster.id.clone(),
                size: members.len(),
                relevance,
                members,
            }
        })
        .collect();

    clusters.sort_by(|a, b| {
        b.relevance
            .partial_cmp(&a.relevance)
            .unwrap_or(std::cmp::Ordering::Equal)
            .then_with(|| b.size.cmp(&a.size))
            .then_with(|| a.id.cmp(&b.id))
    });
    clusters.truncate(args.limit);

    if args.json {
        return serde_json::to_string_pretty(&clusters).unwrap_or_else(|_| "[]".to_owned());
    }

    if matches!(args.skill, Some(ClusterSkill::Gardener)) {
        let mut lines = vec![format!("= gardener clusters ({})", clusters.len())];
        for cluster in &clusters {
            let top = cluster
                .members
                .iter()
                .take(3)
                .map(|(id, score)| format!("{id} ({score:.3})"))
                .collect::<Vec<_>>()
                .join(", ");
            lines.push(format!(
                "- {} | relevance {:.3} | size {} | top: {}",
                cluster.id, cluster.relevance, cluster.size, top
            ));
            lines.push(format!(
                "- action: review cluster {}, merge aliases/facts, then keep strongest node as canonical",
                cluster.id
            ));
        }
        return format!("{}\n", lines.join("\n"));
    }

    let mut lines = vec![format!("= clusters ({})", clusters.len())];
    for cluster in &clusters {
        let top = cluster
            .members
            .iter()
            .take(5)
            .map(|(id, score)| format!("{id}:{score:.3}"))
            .collect::<Vec<_>>()
            .join(", ");
        lines.push(format!(
            "- {} | relevance {:.3} | size {} | top {}",
            cluster.id, cluster.relevance, cluster.size, top
        ));
    }
    format!("{}\n", lines.join("\n"))
}

fn node_command_mutates(command: &NodeCommand) -> bool {
    matches!(
        command,
        NodeCommand::Add(_)
            | NodeCommand::Modify(_)
            | NodeCommand::Rename { .. }
            | NodeCommand::Remove { .. }
    )
}

fn edge_command_mutates(command: &EdgeCommand) -> bool {
    matches!(
        command,
        EdgeCommand::Add(_) | EdgeCommand::AddBatch(_) | EdgeCommand::Remove(_)
    )
}

fn note_command_mutates(command: &NoteCommand) -> bool {
    matches!(command, NoteCommand::Add(_) | NoteCommand::Remove { .. })
}

#[derive(Debug, Serialize)]
struct GraphListEntry {
    name: String,
    path: String,
}

#[derive(Debug, Serialize)]
struct GraphListResponse {
    graphs: Vec<GraphListEntry>,
}

fn render_graph_list_json(store: &dyn GraphStore) -> Result<String> {
    let graphs = store.list_graphs()?;
    let entries = graphs
        .into_iter()
        .map(|(name, path)| GraphListEntry {
            name,
            path: path.display().to_string(),
        })
        .collect();
    let payload = GraphListResponse { graphs: entries };
    Ok(serde_json::to_string_pretty(&payload).unwrap_or_else(|_| "{}".to_owned()))
}

#[derive(Debug, Serialize)]
struct FindQueryResult {
    query: String,
    count: usize,
    nodes: Vec<ScoredFindNode>,
}

#[derive(Debug, Serialize)]
struct ScoredFindNode {
    score: i64,
    node: Node,
    #[serde(skip_serializing_if = "Option::is_none")]
    score_breakdown: Option<ScoredFindBreakdown>,
}

#[derive(Debug, Serialize)]
struct ScoredFindBreakdown {
    raw_relevance: f64,
    normalized_relevance: i64,
    lexical_boost: i64,
    feedback_boost: i64,
    importance_boost: i64,
    authority_raw: i64,
    authority_applied: i64,
    authority_cap: i64,
}

#[derive(Debug, Serialize)]
struct FindResponse {
    total: usize,
    queries: Vec<FindQueryResult>,
}

pub(crate) fn render_find_json_with_index(
    graph: &GraphFile,
    queries: &[String],
    limit: usize,
    include_metadata: bool,
    mode: output::FindMode,
    debug_score: bool,
    index: Option<&Bm25Index>,
    tune: Option<&output::FindTune>,
) -> String {
    let mut total = 0usize;
    let mut results = Vec::new();
    for query in queries {
        let (count, scored_nodes) = output::find_scored_nodes_and_total_with_index_tuned(
            graph,
            query,
            limit,
            true,
            include_metadata,
            mode,
            index,
            tune,
        );
        total += count;
        let nodes = scored_nodes
            .into_iter()
            .map(|entry| ScoredFindNode {
                score: entry.score,
                node: entry.node,
                score_breakdown: debug_score.then_some(ScoredFindBreakdown {
                    raw_relevance: entry.breakdown.raw_relevance,
                    normalized_relevance: entry.breakdown.normalized_relevance,
                    lexical_boost: entry.breakdown.lexical_boost,
                    feedback_boost: entry.breakdown.feedback_boost,
                    importance_boost: entry.breakdown.importance_boost,
                    authority_raw: entry.breakdown.authority_raw,
                    authority_applied: entry.breakdown.authority_applied,
                    authority_cap: entry.breakdown.authority_cap,
                }),
            })
            .collect();
        results.push(FindQueryResult {
            query: query.clone(),
            count,
            nodes,
        });
    }
    let payload = FindResponse {
        total,
        queries: results,
    };
    serde_json::to_string_pretty(&payload).unwrap_or_else(|_| "{}".to_owned())
}

#[derive(Debug, Serialize)]
struct NodeGetResponse {
    node: Node,
}

pub(crate) fn render_node_json(node: &Node) -> String {
    let payload = NodeGetResponse { node: node.clone() };
    serde_json::to_string_pretty(&payload).unwrap_or_else(|_| "{}".to_owned())
}

fn render_graph_diff(store: &dyn GraphStore, left: &str, right: &str) -> Result<String> {
    let left_path = store.resolve_graph_path(left)?;
    let right_path = store.resolve_graph_path(right)?;
    let left_graph = store.load_graph(&left_path)?;
    let right_graph = store.load_graph(&right_path)?;
    Ok(render_graph_diff_from_files(
        left,
        right,
        &left_graph,
        &right_graph,
    ))
}

fn render_graph_diff_json(store: &dyn GraphStore, left: &str, right: &str) -> Result<String> {
    let left_path = store.resolve_graph_path(left)?;
    let right_path = store.resolve_graph_path(right)?;
    let left_graph = store.load_graph(&left_path)?;
    let right_graph = store.load_graph(&right_path)?;
    Ok(render_graph_diff_json_from_files(
        left,
        right,
        &left_graph,
        &right_graph,
    ))
}

#[derive(Debug, Serialize)]
struct DiffEntry {
    path: String,
    left: Value,
    right: Value,
}

#[derive(Debug, Serialize)]
struct EntityDiff {
    id: String,
    diffs: Vec<DiffEntry>,
}

#[derive(Debug, Serialize)]
struct GraphDiffResponse {
    left: String,
    right: String,
    added_nodes: Vec<String>,
    removed_nodes: Vec<String>,
    changed_nodes: Vec<EntityDiff>,
    added_edges: Vec<String>,
    removed_edges: Vec<String>,
    changed_edges: Vec<EntityDiff>,
    added_notes: Vec<String>,
    removed_notes: Vec<String>,
    changed_notes: Vec<EntityDiff>,
}

fn render_graph_diff_json_from_files(
    left: &str,
    right: &str,
    left_graph: &GraphFile,
    right_graph: &GraphFile,
) -> String {
    use std::collections::{HashMap, HashSet};

    let left_nodes: HashSet<String> = left_graph.nodes.iter().map(|n| n.id.clone()).collect();
    let right_nodes: HashSet<String> = right_graph.nodes.iter().map(|n| n.id.clone()).collect();

    let left_node_map: HashMap<String, &Node> =
        left_graph.nodes.iter().map(|n| (n.id.clone(), n)).collect();
    let right_node_map: HashMap<String, &Node> = right_graph
        .nodes
        .iter()
        .map(|n| (n.id.clone(), n))
        .collect();

    let left_edges: HashSet<String> = left_graph
        .edges
        .iter()
        .map(|e| format!("{} {} {}", e.source_id, e.relation, e.target_id))
        .collect();
    let right_edges: HashSet<String> = right_graph
        .edges
        .iter()
        .map(|e| format!("{} {} {}", e.source_id, e.relation, e.target_id))
        .collect();

    let left_edge_map: HashMap<String, &Edge> = left_graph
        .edges
        .iter()
        .map(|e| (format!("{} {} {}", e.source_id, e.relation, e.target_id), e))
        .collect();
    let right_edge_map: HashMap<String, &Edge> = right_graph
        .edges
        .iter()
        .map(|e| (format!("{} {} {}", e.source_id, e.relation, e.target_id), e))
        .collect();

    let left_notes: HashSet<String> = left_graph.notes.iter().map(|n| n.id.clone()).collect();
    let right_notes: HashSet<String> = right_graph.notes.iter().map(|n| n.id.clone()).collect();

    let left_note_map: HashMap<String, &Note> =
        left_graph.notes.iter().map(|n| (n.id.clone(), n)).collect();
    let right_note_map: HashMap<String, &Note> = right_graph
        .notes
        .iter()
        .map(|n| (n.id.clone(), n))
        .collect();

    let mut added_nodes: Vec<String> = right_nodes.difference(&left_nodes).cloned().collect();
    let mut removed_nodes: Vec<String> = left_nodes.difference(&right_nodes).cloned().collect();
    let mut added_edges: Vec<String> = right_edges.difference(&left_edges).cloned().collect();
    let mut removed_edges: Vec<String> = left_edges.difference(&right_edges).cloned().collect();
    let mut added_notes: Vec<String> = right_notes.difference(&left_notes).cloned().collect();
    let mut removed_notes: Vec<String> = left_notes.difference(&right_notes).cloned().collect();

    let mut changed_nodes: Vec<String> = left_nodes
        .intersection(&right_nodes)
        .filter_map(|id| {
            let left_node = left_node_map.get(id.as_str())?;
            let right_node = right_node_map.get(id.as_str())?;
            if eq_serialized(*left_node, *right_node) {
                None
            } else {
                Some(id.clone())
            }
        })
        .collect();
    let mut changed_edges: Vec<String> = left_edges
        .intersection(&right_edges)
        .filter_map(|key| {
            let left_edge = left_edge_map.get(key.as_str())?;
            let right_edge = right_edge_map.get(key.as_str())?;
            if eq_serialized(*left_edge, *right_edge) {
                None
            } else {
                Some(key.clone())
            }
        })
        .collect();
    let mut changed_notes: Vec<String> = left_notes
        .intersection(&right_notes)
        .filter_map(|id| {
            let left_note = left_note_map.get(id.as_str())?;
            let right_note = right_note_map.get(id.as_str())?;
            if eq_serialized(*left_note, *right_note) {
                None
            } else {
                Some(id.clone())
            }
        })
        .collect();

    added_nodes.sort();
    removed_nodes.sort();
    added_edges.sort();
    removed_edges.sort();
    added_notes.sort();
    removed_notes.sort();
    changed_nodes.sort();
    changed_edges.sort();
    changed_notes.sort();

    let changed_nodes = changed_nodes
        .into_iter()
        .map(|id| EntityDiff {
            diffs: left_node_map
                .get(id.as_str())
                .zip(right_node_map.get(id.as_str()))
                .map(|(left_node, right_node)| diff_serialized_values_json(*left_node, *right_node))
                .unwrap_or_default(),
            id,
        })
        .collect();
    let changed_edges = changed_edges
        .into_iter()
        .map(|id| EntityDiff {
            diffs: left_edge_map
                .get(id.as_str())
                .zip(right_edge_map.get(id.as_str()))
                .map(|(left_edge, right_edge)| diff_serialized_values_json(*left_edge, *right_edge))
                .unwrap_or_default(),
            id,
        })
        .collect();
    let changed_notes = changed_notes
        .into_iter()
        .map(|id| EntityDiff {
            diffs: left_note_map
                .get(id.as_str())
                .zip(right_note_map.get(id.as_str()))
                .map(|(left_note, right_note)| diff_serialized_values_json(*left_note, *right_note))
                .unwrap_or_default(),
            id,
        })
        .collect();

    let payload = GraphDiffResponse {
        left: left.to_owned(),
        right: right.to_owned(),
        added_nodes,
        removed_nodes,
        changed_nodes,
        added_edges,
        removed_edges,
        changed_edges,
        added_notes,
        removed_notes,
        changed_notes,
    };
    serde_json::to_string_pretty(&payload).unwrap_or_else(|_| "{}".to_owned())
}

fn render_graph_diff_from_files(
    left: &str,
    right: &str,
    left_graph: &GraphFile,
    right_graph: &GraphFile,
) -> String {
    use std::collections::{HashMap, HashSet};

    let left_nodes: HashSet<String> = left_graph.nodes.iter().map(|n| n.id.clone()).collect();
    let right_nodes: HashSet<String> = right_graph.nodes.iter().map(|n| n.id.clone()).collect();

    let left_node_map: HashMap<String, &Node> =
        left_graph.nodes.iter().map(|n| (n.id.clone(), n)).collect();
    let right_node_map: HashMap<String, &Node> = right_graph
        .nodes
        .iter()
        .map(|n| (n.id.clone(), n))
        .collect();

    let left_edges: HashSet<String> = left_graph
        .edges
        .iter()
        .map(|e| format!("{} {} {}", e.source_id, e.relation, e.target_id))
        .collect();
    let right_edges: HashSet<String> = right_graph
        .edges
        .iter()
        .map(|e| format!("{} {} {}", e.source_id, e.relation, e.target_id))
        .collect();

    let left_edge_map: HashMap<String, &Edge> = left_graph
        .edges
        .iter()
        .map(|e| (format!("{} {} {}", e.source_id, e.relation, e.target_id), e))
        .collect();
    let right_edge_map: HashMap<String, &Edge> = right_graph
        .edges
        .iter()
        .map(|e| (format!("{} {} {}", e.source_id, e.relation, e.target_id), e))
        .collect();

    let left_notes: HashSet<String> = left_graph.notes.iter().map(|n| n.id.clone()).collect();
    let right_notes: HashSet<String> = right_graph.notes.iter().map(|n| n.id.clone()).collect();

    let left_note_map: HashMap<String, &Note> =
        left_graph.notes.iter().map(|n| (n.id.clone(), n)).collect();
    let right_note_map: HashMap<String, &Note> = right_graph
        .notes
        .iter()
        .map(|n| (n.id.clone(), n))
        .collect();

    let mut added_nodes: Vec<String> = right_nodes.difference(&left_nodes).cloned().collect();
    let mut removed_nodes: Vec<String> = left_nodes.difference(&right_nodes).cloned().collect();
    let mut added_edges: Vec<String> = right_edges.difference(&left_edges).cloned().collect();
    let mut removed_edges: Vec<String> = left_edges.difference(&right_edges).cloned().collect();
    let mut added_notes: Vec<String> = right_notes.difference(&left_notes).cloned().collect();
    let mut removed_notes: Vec<String> = left_notes.difference(&right_notes).cloned().collect();

    let mut changed_nodes: Vec<String> = left_nodes
        .intersection(&right_nodes)
        .filter_map(|id| {
            let left_node = left_node_map.get(id.as_str())?;
            let right_node = right_node_map.get(id.as_str())?;
            if eq_serialized(*left_node, *right_node) {
                None
            } else {
                Some(id.clone())
            }
        })
        .collect();

    let mut changed_edges: Vec<String> = left_edges
        .intersection(&right_edges)
        .filter_map(|key| {
            let left_edge = left_edge_map.get(key.as_str())?;
            let right_edge = right_edge_map.get(key.as_str())?;
            if eq_serialized(*left_edge, *right_edge) {
                None
            } else {
                Some(key.clone())
            }
        })
        .collect();

    let mut changed_notes: Vec<String> = left_notes
        .intersection(&right_notes)
        .filter_map(|id| {
            let left_note = left_note_map.get(id.as_str())?;
            let right_note = right_note_map.get(id.as_str())?;
            if eq_serialized(*left_note, *right_note) {
                None
            } else {
                Some(id.clone())
            }
        })
        .collect();

    added_nodes.sort();
    removed_nodes.sort();
    added_edges.sort();
    removed_edges.sort();
    added_notes.sort();
    removed_notes.sort();
    changed_nodes.sort();
    changed_edges.sort();
    changed_notes.sort();

    let mut lines = vec![format!("= diff {left} -> {right}")];
    lines.push(format!("+ nodes ({})", added_nodes.len()));
    for id in added_nodes {
        lines.push(format!("+ node {id}"));
    }
    lines.push(format!("- nodes ({})", removed_nodes.len()));
    for id in removed_nodes {
        lines.push(format!("- node {id}"));
    }
    lines.push(format!("~ nodes ({})", changed_nodes.len()));
    for id in changed_nodes {
        if let (Some(left_node), Some(right_node)) = (
            left_node_map.get(id.as_str()),
            right_node_map.get(id.as_str()),
        ) {
            lines.extend(render_entity_diff_lines("node", &id, left_node, right_node));
        } else {
            lines.push(format!("~ node {id}"));
        }
    }
    lines.push(format!("+ edges ({})", added_edges.len()));
    for edge in added_edges {
        lines.push(format!("+ edge {edge}"));
    }
    lines.push(format!("- edges ({})", removed_edges.len()));
    for edge in removed_edges {
        lines.push(format!("- edge {edge}"));
    }
    lines.push(format!("~ edges ({})", changed_edges.len()));
    for edge in changed_edges {
        if let (Some(left_edge), Some(right_edge)) = (
            left_edge_map.get(edge.as_str()),
            right_edge_map.get(edge.as_str()),
        ) {
            lines.extend(render_entity_diff_lines(
                "edge", &edge, left_edge, right_edge,
            ));
        } else {
            lines.push(format!("~ edge {edge}"));
        }
    }
    lines.push(format!("+ notes ({})", added_notes.len()));
    for note_id in added_notes {
        lines.push(format!("+ note {note_id}"));
    }
    lines.push(format!("- notes ({})", removed_notes.len()));
    for note_id in removed_notes {
        lines.push(format!("- note {note_id}"));
    }
    lines.push(format!("~ notes ({})", changed_notes.len()));
    for note_id in changed_notes {
        if let (Some(left_note), Some(right_note)) = (
            left_note_map.get(note_id.as_str()),
            right_note_map.get(note_id.as_str()),
        ) {
            lines.extend(render_entity_diff_lines(
                "note", &note_id, left_note, right_note,
            ));
        } else {
            lines.push(format!("~ note {note_id}"));
        }
    }

    format!("{}\n", lines.join("\n"))
}

fn eq_serialized<T: Serialize>(left: &T, right: &T) -> bool {
    match (serde_json::to_value(left), serde_json::to_value(right)) {
        (Ok(left_value), Ok(right_value)) => left_value == right_value,
        _ => false,
    }
}

fn render_entity_diff_lines<T: Serialize>(
    kind: &str,
    id: &str,
    left: &T,
    right: &T,
) -> Vec<String> {
    let mut lines = Vec::new();
    lines.push(format!("~ {kind} {id}"));
    for diff in diff_serialized_values(left, right) {
        lines.push(format!("  ~ {diff}"));
    }
    lines
}

fn diff_serialized_values<T: Serialize>(left: &T, right: &T) -> Vec<String> {
    match (serde_json::to_value(left), serde_json::to_value(right)) {
        (Ok(left_value), Ok(right_value)) => {
            let mut diffs = Vec::new();
            collect_value_diffs("", &left_value, &right_value, &mut diffs);
            diffs
        }
        _ => vec!["<serialization failed>".to_owned()],
    }
}

fn diff_serialized_values_json<T: Serialize>(left: &T, right: &T) -> Vec<DiffEntry> {
    match (serde_json::to_value(left), serde_json::to_value(right)) {
        (Ok(left_value), Ok(right_value)) => {
            let mut diffs = Vec::new();
            collect_value_diffs_json("", &left_value, &right_value, &mut diffs);
            diffs
        }
        _ => Vec::new(),
    }
}

fn collect_value_diffs_json(path: &str, left: &Value, right: &Value, out: &mut Vec<DiffEntry>) {
    if left == right {
        return;
    }
    match (left, right) {
        (Value::Object(left_obj), Value::Object(right_obj)) => {
            use std::collections::BTreeSet;

            let mut keys: BTreeSet<&str> = BTreeSet::new();
            for key in left_obj.keys() {
                keys.insert(key.as_str());
            }
            for key in right_obj.keys() {
                keys.insert(key.as_str());
            }
            for key in keys {
                let left_value = left_obj.get(key).unwrap_or(&Value::Null);
                let right_value = right_obj.get(key).unwrap_or(&Value::Null);
                let next_path = if path.is_empty() {
                    key.to_owned()
                } else {
                    format!("{path}.{key}")
                };
                collect_value_diffs_json(&next_path, left_value, right_value, out);
            }
        }
        (Value::Array(_), Value::Array(_)) => {
            let label = if path.is_empty() {
                "<root>[]".to_owned()
            } else {
                format!("{path}[]")
            };
            out.push(DiffEntry {
                path: label,
                left: left.clone(),
                right: right.clone(),
            });
        }
        _ => {
            let label = if path.is_empty() { "<root>" } else { path };
            out.push(DiffEntry {
                path: label.to_owned(),
                left: left.clone(),
                right: right.clone(),
            });
        }
    }
}

fn collect_value_diffs(path: &str, left: &Value, right: &Value, out: &mut Vec<String>) {
    if left == right {
        return;
    }
    match (left, right) {
        (Value::Object(left_obj), Value::Object(right_obj)) => {
            use std::collections::BTreeSet;

            let mut keys: BTreeSet<&str> = BTreeSet::new();
            for key in left_obj.keys() {
                keys.insert(key.as_str());
            }
            for key in right_obj.keys() {
                keys.insert(key.as_str());
            }
            for key in keys {
                let left_value = left_obj.get(key).unwrap_or(&Value::Null);
                let right_value = right_obj.get(key).unwrap_or(&Value::Null);
                let next_path = if path.is_empty() {
                    key.to_owned()
                } else {
                    format!("{path}.{key}")
                };
                collect_value_diffs(&next_path, left_value, right_value, out);
            }
        }
        (Value::Array(_), Value::Array(_)) => {
            let label = if path.is_empty() {
                "<root>[]".to_owned()
            } else {
                format!("{path}[]")
            };
            out.push(format!(
                "{label}: {} -> {}",
                format_value(left),
                format_value(right)
            ));
        }
        _ => {
            let label = if path.is_empty() { "<root>" } else { path };
            out.push(format!(
                "{label}: {} -> {}",
                format_value(left),
                format_value(right)
            ));
        }
    }
}

fn format_value(value: &Value) -> String {
    let mut rendered =
        serde_json::to_string(value).unwrap_or_else(|_| "<unserializable>".to_owned());
    rendered = rendered.replace('\n', "\\n");
    truncate_value(rendered, 160)
}

fn truncate_value(mut value: String, limit: usize) -> String {
    if value.len() <= limit {
        return value;
    }
    value.truncate(limit.saturating_sub(3));
    value.push_str("...");
    value
}

fn merge_graphs(
    store: &dyn GraphStore,
    target: &str,
    source: &str,
    strategy: MergeStrategy,
) -> Result<String> {
    use std::collections::HashMap;

    let target_path = store.resolve_graph_path(target)?;
    let _target_write_lock = graph_lock::acquire_for_graph(&target_path)?;
    let source_path = store.resolve_graph_path(source)?;
    let mut target_graph = store.load_graph(&target_path)?;
    let source_graph = store.load_graph(&source_path)?;

    let mut node_index: HashMap<String, usize> = HashMap::new();
    for (idx, node) in target_graph.nodes.iter().enumerate() {
        node_index.insert(node.id.clone(), idx);
    }

    let mut node_added = 0usize;
    let mut node_updated = 0usize;
    for node in &source_graph.nodes {
        if let Some(&idx) = node_index.get(&node.id) {
            if matches!(strategy, MergeStrategy::PreferNew) {
                target_graph.nodes[idx] = node.clone();
                node_updated += 1;
            }
        } else {
            target_graph.nodes.push(node.clone());
            node_index.insert(node.id.clone(), target_graph.nodes.len() - 1);
            node_added += 1;
        }
    }

    let mut edge_index: HashMap<String, usize> = HashMap::new();
    for (idx, edge) in target_graph.edges.iter().enumerate() {
        let key = format!("{} {} {}", edge.source_id, edge.relation, edge.target_id);
        edge_index.insert(key, idx);
    }

    let mut edge_added = 0usize;
    let mut edge_updated = 0usize;
    for edge in &source_graph.edges {
        let key = format!("{} {} {}", edge.source_id, edge.relation, edge.target_id);
        if let Some(&idx) = edge_index.get(&key) {
            if matches!(strategy, MergeStrategy::PreferNew) {
                target_graph.edges[idx] = edge.clone();
                edge_updated += 1;
            }
        } else {
            target_graph.edges.push(edge.clone());
            edge_index.insert(key, target_graph.edges.len() - 1);
            edge_added += 1;
        }
    }

    let mut note_index: HashMap<String, usize> = HashMap::new();
    for (idx, note) in target_graph.notes.iter().enumerate() {
        note_index.insert(note.id.clone(), idx);
    }

    let mut note_added = 0usize;
    let mut note_updated = 0usize;
    for note in &source_graph.notes {
        if let Some(&idx) = note_index.get(&note.id) {
            if matches!(strategy, MergeStrategy::PreferNew) {
                target_graph.notes[idx] = note.clone();
                note_updated += 1;
            }
        } else {
            target_graph.notes.push(note.clone());
            note_index.insert(note.id.clone(), target_graph.notes.len() - 1);
            note_added += 1;
        }
    }

    store.save_graph(&target_path, &target_graph)?;
    append_event_snapshot(
        &target_path,
        "graph.merge",
        Some(format!("{source} -> {target} ({strategy:?})")),
        &target_graph,
    )?;

    let mut lines = vec![format!("+ merged {source} -> {target}")];
    lines.push(format!("nodes: +{node_added} ~{node_updated}"));
    lines.push(format!("edges: +{edge_added} ~{edge_updated}"));
    lines.push(format!("notes: +{note_added} ~{note_updated}"));

    Ok(format!("{}\n", lines.join("\n")))
}

pub(crate) fn export_graph_as_of(path: &Path, graph: &str, args: &AsOfArgs) -> Result<String> {
    match resolve_temporal_source(path, args.source)? {
        TemporalSource::EventLog => export_graph_as_of_event_log(path, graph, args),
        _ => export_graph_as_of_backups(path, graph, args),
    }
}

fn export_graph_as_of_backups(path: &Path, graph: &str, args: &AsOfArgs) -> Result<String> {
    let backups = list_graph_backups(path)?;
    if backups.is_empty() {
        bail!("no backups found for graph: {graph}");
    }
    let target_ts = args.ts_ms / 1000;
    let mut selected = None;
    for (ts, backup_path) in backups {
        if ts <= target_ts {
            selected = Some((ts, backup_path));
        }
    }
    let Some((ts, backup_path)) = selected else {
        bail!("no backup at or before ts_ms={}", args.ts_ms);
    };

    let output_path = args
        .output
        .clone()
        .unwrap_or_else(|| format!("{graph}.asof.{}.json", args.ts_ms));
    let raw = read_gz_to_string(&backup_path)?;
    std::fs::write(&output_path, raw)?;
    Ok(format!("+ exported {output_path} (as-of {ts})\n"))
}

fn export_graph_as_of_event_log(path: &Path, graph: &str, args: &AsOfArgs) -> Result<String> {
    let entries = event_log::read_log(path)?;
    if entries.is_empty() {
        bail!("no event log entries found for graph: {graph}");
    }
    let selected = select_event_at_or_before(&entries, args.ts_ms)
        .ok_or_else(|| anyhow!("no event log entry at or before ts_ms={}", args.ts_ms))?;
    let output_path = args
        .output
        .clone()
        .unwrap_or_else(|| format!("{graph}.asof.{}.json", args.ts_ms));
    let mut snapshot = selected.graph.clone();
    snapshot.refresh_counts();
    let raw = serde_json::to_string_pretty(&snapshot).context("failed to serialize graph")?;
    std::fs::write(&output_path, raw)?;
    Ok(format!(
        "+ exported {output_path} (as-of {})\n",
        selected.ts_ms
    ))
}

fn list_graph_backups(path: &Path) -> Result<Vec<(u64, PathBuf)>> {
    let stem = path
        .file_stem()
        .and_then(|s| s.to_str())
        .ok_or_else(|| anyhow!("invalid graph filename"))?;
    let ext = path.extension().and_then(|s| s.to_str()).unwrap_or("json");
    let prefixes = [format!("{stem}.{ext}.bck."), format!("{stem}.bck.")];
    let suffix = ".gz";

    let mut backups = Vec::new();
    let mut dirs = vec![cache_paths::cache_root_for_graph(path)];
    if let Some(parent) = path.parent() {
        dirs.push(parent.to_path_buf());
    }

    for dir in dirs {
        let Ok(entries) = std::fs::read_dir(dir) else {
            continue;
        };
        for entry in entries {
            let entry = entry?;
            let name = entry.file_name();
            let name = name.to_string_lossy();
            if !name.ends_with(suffix) {
                continue;
            }
            for prefix in &prefixes {
                if !name.starts_with(prefix) {
                    continue;
                }
                let ts_part = &name[prefix.len()..name.len() - suffix.len()];
                if let Ok(ts) = ts_part.parse::<u64>() {
                    backups.push((ts, entry.path()));
                }
            }
        }
    }
    backups.sort_by_key(|(ts, _)| *ts);
    Ok(backups)
}

fn read_gz_to_string(path: &Path) -> Result<String> {
    use flate2::read::GzDecoder;
    use std::io::Read;

    let data = std::fs::read(path)?;
    let mut decoder = GzDecoder::new(&data[..]);
    let mut out = String::new();
    decoder.read_to_string(&mut out)?;
    Ok(out)
}

pub(crate) fn append_event_snapshot(
    path: &Path,
    action: &str,
    detail: Option<String>,
    graph: &GraphFile,
) -> Result<()> {
    if !event_log_enabled() {
        return Ok(());
    }
    event_log::append_snapshot(path, action, detail, graph)
}

fn configure_event_log_mode(cli_switch_enabled: bool) {
    if cli_switch_enabled {
        EVENT_LOG_MODE.store(2, Ordering::Relaxed);
        return;
    }
    EVENT_LOG_MODE.store(0, Ordering::Relaxed);
}

fn event_log_enabled() -> bool {
    match EVENT_LOG_MODE.load(Ordering::Relaxed) {
        2 => true,
        1 => false,
        _ => {
            let raw = std::env::var("KG_EVENT_LOG").unwrap_or_default();
            matches!(raw.as_str(), "1" | "true" | "TRUE" | "yes" | "on")
        }
    }
}

pub(crate) fn export_graph_json(
    graph: &str,
    graph_file: &GraphFile,
    output: Option<&str>,
) -> Result<String> {
    let output_path = output
        .map(|value| value.to_owned())
        .unwrap_or_else(|| format!("{graph}.export.json"));
    let raw = serde_json::to_string_pretty(graph_file).context("failed to serialize graph")?;
    std::fs::write(&output_path, raw)?;
    Ok(format!("+ exported {output_path}\n"))
}

pub(crate) fn import_graph_json(
    path: &Path,
    graph: &str,
    input: &str,
    store: &dyn GraphStore,
) -> Result<String> {
    let raw = std::fs::read_to_string(input)
        .with_context(|| format!("failed to read import file: {input}"))?;
    let mut imported: GraphFile =
        serde_json::from_str(&raw).with_context(|| format!("invalid JSON: {input}"))?;
    imported.metadata.name = graph.to_owned();
    imported.refresh_counts();
    store.save_graph(path, &imported)?;
    append_event_snapshot(path, "graph.import", Some(input.to_owned()), &imported)?;
    Ok(format!("+ imported {input} -> {graph}\n"))
}

pub(crate) fn import_graph_csv(
    path: &Path,
    graph: &str,
    graph_file: &mut GraphFile,
    store: &dyn GraphStore,
    args: &ImportCsvArgs,
    schema: Option<&GraphSchema>,
) -> Result<String> {
    if args.nodes.is_none() && args.edges.is_none() && args.notes.is_none() {
        bail!("expected at least one of --nodes/--edges/--notes");
    }
    let strategy = match args.strategy {
        MergeStrategy::PreferNew => import_csv::CsvStrategy::PreferNew,
        MergeStrategy::PreferOld => import_csv::CsvStrategy::PreferOld,
    };
    let summary = import_csv::import_csv_into_graph(
        graph_file,
        import_csv::CsvImportArgs {
            nodes_path: args.nodes.as_deref(),
            edges_path: args.edges.as_deref(),
            notes_path: args.notes.as_deref(),
            strategy,
        },
    )?;
    if let Some(schema) = schema {
        let all_violations = validate_graph_with_schema(graph_file, schema);
        bail_on_schema_violations(&all_violations)?;
    }
    store.save_graph(path, graph_file)?;
    append_event_snapshot(path, "graph.import-csv", None, graph_file)?;
    let mut lines = vec![format!("+ imported csv into {graph}")];
    lines.extend(import_csv::merge_summary_lines(&summary));
    Ok(format!("{}\n", lines.join("\n")))
}

pub(crate) fn import_graph_markdown(
    path: &Path,
    graph: &str,
    graph_file: &mut GraphFile,
    store: &dyn GraphStore,
    args: &ImportMarkdownArgs,
    schema: Option<&GraphSchema>,
) -> Result<String> {
    let strategy = match args.strategy {
        MergeStrategy::PreferNew => import_markdown::MarkdownStrategy::PreferNew,
        MergeStrategy::PreferOld => import_markdown::MarkdownStrategy::PreferOld,
    };
    let summary = import_markdown::import_markdown_into_graph(
        graph_file,
        import_markdown::MarkdownImportArgs {
            path: &args.path,
            notes_as_nodes: args.notes_as_nodes,
            strategy,
        },
    )?;
    if let Some(schema) = schema {
        let all_violations = validate_graph_with_schema(graph_file, schema);
        bail_on_schema_violations(&all_violations)?;
    }
    store.save_graph(path, graph_file)?;
    append_event_snapshot(path, "graph.import-md", Some(args.path.clone()), graph_file)?;
    let mut lines = vec![format!("+ imported markdown into {graph}")];
    lines.extend(import_csv::merge_summary_lines(&summary));
    Ok(format!("{}\n", lines.join("\n")))
}

pub(crate) fn export_graph_dot(
    graph: &str,
    graph_file: &GraphFile,
    args: &ExportDotArgs,
) -> Result<String> {
    let output_path = args
        .output
        .clone()
        .unwrap_or_else(|| format!("{graph}.dot"));
    let (nodes, edges) = select_subgraph(
        graph_file,
        args.focus.as_deref(),
        args.depth,
        &args.node_types,
    )?;
    let mut lines = Vec::new();
    lines.push("digraph kg {".to_owned());
    for node in &nodes {
        let label = format!("{}\\n{}", node.id, node.name);
        lines.push(format!(
            "  \"{}\" [label=\"{}\"];",
            escape_dot(&node.id),
            escape_dot(&label)
        ));
    }
    for edge in &edges {
        lines.push(format!(
            "  \"{}\" -> \"{}\" [label=\"{}\"];",
            escape_dot(&edge.source_id),
            escape_dot(&edge.target_id),
            escape_dot(&edge.relation)
        ));
    }
    lines.push("}".to_owned());
    std::fs::write(&output_path, format!("{}\n", lines.join("\n")))?;
    Ok(format!("+ exported {output_path}\n"))
}

pub(crate) fn export_graph_mermaid(
    graph: &str,
    graph_file: &GraphFile,
    args: &ExportMermaidArgs,
) -> Result<String> {
    let output_path = args
        .output
        .clone()
        .unwrap_or_else(|| format!("{graph}.mmd"));
    let (nodes, edges) = select_subgraph(
        graph_file,
        args.focus.as_deref(),
        args.depth,
        &args.node_types,
    )?;
    let mut lines = Vec::new();
    lines.push("graph TD".to_owned());
    for node in &nodes {
        let label = format!("{}\\n{}", node.id, node.name);
        lines.push(format!(
            "  {}[\"{}\"]",
            sanitize_mermaid_id(&node.id),
            escape_mermaid(&label)
        ));
    }
    for edge in &edges {
        lines.push(format!(
            "  {} -- \"{}\" --> {}",
            sanitize_mermaid_id(&edge.source_id),
            escape_mermaid(&edge.relation),
            sanitize_mermaid_id(&edge.target_id)
        ));
    }
    std::fs::write(&output_path, format!("{}\n", lines.join("\n")))?;
    Ok(format!("+ exported {output_path}\n"))
}

pub(crate) fn export_graph_graphml(
    graph: &str,
    graph_file: &GraphFile,
    args: &ExportGraphmlArgs,
) -> Result<String> {
    let output_path = args
        .output
        .clone()
        .unwrap_or_else(|| format!("{graph}.graphml"));
    let (nodes, edges) = select_subgraph(
        graph_file,
        args.focus.as_deref(),
        args.depth,
        &args.node_types,
    )?;

    let mut lines = Vec::new();
    lines.push(r#"<?xml version="1.0" encoding="UTF-8"?>"#.to_string());
    lines.push(r#"<graphml xmlns="http://graphml.graphdrawing.org/xmlns" "#.to_string());
    lines.push(r#"  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance""#.to_string());
    lines.push(r#"  xsi:schemaLocation="http://graphml.graphdrawing.org/xmlns"#.to_string());
    lines.push(r#"  http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd">"#.to_string());
    lines.push(r#"  <key id="d0" for="node" attr.name="name" attr.type="string"/>"#.to_string());
    lines.push(r#"  <key id="d1" for="node" attr.name="type" attr.type="string"/>"#.to_string());
    lines.push(
        r#"  <key id="d2" for="node" attr.name="description" attr.type="string"/>"#.to_string(),
    );
    lines
        .push(r#"  <key id="d3" for="edge" attr.name="relation" attr.type="string"/>"#.to_string());
    lines.push(r#"  <key id="d4" for="edge" attr.name="detail" attr.type="string"/>"#.to_string());
    lines.push(format!(
        r#"  <graph id="{}" edgedefault="directed">"#,
        escape_xml(graph)
    ));

    for node in &nodes {
        lines.push(format!(r#"    <node id="{}">"#, escape_xml(&node.id)));
        lines.push(format!(
            r#"      <data key="d0">{}</data>"#,
            escape_xml(&node.name)
        ));
        lines.push(format!(
            r#"      <data key="d1">{}</data>"#,
            escape_xml(&node.r#type)
        ));
        lines.push(format!(
            r#"      <data key="d2">{}</data>"#,
            escape_xml(&node.properties.description)
        ));
        lines.push("    </node>".to_string());
    }

    for edge in &edges {
        lines.push(format!(
            r#"    <edge source="{}" target="{}">"#,
            escape_xml(&edge.source_id),
            escape_xml(&edge.target_id)
        ));
        lines.push(format!(
            r#"      <data key="d3">{}</data>"#,
            escape_xml(&edge.relation)
        ));
        lines.push(format!(
            r#"      <data key="d4">{}</data>"#,
            escape_xml(&edge.properties.detail)
        ));
        lines.push("    </edge>".to_string());
    }

    lines.push("  </graph>".to_string());
    lines.push("</graphml>".to_string());

    std::fs::write(&output_path, lines.join("\n"))?;
    Ok(format!("+ exported {output_path}\n"))
}

fn escape_xml(s: &str) -> String {
    s.replace('&', "&amp;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
        .replace('"', "&quot;")
        .replace('\'', "&apos;")
}

pub(crate) fn export_graph_md(
    graph: &str,
    graph_file: &GraphFile,
    args: &ExportMdArgs,
    _cwd: &Path,
) -> Result<String> {
    let output_dir = args
        .output
        .clone()
        .unwrap_or_else(|| format!("{}-md", graph));

    let (nodes, edges) = select_subgraph(
        graph_file,
        args.focus.as_deref(),
        args.depth,
        &args.node_types,
    )?;

    std::fs::create_dir_all(&output_dir)?;

    let mut index_lines = format!("# {}\n\nNodes: {}\n\n## Index\n", graph, nodes.len());

    for node in &nodes {
        let safe_name = sanitize_filename(&node.id);
        let filename = format!("{}.md", safe_name);
        let filepath = Path::new(&output_dir).join(&filename);

        let mut content = String::new();
        content.push_str(&format!("# {}\n\n", node.name));
        content.push_str(&format!("**ID:** `{}`\n\n", node.id));
        content.push_str(&format!("**Type:** {}\n\n", node.r#type));

        if !node.properties.description.is_empty() {
            content.push_str(&format!(
                "## Description\n\n{}\n\n",
                node.properties.description
            ));
        }

        if !node.properties.key_facts.is_empty() {
            content.push_str("## Facts\n\n");
            for fact in &node.properties.key_facts {
                content.push_str(&format!("- {}\n", fact));
            }
            content.push('\n');
        }

        if !node.properties.alias.is_empty() {
            content.push_str(&format!(
                "**Aliases:** {}\n\n",
                node.properties.alias.join(", ")
            ));
        }

        content.push_str("## Relations\n\n");
        for edge in &edges {
            if edge.source_id == node.id {
                content.push_str(&format!(
                    "- [[{}]] --({})--> [[{}]]\n",
                    node.id, edge.relation, edge.target_id
                ));
            } else if edge.target_id == node.id {
                content.push_str(&format!(
                    "- [[{}]] <--({})-- [[{}]]\n",
                    edge.source_id, edge.relation, node.id
                ));
            }
        }
        content.push('\n');

        content.push_str("## Backlinks\n\n");
        let backlinks: Vec<_> = edges.iter().filter(|e| e.target_id == node.id).collect();
        if backlinks.is_empty() {
            content.push_str("_No backlinks_\n");
        } else {
            for edge in backlinks {
                content.push_str(&format!("- [[{}]] ({})\n", edge.source_id, edge.relation));
            }
        }

        std::fs::write(&filepath, content)?;

        index_lines.push_str(&format!(
            "- [[{}]] - {} [{}]\n",
            node.id, node.name, node.r#type
        ));
    }

    std::fs::write(Path::new(&output_dir).join("index.md"), index_lines)?;

    Ok(format!(
        "+ exported {}/ ({} nodes)\n",
        output_dir,
        nodes.len()
    ))
}

fn sanitize_filename(name: &str) -> String {
    name.replace([':', '/', '\\', ' '], "_").replace('&', "and")
}

pub(crate) fn split_graph(graph: &str, graph_file: &GraphFile, args: &SplitArgs) -> Result<String> {
    let output_dir = args
        .output
        .clone()
        .unwrap_or_else(|| format!("{}-split", graph));

    let nodes_dir = Path::new(&output_dir).join("nodes");
    let edges_dir = Path::new(&output_dir).join("edges");
    let notes_dir = Path::new(&output_dir).join("notes");
    let meta_dir = Path::new(&output_dir).join("metadata");

    std::fs::create_dir_all(&nodes_dir)?;
    std::fs::create_dir_all(&edges_dir)?;
    std::fs::create_dir_all(&notes_dir)?;
    std::fs::create_dir_all(&meta_dir)?;

    let meta_json = serde_json::to_string_pretty(&graph_file.metadata)?;
    std::fs::write(meta_dir.join("metadata.json"), meta_json)?;

    let mut node_count = 0;
    for node in &graph_file.nodes {
        let safe_id = sanitize_filename(&node.id);
        let filepath = nodes_dir.join(format!("{}.json", safe_id));
        let node_json = serde_json::to_string_pretty(node)?;
        std::fs::write(filepath, node_json)?;
        node_count += 1;
    }

    let mut edge_count = 0;
    for edge in &graph_file.edges {
        let edge_key = format!(
            "{}___{}___{}",
            sanitize_filename(&edge.source_id),
            sanitize_filename(&edge.relation),
            sanitize_filename(&edge.target_id)
        );
        let filepath = edges_dir.join(format!("{}.json", edge_key));
        let edge_json = serde_json::to_string_pretty(edge)?;
        std::fs::write(filepath, edge_json)?;
        edge_count += 1;
    }

    let mut note_count = 0;
    for note in &graph_file.notes {
        let safe_id = sanitize_filename(&note.id);
        let filepath = notes_dir.join(format!("{}.json", safe_id));
        let note_json = serde_json::to_string_pretty(note)?;
        std::fs::write(filepath, note_json)?;
        note_count += 1;
    }

    let manifest = format!(
        r#"# {} Split Manifest

This directory contains a git-friendly split representation of the graph.

## Structure

- `metadata/metadata.json` - Graph metadata
- `nodes/` - One JSON file per node (filename = sanitized node id)
- `edges/` - One JSON file per edge (filename = source___relation___target)
- `notes/` - One JSON file per note

## Stats

- Nodes: {}
- Edges: {}
- Notes: {}

## Usage

To reassemble into a single JSON file, use `kg {} import-json`.
"#,
        graph, node_count, edge_count, note_count, graph
    );
    std::fs::write(Path::new(&output_dir).join("MANIFEST.md"), manifest)?;

    Ok(format!(
        "+ split {} into {}/ (nodes: {}, edges: {}, notes: {})\n",
        graph, output_dir, node_count, edge_count, note_count
    ))
}

fn select_subgraph<'a>(
    graph_file: &'a GraphFile,
    focus: Option<&'a str>,
    depth: usize,
    node_types: &'a [String],
) -> Result<(Vec<&'a Node>, Vec<&'a Edge>)> {
    use std::collections::{HashSet, VecDeque};

    let mut selected: HashSet<String> = HashSet::new();
    if let Some(focus_id) = focus {
        if graph_file.node_by_id(focus_id).is_none() {
            bail!("focus node not found: {focus_id}");
        }
        selected.insert(focus_id.to_owned());
        let mut frontier = VecDeque::new();
        frontier.push_back((focus_id.to_owned(), 0usize));
        while let Some((current, dist)) = frontier.pop_front() {
            if dist >= depth {
                continue;
            }
            for edge in &graph_file.edges {
                let next = if edge.source_id == current {
                    Some(edge.target_id.clone())
                } else if edge.target_id == current {
                    Some(edge.source_id.clone())
                } else {
                    None
                };
                if let Some(next_id) = next {
                    if selected.insert(next_id.clone()) {
                        frontier.push_back((next_id, dist + 1));
                    }
                }
            }
        }
    } else {
        for node in &graph_file.nodes {
            selected.insert(node.id.clone());
        }
    }

    let type_filter: Vec<String> = node_types.iter().map(|t| t.to_lowercase()).collect();
    let has_filter = !type_filter.is_empty();
    let mut nodes: Vec<&Node> = graph_file
        .nodes
        .iter()
        .filter(|node| selected.contains(&node.id))
        .filter(|node| {
            if let Some(focus_id) = focus {
                if node.id == focus_id {
                    return true;
                }
            }
            !has_filter || type_filter.contains(&node.r#type.to_lowercase())
        })
        .collect();
    nodes.sort_by(|a, b| a.id.cmp(&b.id));

    let node_set: HashSet<String> = nodes.iter().map(|node| node.id.clone()).collect();
    let mut edges: Vec<&Edge> = graph_file
        .edges
        .iter()
        .filter(|edge| node_set.contains(&edge.source_id) && node_set.contains(&edge.target_id))
        .collect();
    edges.sort_by(|a, b| {
        a.source_id
            .cmp(&b.source_id)
            .then_with(|| a.relation.cmp(&b.relation))
            .then_with(|| a.target_id.cmp(&b.target_id))
    });

    Ok((nodes, edges))
}

fn escape_dot(value: &str) -> String {
    value.replace('"', "\\\"").replace('\n', "\\n")
}

fn escape_mermaid(value: &str) -> String {
    value.replace('"', "\\\"").replace('\n', "\\n")
}

fn sanitize_mermaid_id(value: &str) -> String {
    let mut out = String::new();
    for ch in value.chars() {
        if ch.is_ascii_alphanumeric() || ch == '_' {
            out.push(ch);
        } else {
            out.push('_');
        }
    }
    if out.is_empty() {
        "node".to_owned()
    } else {
        out
    }
}

pub(crate) fn render_graph_history(path: &Path, graph: &str, args: &HistoryArgs) -> Result<String> {
    let backups = list_graph_backups(path)?;
    let total = backups.len();
    let snapshots: Vec<(u64, PathBuf)> = backups.into_iter().rev().take(args.limit).collect();

    if args.json {
        let payload = GraphHistoryResponse {
            graph: graph.to_owned(),
            total,
            snapshots: snapshots
                .iter()
                .map(|(ts, backup_path)| GraphHistorySnapshot {
                    ts: *ts,
                    path: backup_path.display().to_string(),
                })
                .collect(),
        };
        let rendered =
            serde_json::to_string_pretty(&payload).context("failed to render history as JSON")?;
        return Ok(format!("{rendered}\n"));
    }

    let mut lines = vec![format!("= history {graph} ({total})")];
    for (ts, backup_path) in snapshots {
        lines.push(format!("- {ts} | {}", backup_path.display()));
    }
    Ok(format!("{}\n", lines.join("\n")))
}

pub(crate) fn render_graph_timeline(
    path: &Path,
    graph: &str,
    args: &TimelineArgs,
) -> Result<String> {
    let entries = event_log::read_log(path)?;
    let total = entries.len();
    let filtered: Vec<&event_log::EventLogEntry> = entries
        .iter()
        .filter(|entry| {
            let after_since = args
                .since_ts_ms
                .map(|since| entry.ts_ms >= since)
                .unwrap_or(true);
            let before_until = args
                .until_ts_ms
                .map(|until| entry.ts_ms <= until)
                .unwrap_or(true);
            after_since && before_until
        })
        .collect();
    let recent: Vec<&event_log::EventLogEntry> =
        filtered.into_iter().rev().take(args.limit).collect();

    if args.json {
        let payload = GraphTimelineResponse {
            graph: graph.to_owned(),
            total,
            filtered: recent.len(),
            since_ts_ms: args.since_ts_ms,
            until_ts_ms: args.until_ts_ms,
            entries: recent
                .iter()
                .map(|entry| GraphTimelineEntry {
                    ts_ms: entry.ts_ms,
                    action: entry.action.clone(),
                    detail: entry.detail.clone(),
                    node_count: entry.graph.nodes.len(),
                    edge_count: entry.graph.edges.len(),
                    note_count: entry.graph.notes.len(),
                })
                .collect(),
        };
        let rendered =
            serde_json::to_string_pretty(&payload).context("failed to render timeline as JSON")?;
        return Ok(format!("{rendered}\n"));
    }

    let mut lines = vec![format!("= timeline {graph} ({total})")];
    if args.since_ts_ms.is_some() || args.until_ts_ms.is_some() {
        lines.push(format!(
            "range: {} -> {}",
            args.since_ts_ms
                .map(|value| value.to_string())
                .unwrap_or_else(|| "-inf".to_owned()),
            args.until_ts_ms
                .map(|value| value.to_string())
                .unwrap_or_else(|| "+inf".to_owned())
        ));
        lines.push(format!("showing: {}", recent.len()));
    }
    for entry in recent {
        let detail = entry
            .detail
            .as_deref()
            .map(|value| format!(" | {value}"))
            .unwrap_or_default();
        lines.push(format!(
            "- {} | {}{} | nodes: {} | edges: {} | notes: {}",
            entry.ts_ms,
            entry.action,
            detail,
            entry.graph.nodes.len(),
            entry.graph.edges.len(),
            entry.graph.notes.len()
        ));
    }
    Ok(format!("{}\n", lines.join("\n")))
}

#[derive(Debug, Serialize)]
struct GraphHistorySnapshot {
    ts: u64,
    path: String,
}

#[derive(Debug, Serialize)]
struct GraphHistoryResponse {
    graph: String,
    total: usize,
    snapshots: Vec<GraphHistorySnapshot>,
}

#[derive(Debug, Serialize)]
struct GraphTimelineEntry {
    ts_ms: u64,
    action: String,
    detail: Option<String>,
    node_count: usize,
    edge_count: usize,
    note_count: usize,
}

#[derive(Debug, Serialize)]
struct GraphTimelineResponse {
    graph: String,
    total: usize,
    filtered: usize,
    since_ts_ms: Option<u64>,
    until_ts_ms: Option<u64>,
    entries: Vec<GraphTimelineEntry>,
}

pub(crate) fn render_graph_diff_as_of(
    path: &Path,
    graph: &str,
    args: &DiffAsOfArgs,
) -> Result<String> {
    match resolve_temporal_source(path, args.source)? {
        TemporalSource::EventLog => render_graph_diff_as_of_event_log(path, graph, args),
        _ => render_graph_diff_as_of_backups(path, graph, args),
    }
}

pub(crate) fn render_graph_diff_as_of_json(
    path: &Path,
    graph: &str,
    args: &DiffAsOfArgs,
) -> Result<String> {
    match resolve_temporal_source(path, args.source)? {
        TemporalSource::EventLog => render_graph_diff_as_of_event_log_json(path, graph, args),
        _ => render_graph_diff_as_of_backups_json(path, graph, args),
    }
}

fn render_graph_diff_as_of_backups(
    path: &Path,
    graph: &str,
    args: &DiffAsOfArgs,
) -> Result<String> {
    let backups = list_graph_backups(path)?;
    if backups.is_empty() {
        bail!("no backups found for graph: {graph}");
    }
    let from_ts = args.from_ts_ms / 1000;
    let to_ts = args.to_ts_ms / 1000;
    let from_backup = select_backup_at_or_before(&backups, from_ts)
        .ok_or_else(|| anyhow!("no backup at or before from_ts_ms={}", args.from_ts_ms))?;
    let to_backup = select_backup_at_or_before(&backups, to_ts)
        .ok_or_else(|| anyhow!("no backup at or before to_ts_ms={}", args.to_ts_ms))?;

    let from_graph = load_graph_from_backup(&from_backup.1)?;
    let to_graph = load_graph_from_backup(&to_backup.1)?;
    let left_label = format!("{graph}@{}", args.from_ts_ms);
    let right_label = format!("{graph}@{}", args.to_ts_ms);
    Ok(render_graph_diff_from_files(
        &left_label,
        &right_label,
        &from_graph,
        &to_graph,
    ))
}

fn render_graph_diff_as_of_backups_json(
    path: &Path,
    graph: &str,
    args: &DiffAsOfArgs,
) -> Result<String> {
    let backups = list_graph_backups(path)?;
    if backups.is_empty() {
        bail!("no backups found for graph: {graph}");
    }
    let from_ts = args.from_ts_ms / 1000;
    let to_ts = args.to_ts_ms / 1000;
    let from_backup = select_backup_at_or_before(&backups, from_ts)
        .ok_or_else(|| anyhow!("no backup at or before from_ts_ms={}", args.from_ts_ms))?;
    let to_backup = select_backup_at_or_before(&backups, to_ts)
        .ok_or_else(|| anyhow!("no backup at or before to_ts_ms={}", args.to_ts_ms))?;

    let from_graph = load_graph_from_backup(&from_backup.1)?;
    let to_graph = load_graph_from_backup(&to_backup.1)?;
    let left_label = format!("{graph}@{}", args.from_ts_ms);
    let right_label = format!("{graph}@{}", args.to_ts_ms);
    Ok(render_graph_diff_json_from_files(
        &left_label,
        &right_label,
        &from_graph,
        &to_graph,
    ))
}

fn render_graph_diff_as_of_event_log(
    path: &Path,
    graph: &str,
    args: &DiffAsOfArgs,
) -> Result<String> {
    let entries = event_log::read_log(path)?;
    if entries.is_empty() {
        bail!("no event log entries found for graph: {graph}");
    }
    let from_entry = select_event_at_or_before(&entries, args.from_ts_ms).ok_or_else(|| {
        anyhow!(
            "no event log entry at or before from_ts_ms={}",
            args.from_ts_ms
        )
    })?;
    let to_entry = select_event_at_or_before(&entries, args.to_ts_ms)
        .ok_or_else(|| anyhow!("no event log entry at or before to_ts_ms={}", args.to_ts_ms))?;

    let left_label = format!("{graph}@{}", args.from_ts_ms);
    let right_label = format!("{graph}@{}", args.to_ts_ms);
    Ok(render_graph_diff_from_files(
        &left_label,
        &right_label,
        &from_entry.graph,
        &to_entry.graph,
    ))
}

fn render_graph_diff_as_of_event_log_json(
    path: &Path,
    graph: &str,
    args: &DiffAsOfArgs,
) -> Result<String> {
    let entries = event_log::read_log(path)?;
    if entries.is_empty() {
        bail!("no event log entries found for graph: {graph}");
    }
    let from_entry = select_event_at_or_before(&entries, args.from_ts_ms).ok_or_else(|| {
        anyhow!(
            "no event log entry at or before from_ts_ms={}",
            args.from_ts_ms
        )
    })?;
    let to_entry = select_event_at_or_before(&entries, args.to_ts_ms)
        .ok_or_else(|| anyhow!("no event log entry at or before to_ts_ms={}", args.to_ts_ms))?;

    let left_label = format!("{graph}@{}", args.from_ts_ms);
    let right_label = format!("{graph}@{}", args.to_ts_ms);
    Ok(render_graph_diff_json_from_files(
        &left_label,
        &right_label,
        &from_entry.graph,
        &to_entry.graph,
    ))
}

fn resolve_temporal_source(path: &Path, source: TemporalSource) -> Result<TemporalSource> {
    if matches!(source, TemporalSource::Auto) {
        let has_events = event_log::has_log(path);
        return Ok(if has_events {
            TemporalSource::EventLog
        } else {
            TemporalSource::Backups
        });
    }
    Ok(source)
}

fn select_event_at_or_before(
    entries: &[event_log::EventLogEntry],
    target_ts_ms: u64,
) -> Option<&event_log::EventLogEntry> {
    let mut selected = None;
    for entry in entries {
        if entry.ts_ms <= target_ts_ms {
            selected = Some(entry);
        }
    }
    selected
}

fn select_backup_at_or_before(
    backups: &[(u64, PathBuf)],
    target_ts: u64,
) -> Option<(u64, PathBuf)> {
    let mut selected = None;
    for (ts, path) in backups {
        if *ts <= target_ts {
            selected = Some((*ts, path.clone()));
        }
    }
    selected
}

fn load_graph_from_backup(path: &Path) -> Result<GraphFile> {
    let raw = read_gz_to_string(path)?;
    let graph: GraphFile = serde_json::from_str(&raw)
        .with_context(|| format!("failed to parse backup: {}", path.display()))?;
    Ok(graph)
}

pub(crate) fn render_note_list(graph: &GraphFile, args: &NoteListArgs) -> String {
    let mut notes: Vec<&Note> = graph
        .notes
        .iter()
        .filter(|note| args.node.as_ref().is_none_or(|node| note.node_id == *node))
        .collect();

    notes.sort_by(|a, b| {
        a.created_at
            .cmp(&b.created_at)
            .then_with(|| a.id.cmp(&b.id))
    });

    let total = notes.len();
    let visible: Vec<&Note> = notes.into_iter().take(args.limit).collect();

    let mut lines = vec![format!("= notes ({total})")];
    for note in &visible {
        let mut line = format!(
            "- {} | {} | {} | {}",
            note.id,
            note.node_id,
            note.created_at,
            truncate_note(&escape_cli_text(&note.body), 80)
        );
        if !note.tags.is_empty() {
            line.push_str(" | tags: ");
            line.push_str(
                &note
                    .tags
                    .iter()
                    .map(|tag| escape_cli_text(tag))
                    .collect::<Vec<_>>()
                    .join(", "),
            );
        }
        if !note.author.is_empty() {
            line.push_str(" | by: ");
            line.push_str(&escape_cli_text(&note.author));
        }
        lines.push(line);
    }
    let omitted = total.saturating_sub(visible.len());
    if omitted > 0 {
        lines.push(format!("... {omitted} more notes omitted"));
    }

    format!("{}\n", lines.join("\n"))
}

pub(crate) fn build_note(graph: &GraphFile, args: NoteAddArgs) -> Result<Note> {
    if graph.node_by_id(&args.node_id).is_none() {
        bail!("node not found: {}", args.node_id);
    }
    let ts = now_ms();
    let id = args.id.unwrap_or_else(|| format!("note:{ts}"));
    let created_at = args.created_at.unwrap_or_else(|| ts.to_string());
    Ok(Note {
        id,
        node_id: args.node_id,
        body: args.text,
        tags: args.tag,
        author: args.author.unwrap_or_default(),
        created_at,
        provenance: args.provenance.unwrap_or_default(),
        source_files: args.source,
    })
}

fn truncate_note(value: &str, max_len: usize) -> String {
    let char_count = value.chars().count();
    if char_count <= max_len {
        return value.to_owned();
    }
    let truncated: String = value.chars().take(max_len.saturating_sub(3)).collect();
    format!("{truncated}...")
}

fn escape_cli_text(value: &str) -> String {
    let mut out = String::new();
    for ch in value.chars() {
        match ch {
            '\\' => out.push_str("\\\\"),
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '\t' => out.push_str("\\t"),
            _ => out.push(ch),
        }
    }
    out
}

fn now_ms() -> u128 {
    use std::time::{SystemTime, UNIX_EPOCH};

    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_millis()
}

pub(crate) fn map_find_mode(mode: CliFindMode) -> output::FindMode {
    match mode {
        CliFindMode::Fuzzy => output::FindMode::Fuzzy,
        CliFindMode::Bm25 => output::FindMode::Bm25,
        CliFindMode::Hybrid => output::FindMode::Hybrid,
        CliFindMode::Vector => output::FindMode::Fuzzy,
    }
}

pub(crate) fn render_feedback_log(cwd: &Path, args: &FeedbackLogArgs) -> Result<String> {
    let path = first_existing_feedback_log_path(cwd);
    if !path.exists() {
        return Ok(String::from("= feedback-log\nempty: no entries yet\n"));
    }

    let content = std::fs::read_to_string(&path)?;
    let mut entries: Vec<FeedbackLogEntry> = Vec::new();
    for line in content.lines() {
        if let Some(entry) = FeedbackLogEntry::parse(line) {
            if let Some(ref uid) = args.uid {
                if &entry.uid != uid {
                    continue;
                }
            }
            if let Some(ref graph) = args.graph {
                if &entry.graph != graph {
                    continue;
                }
            }
            entries.push(entry);
        }
    }

    entries.reverse();
    let shown: Vec<&FeedbackLogEntry> = entries.iter().take(args.limit).collect();

    let mut output = vec![String::from("= feedback-log")];
    output.push(format!("total_entries: {}", entries.len()));
    output.push(format!("showing: {}", shown.len()));
    output.push(String::from("recent_entries:"));
    for e in shown {
        let pick = e.pick.as_deref().unwrap_or("-");
        let selected = e.selected.as_deref().unwrap_or("-");
        let graph = if e.graph.is_empty() { "-" } else { &e.graph };
        let queries = if e.queries.is_empty() {
            "-"
        } else {
            &e.queries
        };
        output.push(format!(
            "- {} | {} | {} | pick={} | selected={} | graph={} | {}",
            e.ts_ms, e.uid, e.action, pick, selected, graph, queries
        ));
    }

    Ok(format!("{}\n", output.join("\n")))
}

pub(crate) fn handle_vector_command(
    path: &Path,
    _graph: &str,
    graph_file: &GraphFile,
    command: &VectorCommand,
    _cwd: &Path,
) -> Result<String> {
    match command {
        VectorCommand::Import(args) => {
            let vector_path = path
                .parent()
                .map(|p| p.join(".kg.vectors.json"))
                .unwrap_or_else(|| PathBuf::from(".kg.vectors.json"));
            let store =
                vectors::VectorStore::import_jsonl(std::path::Path::new(&args.input), graph_file)?;
            store.save(&vector_path)?;
            Ok(format!(
                "+ imported {} vectors (dim={}) to {}\n",
                store.vectors.len(),
                store.dimension,
                vector_path.display()
            ))
        }
        VectorCommand::Stats(_args) => {
            let vector_path = path
                .parent()
                .map(|p| p.join(".kg.vectors.json"))
                .unwrap_or_else(|| PathBuf::from(".kg.vectors.json"));
            if !vector_path.exists() {
                return Ok(String::from("= vectors\nnot initialized\n"));
            }
            let store = vectors::VectorStore::load(&vector_path)?;
            let node_ids: Vec<_> = store.vectors.keys().cloned().collect();
            let in_graph = node_ids
                .iter()
                .filter(|id| graph_file.node_by_id(id).is_some())
                .count();
            Ok(format!(
                "= vectors\ndimension: {}\ntotal: {}\nin_graph: {}\n",
                store.dimension,
                store.vectors.len(),
                in_graph
            ))
        }
    }
}

fn render_feedback_summary(cwd: &Path, args: &FeedbackSummaryArgs) -> Result<String> {
    use std::collections::HashMap;

    let path = first_existing_feedback_log_path(cwd);
    if !path.exists() {
        return Ok(String::from("= feedback-summary\nNo feedback yet.\n"));
    }

    let content = std::fs::read_to_string(&path)?;
    let mut entries: Vec<FeedbackLogEntry> = Vec::new();
    for line in content.lines() {
        if let Some(entry) = FeedbackLogEntry::parse(line) {
            if let Some(ref graph) = args.graph {
                if &entry.graph != graph {
                    continue;
                }
            }
            entries.push(entry);
        }
    }

    entries.reverse();
    let _shown = entries.iter().take(args.limit).collect::<Vec<_>>();

    let mut lines = vec![String::from("= feedback-summary")];
    lines.push(format!("Total entries: {}", entries.len()));

    let mut by_action: HashMap<&str, usize> = HashMap::new();
    let mut nil_queries: Vec<&str> = Vec::new();
    let mut yes_count = 0;
    let mut no_count = 0;
    let mut pick_map: HashMap<&str, usize> = HashMap::new();
    let mut query_counts: HashMap<&str, usize> = HashMap::new();

    for e in &entries {
        *by_action.entry(&e.action).or_insert(0) += 1;

        match e.action.as_str() {
            "NIL" => {
                if !e.queries.is_empty() {
                    nil_queries.push(&e.queries);
                }
            }
            "YES" => yes_count += 1,
            "NO" => no_count += 1,
            "PICK" => {
                if let Some(ref sel) = e.selected {
                    *pick_map.entry(sel).or_insert(0) += 1;
                }
            }
            _ => {}
        }

        if !e.queries.is_empty() {
            *query_counts.entry(&e.queries).or_insert(0) += 1;
        }
    }

    lines.push(String::from("\n### By response"));
    lines.push(format!(
        "YES:  {} ({:.0}%)",
        yes_count,
        if !entries.is_empty() {
            (yes_count as f64 / entries.len() as f64) * 100.0
        } else {
            0.0
        }
    ));
    lines.push(format!("NO:   {}", no_count));
    lines.push(format!("PICK: {}", by_action.get("PICK").unwrap_or(&0)));
    lines.push(format!("NIL:  {} (no results)", nil_queries.len()));

    if !nil_queries.is_empty() {
        lines.push(String::from("\n### BrakujÄ…ce node'y (NIL queries)"));
        for q in nil_queries.iter().take(10) {
            lines.push(format!("- \"{}\"", q));
        }
        if nil_queries.len() > 10 {
            lines.push(format!("  ... i {} więcej", nil_queries.len() - 10));
        }
    }

    if !pick_map.is_empty() {
        lines.push(String::from("\n### Najczęściej wybierane node'y (PICK)"));
        let mut sorted: Vec<_> = pick_map.iter().collect();
        sorted.sort_by(|a, b| b.1.cmp(a.1));
        for (node, count) in sorted.iter().take(10) {
            lines.push(format!("- {} ({}x)", node, count));
        }
    }

    if !query_counts.is_empty() {
        lines.push(String::from("\n### Top wyszukiwane terminy"));
        let mut sorted: Vec<_> = query_counts.iter().collect();
        sorted.sort_by(|a, b| b.1.cmp(a.1));
        for (query, count) in sorted.iter().take(10) {
            lines.push(format!("- \"{}\" ({})", query, count));
        }
    }

    if yes_count == 0 && no_count == 0 && nil_queries.is_empty() {
        lines.push(String::from(
            "\n(Wpływy za mało na wnioski - potrzeba więcej feedbacku)",
        ));
    } else if yes_count > no_count * 3 {
        lines.push(String::from(
            "\n✓ Feedback pozytywny - wyszukiwania działają dobrze.",
        ));
    } else if no_count > yes_count {
        lines.push(String::from(
            "\n⚠ Dużo NO - sprawdź jakość aliasów i dopasowań.",
        ));
    }

    Ok(format!("{}\n", lines.join("\n")))
}

pub fn feedback_log_path(cwd: &Path) -> PathBuf {
    cache_paths::cache_root_for_cwd(cwd).join("kg-mcp.feedback.log")
}

fn legacy_feedback_log_path(cwd: &Path) -> PathBuf {
    cwd.join("kg-mcp.feedback.log")
}

pub fn first_existing_feedback_log_path(cwd: &Path) -> PathBuf {
    let preferred = feedback_log_path(cwd);
    if preferred.exists() {
        return preferred;
    }
    let legacy = legacy_feedback_log_path(cwd);
    if legacy.exists() {
        return legacy;
    }
    preferred
}

pub(crate) fn render_feedback_summary_for_graph(
    cwd: &Path,
    graph: &str,
    args: &FeedbackSummaryArgs,
) -> Result<String> {
    let mut args = args.clone();
    args.graph = Some(graph.to_string());
    render_feedback_summary(cwd, &args)
}

#[derive(Debug, Serialize)]
struct BaselineFeedbackMetrics {
    entries: usize,
    yes: usize,
    no: usize,
    pick: usize,
    nil: usize,
    yes_rate: f64,
    no_rate: f64,
    nil_rate: f64,
}

#[derive(Debug, Serialize)]
struct BaselineCostMetrics {
    find_operations: usize,
    feedback_events: usize,
    feedback_events_per_1000_find_ops: f64,
    token_cost_estimate: Option<f64>,
    token_cost_note: &'static str,
}

#[derive(Debug, Serialize)]
struct GoldenSetMetrics {
    cases: usize,
    hits_any: usize,
    top1_hits: usize,
    hit_rate: f64,
    top1_rate: f64,
    mrr: f64,
    ndcg_at_k: f64,
}

#[derive(Debug, Serialize)]
struct BaselineQualityScore {
    description_coverage: f64,
    facts_coverage: f64,
    duplicate_penalty: f64,
    edge_gap_penalty: f64,
    score_0_100: f64,
}

#[derive(Debug, Serialize)]
struct BaselineReport {
    graph: String,
    quality: crate::analysis::QualitySnapshot,
    quality_score: BaselineQualityScore,
    feedback: BaselineFeedbackMetrics,
    cost: BaselineCostMetrics,
    golden: Option<GoldenSetMetrics>,
}

#[derive(Debug, Deserialize)]
struct GoldenSetCase {
    query: String,
    expected: Vec<String>,
}

fn parse_feedback_entries(cwd: &Path, graph_name: &str) -> Result<Vec<FeedbackLogEntry>> {
    let path = first_existing_feedback_log_path(cwd);
    if !path.exists() {
        return Ok(Vec::new());
    }

    let content = std::fs::read_to_string(path)?;
    let mut entries = Vec::new();
    for line in content.lines() {
        if let Some(entry) = FeedbackLogEntry::parse(line) {
            if entry.graph == graph_name {
                entries.push(entry);
            }
        }
    }
    Ok(entries)
}

fn parse_find_operations(graph_path: &Path) -> Result<usize> {
    let Some(path) = access_log::first_existing_access_log_path(graph_path) else {
        return Ok(0);
    };

    let content = std::fs::read_to_string(path)?;
    let mut find_ops = 0usize;
    for line in content.lines() {
        let mut parts = line.split('\t');
        let _ts = parts.next();
        if let Some(op) = parts.next() {
            if op == "FIND" {
                find_ops += 1;
            }
        }
    }
    Ok(find_ops)
}

fn compute_feedback_metrics(entries: &[FeedbackLogEntry]) -> BaselineFeedbackMetrics {
    let mut yes = 0usize;
    let mut no = 0usize;
    let mut pick = 0usize;
    let mut nil = 0usize;
    for entry in entries {
        match entry.action.as_str() {
            "YES" => yes += 1,
            "NO" => no += 1,
            "PICK" => pick += 1,
            "NIL" => nil += 1,
            _ => {}
        }
    }
    let total = entries.len() as f64;
    BaselineFeedbackMetrics {
        entries: entries.len(),
        yes,
        no,
        pick,
        nil,
        yes_rate: if total > 0.0 { yes as f64 / total } else { 0.0 },
        no_rate: if total > 0.0 { no as f64 / total } else { 0.0 },
        nil_rate: if total > 0.0 { nil as f64 / total } else { 0.0 },
    }
}

fn compute_quality_score(snapshot: &crate::analysis::QualitySnapshot) -> BaselineQualityScore {
    let total_nodes = snapshot.total_nodes as f64;
    let description_coverage = if total_nodes > 0.0 {
        (snapshot
            .total_nodes
            .saturating_sub(snapshot.missing_descriptions)) as f64
            / total_nodes
    } else {
        1.0
    };
    let facts_coverage = if total_nodes > 0.0 {
        (snapshot.total_nodes.saturating_sub(snapshot.missing_facts)) as f64 / total_nodes
    } else {
        1.0
    };

    let duplicate_penalty = if snapshot.total_nodes > 1 {
        let max_pairs = (snapshot.total_nodes * (snapshot.total_nodes - 1) / 2) as f64;
        (snapshot.duplicate_pairs as f64 / max_pairs).clamp(0.0, 1.0)
    } else {
        0.0
    };

    let edge_candidates = snapshot.edge_gaps.total_candidates();
    let edge_gap_penalty = if edge_candidates > 0 {
        (snapshot.edge_gaps.total_missing() as f64 / edge_candidates as f64).clamp(0.0, 1.0)
    } else {
        0.0
    };

    let score = 100.0
        * (0.35 * description_coverage
            + 0.35 * facts_coverage
            + 0.15 * (1.0 - duplicate_penalty)
            + 0.15 * (1.0 - edge_gap_penalty));

    BaselineQualityScore {
        description_coverage,
        facts_coverage,
        duplicate_penalty,
        edge_gap_penalty,
        score_0_100: score,
    }
}

fn eval_golden_set(graph: &GraphFile, args: &BaselineArgs) -> Result<Option<GoldenSetMetrics>> {
    if matches!(args.mode, CliFindMode::Vector) {
        anyhow::bail!("baseline does not support --mode vector");
    }

    let Some(path) = args.golden.as_ref() else {
        return Ok(None);
    };

    let raw = std::fs::read_to_string(path)
        .with_context(|| format!("failed to read golden set: {path}"))?;
    let cases: Vec<GoldenSetCase> =
        serde_json::from_str(&raw).with_context(|| format!("invalid golden set JSON: {path}"))?;

    if cases.is_empty() {
        return Ok(Some(GoldenSetMetrics {
            cases: 0,
            hits_any: 0,
            top1_hits: 0,
            hit_rate: 0.0,
            top1_rate: 0.0,
            mrr: 0.0,
            ndcg_at_k: 0.0,
        }));
    }

    let mode = map_find_mode(args.mode);
    let mut hits_any = 0usize;
    let mut top1_hits = 0usize;
    let mut mrr_sum = 0.0;
    let mut ndcg_sum = 0.0;

    for case in &cases {
        let results = output::find_nodes(
            graph,
            &case.query,
            args.find_limit,
            args.include_features,
            false,
            mode,
        );

        let mut first_rank: Option<usize> = None;
        for (idx, node) in results.iter().enumerate() {
            if case.expected.iter().any(|id| id == &node.id) {
                first_rank = Some(idx + 1);
                break;
            }
        }

        if let Some(rank) = first_rank {
            hits_any += 1;
            if rank == 1 {
                top1_hits += 1;
            }
            mrr_sum += 1.0 / rank as f64;
        }

        let mut dcg = 0.0;
        for (idx, node) in results.iter().enumerate() {
            if case.expected.iter().any(|id| id == &node.id) {
                let denom = (idx as f64 + 2.0).log2();
                dcg += 1.0 / denom;
            }
        }
        let ideal_hits = case.expected.len().min(results.len());
        let mut idcg = 0.0;
        for rank in 0..ideal_hits {
            let denom = (rank as f64 + 2.0).log2();
            idcg += 1.0 / denom;
        }
        if idcg > 0.0 {
            ndcg_sum += dcg / idcg;
        }
    }

    let total = cases.len() as f64;
    Ok(Some(GoldenSetMetrics {
        cases: cases.len(),
        hits_any,
        top1_hits,
        hit_rate: hits_any as f64 / total,
        top1_rate: top1_hits as f64 / total,
        mrr: mrr_sum / total,
        ndcg_at_k: ndcg_sum / total,
    }))
}

pub(crate) fn render_baseline_report(
    cwd: &Path,
    graph_name: &str,
    graph: &GraphFile,
    quality: &crate::analysis::QualitySnapshot,
    args: &BaselineArgs,
) -> Result<String> {
    let feedback_entries = parse_feedback_entries(cwd, graph_name)?;
    let feedback = compute_feedback_metrics(&feedback_entries);

    let graph_root = default_graph_root(cwd);
    let graph_path = resolve_graph_path(cwd, &graph_root, graph_name)?;
    let find_operations = parse_find_operations(&graph_path)?;

    let cost = BaselineCostMetrics {
        find_operations,
        feedback_events: feedback.entries,
        feedback_events_per_1000_find_ops: if find_operations > 0 {
            (feedback.entries as f64 / find_operations as f64) * 1000.0
        } else {
            0.0
        },
        token_cost_estimate: None,
        token_cost_note: "token cost unavailable in current logs (instrumentation pending)",
    };

    let quality_score = compute_quality_score(quality);
    let golden = eval_golden_set(graph, args)?;

    let report = BaselineReport {
        graph: graph_name.to_owned(),
        quality: crate::analysis::QualitySnapshot {
            total_nodes: quality.total_nodes,
            missing_descriptions: quality.missing_descriptions,
            missing_facts: quality.missing_facts,
            duplicate_pairs: quality.duplicate_pairs,
            edge_gaps: crate::analysis::EdgeGapSnapshot {
                datastore_candidates: quality.edge_gaps.datastore_candidates,
                datastore_missing_stored_in: quality.edge_gaps.datastore_missing_stored_in,
                process_candidates: quality.edge_gaps.process_candidates,
                process_missing_incoming: quality.edge_gaps.process_missing_incoming,
            },
        },
        quality_score,
        feedback,
        cost,
        golden,
    };

    if args.json {
        let rendered = serde_json::to_string_pretty(&report).unwrap_or_else(|_| "{}".to_owned());
        return Ok(format!("{rendered}\n"));
    }

    let mut lines = vec![String::from("= baseline")];
    lines.push(format!("graph: {}", report.graph));
    lines.push(format!(
        "quality_score_0_100: {:.1}",
        report.quality_score.score_0_100
    ));
    lines.push(String::from("quality:"));
    lines.push(format!("- total_nodes: {}", report.quality.total_nodes));
    lines.push(format!(
        "- missing_descriptions: {} ({:.1}%)",
        report.quality.missing_descriptions,
        report
            .quality_score
            .description_coverage
            .mul_add(-100.0, 100.0)
    ));
    lines.push(format!(
        "- missing_facts: {} ({:.1}%)",
        report.quality.missing_facts,
        report.quality_score.facts_coverage.mul_add(-100.0, 100.0)
    ));
    lines.push(format!(
        "- duplicate_pairs: {}",
        report.quality.duplicate_pairs
    ));
    lines.push(format!(
        "- edge_gaps: {} / {}",
        report.quality.edge_gaps.total_missing(),
        report.quality.edge_gaps.total_candidates()
    ));

    lines.push(String::from("feedback:"));
    lines.push(format!("- entries: {}", report.feedback.entries));
    lines.push(format!(
        "- YES/NO/NIL/PICK: {}/{}/{}/{}",
        report.feedback.yes, report.feedback.no, report.feedback.nil, report.feedback.pick
    ));
    lines.push(format!(
        "- yes_rate: {:.1}%",
        report.feedback.yes_rate * 100.0
    ));
    lines.push(format!(
        "- no_rate: {:.1}%",
        report.feedback.no_rate * 100.0
    ));

    lines.push(String::from("cost:"));
    lines.push(format!(
        "- find_operations: {}",
        report.cost.find_operations
    ));
    lines.push(format!(
        "- feedback_events: {}",
        report.cost.feedback_events
    ));
    lines.push(format!(
        "- feedback_events_per_1000_find_ops: {:.1}",
        report.cost.feedback_events_per_1000_find_ops
    ));
    lines.push(format!("- token_cost: {}", report.cost.token_cost_note));

    if let Some(golden) = report.golden {
        lines.push(String::from("golden_set:"));
        lines.push(format!("- cases: {}", golden.cases));
        lines.push(format!("- hit_rate: {:.1}%", golden.hit_rate * 100.0));
        lines.push(format!("- top1_rate: {:.1}%", golden.top1_rate * 100.0));
        lines.push(format!("- mrr: {:.3}", golden.mrr));
        lines.push(format!("- ndcg@k: {:.3}", golden.ndcg_at_k));
    }

    Ok(format!("{}\n", lines.join("\n")))
}

#[derive(Debug, Clone)]
struct FeedbackLogEntry {
    ts_ms: String,
    uid: String,
    action: String,
    pick: Option<String>,
    selected: Option<String>,
    graph: String,
    queries: String,
}

impl FeedbackLogEntry {
    fn parse(line: &str) -> Option<Self> {
        // Expected (tab-separated):
        // ts_ms=...\tuid=...\taction=...\tpick=...\tselected=...\tgraph=...\tqueries=...
        let mut ts_ms: Option<String> = None;
        let mut uid: Option<String> = None;
        let mut action: Option<String> = None;
        let mut pick: Option<String> = None;
        let mut selected: Option<String> = None;
        let mut graph: Option<String> = None;
        let mut queries: Option<String> = None;

        for part in line.split('\t') {
            let (k, v) = part.split_once('=')?;
            let v = v.trim();
            match k {
                "ts_ms" => ts_ms = Some(v.to_owned()),
                "uid" => uid = Some(v.to_owned()),
                "action" => action = Some(v.to_owned()),
                "pick" => {
                    if v != "-" {
                        pick = Some(v.to_owned());
                    }
                }
                "selected" => {
                    if v != "-" {
                        selected = Some(v.to_owned());
                    }
                }
                "graph" => {
                    if v != "-" {
                        graph = Some(v.to_owned());
                    }
                }
                "queries" => {
                    if v != "-" {
                        queries = Some(v.to_owned());
                    }
                }
                _ => {}
            }
        }

        Some(Self {
            ts_ms: ts_ms?,
            uid: uid?,
            action: action?,
            pick,
            selected,
            graph: graph.unwrap_or_default(),
            queries: queries.unwrap_or_default(),
        })
    }
}

// ---------------------------------------------------------------------------
// Graph lifecycle helpers
// ---------------------------------------------------------------------------

/// Returns the default graph root directory for this environment.
///
/// This is primarily exposed for embedding use-cases (e.g. kg-mcp), so they
/// can resolve graph paths consistently with the CLI.
pub fn default_graph_root(cwd: &Path) -> PathBuf {
    let home = std::env::var_os("HOME")
        .map(PathBuf::from)
        .or_else(|| std::env::var_os("USERPROFILE").map(PathBuf::from));
    graph_root_from(home.as_deref(), cwd)
}

fn graph_root_from(home: Option<&Path>, cwd: &Path) -> PathBuf {
    match home {
        Some(home) => home.join(".kg").join("graphs"),
        None => cwd.join(".kg").join("graphs"),
    }
}

/// Resolve a graph identifier/path to an on-disk JSON file.
///
/// This is primarily exposed for embedding use-cases (e.g. kg-mcp), so they
/// can resolve graph paths consistently with the CLI.
pub fn resolve_graph_path(cwd: &Path, graph_root: &Path, graph: &str) -> Result<PathBuf> {
    let store = graph_store(cwd, graph_root, false)?;
    store.resolve_graph_path(graph)
}

/// Load the MCP nudge probability from `.kg.toml`, defaulting to 20.
pub fn feedback_nudge_percent(cwd: &Path) -> Result<u8> {
    Ok(config::KgConfig::discover(cwd)?
        .map(|(_, config)| config.nudge_percent())
        .unwrap_or(config::DEFAULT_NUDGE_PERCENT))
}

/// Resolve and (if needed) persist `user_short_uid` for sidecar logging.
pub fn sidecar_user_short_uid(cwd: &Path) -> String {
    config::ensure_user_short_uid(cwd)
}

/// Best-effort append of an `F` feedback record to `<graph>.kglog`.
pub fn append_kg_feedback(graph_path: &Path, user_short_uid: &str, node_id: &str, feedback: &str) {
    let _ = kg_sidecar::append_feedback_with_uid(graph_path, user_short_uid, node_id, feedback);
}

// ---------------------------------------------------------------------------
// Validation renderers (check vs audit differ in header only)
// ---------------------------------------------------------------------------

pub(crate) fn render_check(graph: &GraphFile, cwd: &Path, args: &CheckArgs) -> String {
    let report = validate_graph(graph, cwd, args.deep, args.base_dir.as_deref());
    format_validation_report(
        "check",
        &report.errors,
        &report.warnings,
        args.errors_only,
        args.warnings_only,
        args.limit,
    )
}

pub(crate) fn render_audit(graph: &GraphFile, cwd: &Path, args: &AuditArgs) -> String {
    let report = validate_graph(graph, cwd, args.deep, args.base_dir.as_deref());
    format_validation_report(
        "audit",
        &report.errors,
        &report.warnings,
        args.errors_only,
        args.warnings_only,
        args.limit,
    )
}

fn format_validation_report(
    header: &str,
    errors: &[String],
    warnings: &[String],
    errors_only: bool,
    warnings_only: bool,
    limit: usize,
) -> String {
    let mut lines = vec![format!("= {header}")];
    lines.push(format!(
        "status: {}",
        if errors.is_empty() {
            "VALID"
        } else {
            "INVALID"
        }
    ));
    lines.push(format!("errors: {}", errors.len()));
    lines.push(format!("warnings: {}", warnings.len()));
    if !warnings_only {
        lines.push("error-list:".to_owned());
        for error in errors.iter().take(limit) {
            lines.push(format!("- {error}"));
        }
    }
    if !errors_only {
        lines.push("warning-list:".to_owned());
        for warning in warnings.iter().take(limit) {
            lines.push(format!("- {warning}"));
        }
    }
    format!("{}\n", lines.join("\n"))
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    fn fixture_graph() -> GraphFile {
        serde_json::from_str(include_str!("../graph-example-fridge.json")).expect("fixture graph")
    }

    fn exec_safe(args: &[&str], cwd: &Path) -> Result<String> {
        run_args_safe(args.iter().map(OsString::from), cwd)
    }

    #[test]
    fn graph_root_prefers_home_directory() {
        let cwd = Path::new("/tmp/workspace");
        let home = Path::new("/tmp/home");
        assert_eq!(
            graph_root_from(Some(home), cwd),
            PathBuf::from("/tmp/home/.kg/graphs")
        );
        assert_eq!(
            graph_root_from(None, cwd),
            PathBuf::from("/tmp/workspace/.kg/graphs")
        );
    }

    #[test]
    fn get_renders_compact_symbolic_view() {
        let graph = fixture_graph();
        let node = graph.node_by_id("concept:refrigerator").expect("node");
        let rendered = output::render_node(&graph, node, false);
        assert!(rendered.contains("# concept:refrigerator | Lodowka"));
        assert!(rendered.contains("aka: Chlodziarka, Fridge"));
        assert!(rendered.contains("-> HAS | concept:cooling_chamber | Komora Chlodzenia"));
        assert!(rendered.contains("-> HAS | concept:temperature | Temperatura"));
    }

    #[test]
    fn help_lists_mvp_commands() {
        let help = Cli::try_parse_from(["kg", "--help"]).expect_err("help exits");
        let rendered = help.to_string();
        assert!(!rendered.contains("â–“ â–„â–„"));
        assert!(rendered.contains("create"));
        assert!(rendered.contains("list"));
        assert!(rendered.contains("feedback-log"));
        assert!(rendered.contains("fridge node"));
        assert!(rendered.contains("edge"));
        assert!(rendered.contains("quality"));
        assert!(rendered.contains("kg graph fridge stats"));
    }

    #[test]
    fn run_args_safe_returns_error_instead_of_exiting() {
        let dir = tempdir().expect("tempdir");
        let err = exec_safe(&["kg", "create"], dir.path()).expect_err("parse error");
        let rendered = err.to_string();
        assert!(rendered.contains("required arguments were not provided"));
        assert!(rendered.contains("<GRAPH_NAME>"));
    }

    #[test]
    fn colorize_cli_output_styles_key_lines() {
        let rendered = "? weather (1)\nscore: 1000\n# concept:rain | Rain [Concept]\n-> DEPENDS_ON | process:forecast | Forecast\n";
        let colored = colorize_cli_output(rendered);
        assert!(colored.contains("\x1b[1;33m? weather (1)\x1b[0m"));
        assert!(colored.contains("\x1b[1;35mscore: 1000\x1b[0m"));
        assert!(colored.contains("\x1b[1;36m# concept:rain | Rain [Concept]\x1b[0m"));
        assert!(colored.contains("\x1b[34m-> DEPENDS_ON | process:forecast | Forecast\x1b[0m"));
    }

    #[test]
    fn colorize_cli_output_leaves_json_unchanged() {
        let rendered = "{\n  \"nodes\": []\n}\n";
        assert_eq!(colorize_cli_output(rendered), rendered);
    }

    #[test]
    fn execute_clusters_sorts_by_relevance_then_size() {
        let mut graph = GraphFile::new("score");
        graph.nodes.push(Node {
            id: "@:cluster_0001".to_owned(),
            r#type: "@".to_owned(),
            name: "Cluster 1".to_owned(),
            properties: NodeProperties::default(),
            source_files: vec![],
        });
        graph.nodes.push(Node {
            id: "@:cluster_0002".to_owned(),
            r#type: "@".to_owned(),
            name: "Cluster 2".to_owned(),
            properties: NodeProperties::default(),
            source_files: vec![],
        });
        for id in ["concept:a", "concept:b", "concept:c", "concept:d"] {
            graph.nodes.push(Node {
                id: id.to_owned(),
                r#type: "Concept".to_owned(),
                name: id.to_owned(),
                properties: NodeProperties::default(),
                source_files: vec![],
            });
        }
        graph.edges.push(Edge {
            source_id: "@:cluster_0001".to_owned(),
            relation: "HAS".to_owned(),
            target_id: "concept:a".to_owned(),
            properties: EdgeProperties {
                detail: "0.95".to_owned(),
                ..Default::default()
            },
        });
        graph.edges.push(Edge {
            source_id: "@:cluster_0001".to_owned(),
            relation: "HAS".to_owned(),
            target_id: "concept:b".to_owned(),
            properties: EdgeProperties {
                detail: "0.85".to_owned(),
                ..Default::default()
            },
        });
        graph.edges.push(Edge {
            source_id: "@:cluster_0002".to_owned(),
            relation: "HAS".to_owned(),
            target_id: "concept:c".to_owned(),
            properties: EdgeProperties {
                detail: "0.70".to_owned(),
                ..Default::default()
            },
        });
        graph.edges.push(Edge {
            source_id: "@:cluster_0002".to_owned(),
            relation: "HAS".to_owned(),
            target_id: "concept:d".to_owned(),
            properties: EdgeProperties {
                detail: "0.65".to_owned(),
                ..Default::default()
            },
        });

        let rendered = render_clusters(
            &graph,
            &ClustersArgs {
                limit: 10,
                json: false,
                skill: None,
            },
        );
        let first = rendered.find("@:cluster_0001").expect("cluster 1 present");
        let second = rendered.find("@:cluster_0002").expect("cluster 2 present");
        assert!(first < second);
    }

    #[test]
    fn execute_clusters_gardener_mode_emits_actions() {
        let mut graph = GraphFile::new("score");
        graph.nodes.push(Node {
            id: "@:cluster_0001".to_owned(),
            r#type: "@".to_owned(),
            name: "Cluster 1".to_owned(),
            properties: NodeProperties::default(),
            source_files: vec![],
        });
        graph.nodes.push(Node {
            id: "concept:a".to_owned(),
            r#type: "Concept".to_owned(),
            name: "A".to_owned(),
            properties: NodeProperties::default(),
            source_files: vec![],
        });
        graph.edges.push(Edge {
            source_id: "@:cluster_0001".to_owned(),
            relation: "HAS".to_owned(),
            target_id: "concept:a".to_owned(),
            properties: EdgeProperties {
                detail: "0.9".to_owned(),
                ..Default::default()
            },
        });

        let rendered = render_clusters(
            &graph,
            &ClustersArgs {
                limit: 5,
                json: false,
                skill: Some(ClusterSkill::Gardener),
            },
        );
        assert!(rendered.contains("= gardener clusters"));
        assert!(rendered.contains("action: review cluster"));
    }

    #[test]
    fn find_latest_score_snapshot_picks_newest_timestamp() {
        let dir = tempdir().expect("tempdir");
        let graph_path = dir.path().join("fridge.kg");
        std::fs::write(&graph_path, "").expect("graph file");
        let cache_dir = crate::cache_paths::cache_root_for_graph(&graph_path);
        std::fs::create_dir_all(&cache_dir).expect("cache dir");
        let older = cache_dir.join("fridge.score.100.kg");
        let newer = cache_dir.join("fridge.score.200.kg");
        std::fs::write(&older, "").expect("older");
        std::fs::write(&newer, "").expect("newer");

        let latest = find_latest_score_snapshot(&graph_path)
            .expect("latest")
            .expect("some path");
        assert_eq!(latest, newer);
    }

    #[test]
    fn baseline_rejects_vector_mode() {
        let graph = fixture_graph();
        let err = eval_golden_set(
            &graph,
            &BaselineArgs {
                find_limit: 5,
                include_features: true,
                mode: CliFindMode::Vector,
                golden: None,
                json: false,
            },
        )
        .expect_err("vector mode should be rejected for baseline");
        assert!(
            err.to_string()
                .contains("baseline does not support --mode vector")
        );
    }
}