chasm-cli 2.0.0

Universal chat session manager - harvest, merge, and analyze AI chat history from VS Code, Cursor, and other editors
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
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
// Copyright (c) 2024-2026 Nervosys LLC
// SPDX-License-Identifier: AGPL-3.0-only
//! Harvest commands for collecting chat sessions from multiple providers
//!
//! The harvester scans for local and remote LLM providers, downloads all chat
//! sessions into a single SQLite database, and allows users to version-track
//! the database with git.

use anyhow::{Context, Result};
use chrono::{DateTime, Utc};
use colored::*;
use rusqlite::{params, Connection};
use serde::{Deserialize, Serialize};
use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::time::Duration;

use crate::browser::{get_installed_browsers, scan_browser_auth, BrowserType};
use crate::database::{ChatDatabase, ShareLinkParser};
use crate::models::ChatSession;
use crate::providers::{ProviderRegistry, ProviderType};
use crate::storage::parse_session_json;
use crate::workspace::{discover_workspaces, get_chat_sessions_from_workspace};

/// Check if a string is an empty code block marker (just ``` with no content)
fn is_empty_code_block(s: &str) -> bool {
    // Match patterns like "```", "```\n", "```language", "```\n```", "```\n\n```"
    let s = s.trim();
    if s == "```" {
        return true;
    }
    // Check for code block with just a language identifier and no content
    if s.starts_with("```") && !s.contains('\n') {
        return true;
    }
    // Check for empty code block with opening and closing (possibly with whitespace-only lines)
    let lines: Vec<&str> = s.lines().collect();
    if lines.len() >= 2 && lines[0].starts_with("```") && lines.last() == Some(&"```") {
        // Check if all lines between opening and closing are empty or whitespace
        let content_lines = &lines[1..lines.len() - 1];
        if content_lines.iter().all(|line| line.trim().is_empty()) {
            return true;
        }
    }
    false
}

/// Type alias for harvested session query result (id, provider, title, msg_count, created, last_msg, workspace)
type HarvestQueryResult = (String, String, String, i64, i64, i64, Option<String>);

/// Web-based LLM provider endpoint configuration
#[derive(Debug, Clone)]
struct WebProviderEndpoint {
    name: &'static str,
    url: &'static str,
    description: &'static str,
}

/// List of known web-based LLM provider endpoints to probe
const WEB_PROVIDERS: &[WebProviderEndpoint] = &[
    WebProviderEndpoint {
        name: "ChatGPT",
        url: "https://chat.openai.com",
        description: "OpenAI ChatGPT Web Interface",
    },
    WebProviderEndpoint {
        name: "Claude",
        url: "https://claude.ai",
        description: "Anthropic Claude Web Interface",
    },
    WebProviderEndpoint {
        name: "Gemini",
        url: "https://gemini.google.com",
        description: "Google Gemini Web Interface",
    },
    WebProviderEndpoint {
        name: "Perplexity",
        url: "https://www.perplexity.ai",
        description: "Perplexity AI Search Interface",
    },
    WebProviderEndpoint {
        name: "DeepSeek",
        url: "https://chat.deepseek.com",
        description: "DeepSeek Chat Interface",
    },
    WebProviderEndpoint {
        name: "Poe",
        url: "https://poe.com",
        description: "Quora Poe Multi-model Chat",
    },
    WebProviderEndpoint {
        name: "You.com",
        url: "https://you.com/chat",
        description: "You.com AI Chat",
    },
    WebProviderEndpoint {
        name: "HuggingChat",
        url: "https://huggingface.co/chat",
        description: "HuggingFace Chat Interface",
    },
    WebProviderEndpoint {
        name: "Copilot",
        url: "https://copilot.microsoft.com",
        description: "Microsoft Copilot Web Interface",
    },
    WebProviderEndpoint {
        name: "Mistral",
        url: "https://chat.mistral.ai",
        description: "Mistral AI Le Chat Interface",
    },
    WebProviderEndpoint {
        name: "Cohere",
        url: "https://coral.cohere.com",
        description: "Cohere Coral Chat Interface",
    },
    WebProviderEndpoint {
        name: "Groq",
        url: "https://groq.com",
        description: "Groq Fast Inference Interface",
    },
    WebProviderEndpoint {
        name: "Phind",
        url: "https://www.phind.com",
        description: "Phind AI Code Search",
    },
    WebProviderEndpoint {
        name: "Character.AI",
        url: "https://character.ai",
        description: "Character.AI Chat Interface",
    },
    WebProviderEndpoint {
        name: "Pi",
        url: "https://pi.ai",
        description: "Inflection Pi Personal AI",
    },
];

/// Scan for reachable web-based LLM providers (parallel)
fn scan_web_providers(timeout_secs: u64) -> Vec<String> {
    use std::sync::{Arc, Mutex};
    use std::thread;

    let reachable = Arc::new(Mutex::new(Vec::new()));
    let results = Arc::new(Mutex::new(Vec::new()));

    // Create threads for parallel scanning
    let handles: Vec<_> = WEB_PROVIDERS
        .iter()
        .map(|provider| {
            let reachable = Arc::clone(&reachable);
            let results = Arc::clone(&results);
            let timeout = timeout_secs;
            let name = provider.name;
            let url = provider.url;
            let desc = provider.description;

            thread::spawn(move || {
                let client = match reqwest::blocking::Client::builder()
                    .timeout(Duration::from_secs(timeout))
                    .connect_timeout(Duration::from_secs(timeout.min(3))) // Short connect timeout
                    .user_agent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36")
                    .build()
                {
                    Ok(c) => c,
                    Err(_) => return,
                };

                let result: (&str, bool, String, &str) = match client.head(url).send() {
                    Ok(response) => {
                        let status = response.status();
                        if status.is_success() || status.is_redirection() {
                            reachable.lock().unwrap().push(name.to_string());
                            (name, true, desc.to_string(), url)
                        } else {
                            (name, false, format!("HTTP {}", status.as_u16()), url)
                        }
                    }
                    Err(e) => {
                        let reason = if e.is_timeout() {
                            "timeout".to_string()
                        } else if e.is_connect() {
                            "connection failed".to_string()
                        } else {
                            "unreachable".to_string()
                        };
                        (name, false, reason, url)
                    }
                };

                results.lock().unwrap().push((
                    result.0.to_string(),
                    result.1,
                    result.2,
                    result.3.to_string(),
                ));
            })
        })
        .collect();

    // Wait for all threads to complete
    for handle in handles {
        let _ = handle.join();
    }

    // Print results in order
    let results = results.lock().unwrap();
    let mut sorted_results: Vec<_> = results.iter().collect();
    sorted_results.sort_by_key(|(name, _, _, _)| name.as_str());

    for (name, success, info, url) in sorted_results {
        if *success {
            println!(
                "   {} {}: {} ({})",
                "[+]".green(),
                name.bold(),
                "reachable".green(),
                info.dimmed()
            );
            println!("      {} {}", "`".dimmed(), url.dimmed());
        } else {
            println!(
                "   {} {}: {} ({})",
                "[-]".dimmed(),
                name,
                "blocked or unavailable".dimmed(),
                info.dimmed()
            );
        }
    }

    let result = reachable.lock().unwrap().clone();
    result
}

/// Scan browser cookies for authenticated web LLM providers
fn scan_browser_authentication(
    verbose: bool,
) -> (std::collections::HashMap<String, Vec<BrowserType>>, usize) {
    use crate::browser::scan_browser_auth_verbose;
    use std::collections::HashMap;

    let installed = get_installed_browsers();
    if installed.is_empty() {
        println!("   {} No supported browsers found", "[-]".dimmed());
        return (HashMap::new(), 0);
    }

    println!(
        "   {} Checking {} browser(s): {}",
        "[*]".blue(),
        installed.len(),
        installed
            .iter()
            .map(|b| b.name())
            .collect::<Vec<_>>()
            .join(", ")
    );

    let results = if verbose {
        scan_browser_auth_verbose()
    } else {
        scan_browser_auth()
    };

    // Group results by provider
    let mut authenticated: HashMap<String, Vec<BrowserType>> = HashMap::new();

    for result in results {
        if result.authenticated {
            authenticated
                .entry(result.provider.clone())
                .or_default()
                .push(result.browser);
        }
    }

    let count = authenticated.len();

    if authenticated.is_empty() {
        println!(
            "   {} No authenticated web LLM providers found",
            "[-]".dimmed()
        );
        println!(
            "      {} Log into ChatGPT, Claude, etc. in your browser to enable harvesting",
            "`".dimmed()
        );
    } else {
        for (provider, browsers) in &authenticated {
            let browser_names: Vec<_> = browsers.iter().map(|b| b.name()).collect();
            println!(
                "   {} {}: {} in {}",
                "[+]".green(),
                provider.bold(),
                "authenticated".green(),
                browser_names.join(", ")
            );
        }
    }

    (authenticated, count)
}

/// Configuration for the harvest database
#[allow(dead_code)]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HarvestConfig {
    /// Path to the harvest database
    pub db_path: PathBuf,
    /// Auto-commit changes to git
    pub auto_commit: bool,
    /// Providers to include (empty = all)
    pub include_providers: Vec<String>,
    /// Providers to exclude
    pub exclude_providers: Vec<String>,
    /// Include VS Code workspaces
    pub include_workspaces: bool,
    /// Last harvest timestamp
    pub last_harvest: Option<i64>,
}

#[allow(dead_code)]
impl Default for HarvestConfig {
    fn default() -> Self {
        Self {
            db_path: PathBuf::from("chat_sessions.db"),
            auto_commit: false,
            include_providers: Vec::new(),
            exclude_providers: Vec::new(),
            include_workspaces: true,
            last_harvest: None,
        }
    }
}

/// Statistics from a harvest operation
#[derive(Debug, Default)]
pub struct HarvestStats {
    pub providers_scanned: usize,
    pub workspaces_scanned: usize,
    pub sessions_found: usize,
    pub sessions_added: usize,
    pub sessions_updated: usize,
    pub sessions_skipped: usize,
    pub errors: Vec<String>,
}

/// A harvested session record
#[allow(dead_code)]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HarvestedSession {
    pub id: String,
    pub provider: String,
    pub provider_type: String,
    pub workspace_id: Option<String>,
    pub workspace_name: Option<String>,
    pub title: String,
    pub message_count: usize,
    pub created_at: i64,
    pub updated_at: i64,
    pub harvested_at: i64,
    pub session_json: String,
}

/// Initialize a harvest database at the specified path
pub fn harvest_init(path: Option<&str>, git_init: bool) -> Result<()> {
    let db_path = get_db_path(path)?;
    let db_dir = db_path.parent().unwrap_or(Path::new("."));

    println!("\n{} Initializing Harvest Database", "[H]".magenta().bold());
    println!("{}", "=".repeat(60));

    // Create directory if needed
    if !db_dir.exists() {
        fs::create_dir_all(db_dir)?;
        println!("{} Created directory: {}", "[+]".green(), db_dir.display());
    }

    // Check if database already exists
    if db_path.exists() {
        println!(
            "{} Database already exists: {}",
            "[!]".yellow(),
            db_path.display()
        );
        println!("   Use 'csm harvest run' to update it");
        return Ok(());
    }

    // Create the database
    create_harvest_database(&db_path)?;
    println!("{} Created database: {}", "[+]".green(), db_path.display());

    // Initialize git if requested
    if git_init {
        init_git_tracking(&db_path)?;
    }

    println!("\n{} Harvest database initialized!", "[+]".green().bold());
    println!("\nNext steps:");
    println!("  1. Run 'csm harvest scan' to see available providers");
    println!("  2. Run 'csm harvest run' to collect sessions");
    if !git_init {
        println!("  3. Run 'csm harvest git init' to enable version tracking");
    }

    Ok(())
}

/// Scan for available providers and workspaces
pub fn harvest_scan(
    show_sessions: bool,
    scan_web: bool,
    timeout_secs: u64,
    verbose: bool,
) -> Result<()> {
    println!("\n{} Scanning for Providers", "[H]".magenta().bold());
    println!("{}", "=".repeat(60));

    let registry = ProviderRegistry::new();
    let mut total_sessions = 0;
    let mut available_providers = Vec::new();

    // Scan LLM providers
    println!("\n{} LLM Providers:", "[*]".blue().bold());

    let provider_types = vec![
        ProviderType::Copilot,
        ProviderType::Cursor,
        ProviderType::CodexCli,
        ProviderType::DroidCli,
        ProviderType::GeminiCli,
        ProviderType::Ollama,
        ProviderType::Vllm,
        ProviderType::Foundry,
        ProviderType::LmStudio,
        ProviderType::LocalAI,
        ProviderType::TextGenWebUI,
        ProviderType::Jan,
        ProviderType::Gpt4All,
        ProviderType::Llamafile,
        ProviderType::OpenAI,
        ProviderType::ChatGPT,
        ProviderType::Anthropic,
        ProviderType::Perplexity,
        ProviderType::DeepSeek,
        ProviderType::Gemini,
    ];

    for pt in &provider_types {
        if let Some(provider) = registry.get_provider(*pt) {
            let available = provider.is_available();
            let session_count = if available {
                provider.list_sessions().map(|s| s.len()).unwrap_or(0)
            } else {
                0
            };

            if available {
                available_providers.push((*pt, session_count));
                total_sessions += session_count;

                let status = if session_count > 0 {
                    format!(
                        "{} {} sessions",
                        "+".green(),
                        session_count.to_string().cyan()
                    )
                } else {
                    format!("{} no sessions", "+".green())
                };

                println!(
                    "   {} {}: {}",
                    "[+]".green(),
                    provider.name().bold(),
                    status
                );

                if show_sessions && session_count > 0 {
                    if let Ok(sessions) = provider.list_sessions() {
                        for session in sessions.iter().take(3) {
                            println!("      {} {}", "`".dimmed(), session.title().dimmed());
                        }
                        if sessions.len() > 3 {
                            println!("      {} ... and {} more", "`".dimmed(), sessions.len() - 3);
                        }
                    }
                }

                if let Some(path) = provider.sessions_path() {
                    println!(
                        "      {} {}",
                        "`".dimmed(),
                        path.display().to_string().dimmed()
                    );
                }
            }
        }
    }

    // Scan VS Code workspaces
    println!("\n{} VS Code Workspaces:", "[*]".blue().bold());

    match discover_workspaces() {
        Ok(workspaces) => {
            let workspaces_with_sessions: Vec<_> = workspaces
                .iter()
                .filter(|ws| ws.chat_session_count > 0)
                .collect();

            let ws_sessions: usize = workspaces_with_sessions
                .iter()
                .map(|ws| ws.chat_session_count)
                .sum();

            println!(
                "   {} {} workspaces with {} sessions",
                "[+]".green(),
                workspaces_with_sessions.len().to_string().cyan(),
                ws_sessions.to_string().cyan()
            );

            if show_sessions {
                for ws in workspaces_with_sessions.iter().take(5) {
                    let name = ws
                        .project_path
                        .clone()
                        .unwrap_or_else(|| ws.hash[..8.min(ws.hash.len())].to_string());
                    println!(
                        "      {} {} ({} sessions)",
                        "`".dimmed(),
                        name.dimmed(),
                        ws.chat_session_count
                    );
                }
                if workspaces_with_sessions.len() > 5 {
                    println!(
                        "      {} ... and {} more workspaces",
                        "`".dimmed(),
                        workspaces_with_sessions.len() - 5
                    );
                }
            }

            total_sessions += ws_sessions;
        }
        Err(e) => {
            println!("   {} Failed to scan workspaces: {}", "[!]".yellow(), e);
        }
    }

    // Scan web-based LLM providers if requested
    let mut web_providers_found = Vec::new();
    let mut authenticated_count = 0;
    if scan_web {
        // First check browser authentication (no network requests)
        println!("\n{} Browser Authentication:", "[*]".blue().bold());
        let (auth_results, auth_count) = scan_browser_authentication(verbose);
        authenticated_count = auth_count;

        // Then probe web endpoints
        println!("\n{} Web LLM Provider Endpoints:", "[*]".blue().bold());
        web_providers_found = scan_web_providers(timeout_secs);

        // Show which authenticated providers are reachable
        if !auth_results.is_empty() {
            println!("\n{} Authenticated Provider Sessions:", "[*]".blue().bold());
            for (provider, browsers) in &auth_results {
                let browser_list: Vec<_> = browsers.iter().map(|b| b.name()).collect();
                let reachable = web_providers_found.iter().any(|p| p == provider);
                let status = if reachable {
                    format!("{} (reachable)", "ready to harvest".green())
                } else {
                    format!("{}", "authenticated but endpoint blocked".yellow())
                };
                println!(
                    "   {} {}: {} via {}",
                    "[+]".green(),
                    provider.bold(),
                    status,
                    browser_list.join(", ").dimmed()
                );
            }
        }
    }

    // Summary
    println!("\n{} Summary:", "[*]".green().bold());
    println!(
        "   {} local providers available",
        available_providers.len().to_string().cyan()
    );
    if scan_web {
        println!(
            "   {} web providers reachable",
            web_providers_found.len().to_string().cyan()
        );
        println!(
            "   {} web providers authenticated",
            authenticated_count.to_string().cyan()
        );
    }
    println!(
        "   {} total sessions to harvest",
        total_sessions.to_string().truecolor(252, 152, 103)
    );

    Ok(())
}

/// Run the harvest operation
pub fn harvest_run(
    path: Option<&str>,
    providers: Option<&[String]>,
    exclude: Option<&[String]>,
    incremental: bool,
    auto_commit: bool,
    message: Option<&str>,
) -> Result<()> {
    let db_path = get_db_path(path)?;

    println!("\n{} Running Harvest", "[H]".magenta().bold());
    println!("{}", "=".repeat(60));

    // Ensure database exists
    if !db_path.exists() {
        println!("{} Database not found, creating...", "[*]".blue());
        create_harvest_database(&db_path)?;
    }

    let conn = Connection::open(&db_path)?;

    // Enable WAL mode and set pragmas for large databases
    conn.execute_batch(
        "PRAGMA journal_mode = WAL;
         PRAGMA synchronous = NORMAL;
         PRAGMA cache_size = -64000;",
    )?;

    let mut stats = HarvestStats::default();

    // Get last harvest time for incremental updates
    let last_harvest: Option<i64> = if incremental {
        conn.query_row("SELECT MAX(harvested_at) FROM sessions", [], |row| {
            row.get(0)
        })
        .ok()
    } else {
        None
    };

    if let Some(ts) = last_harvest {
        let dt = DateTime::from_timestamp_millis(ts)
            .map(|d| d.format("%Y-%m-%d %H:%M:%S").to_string())
            .unwrap_or_default();
        println!("{} Incremental harvest since: {}", "[*]".blue(), dt);
    }

    let registry = ProviderRegistry::new();
    let include_providers = providers.map(|p| p.to_vec());
    let exclude_providers = exclude.map(|p| p.to_vec()).unwrap_or_default();

    // Harvest from LLM providers
    println!("\n{} Harvesting from providers...", "[*]".blue());

    let provider_types = vec![
        ProviderType::Copilot,
        ProviderType::Cursor,
        ProviderType::ClaudeCode,
        ProviderType::CodexCli,
        ProviderType::DroidCli,
        ProviderType::GeminiCli,
        ProviderType::OpenCode,
        ProviderType::OpenClaw,
        ProviderType::Antigravity,
        ProviderType::Ollama,
        ProviderType::Vllm,
        ProviderType::Foundry,
        ProviderType::LmStudio,
        ProviderType::LocalAI,
        ProviderType::TextGenWebUI,
        ProviderType::Jan,
        ProviderType::Gpt4All,
        ProviderType::Llamafile,
    ];

    for pt in &provider_types {
        let provider_name = pt.display_name().to_lowercase();

        // Check include/exclude filters
        if let Some(ref include) = include_providers {
            if !include
                .iter()
                .any(|p| provider_name.contains(&p.to_lowercase()))
            {
                continue;
            }
        }
        if exclude_providers
            .iter()
            .any(|p| provider_name.contains(&p.to_lowercase()))
        {
            continue;
        }

        if let Some(provider) = registry.get_provider(*pt) {
            if !provider.is_available() {
                continue;
            }

            stats.providers_scanned += 1;

            match provider.list_sessions() {
                Ok(sessions) => {
                    for session in sessions {
                        stats.sessions_found += 1;

                        // Check if session should be skipped (incremental)
                        if let Some(last) = last_harvest {
                            if session.last_message_date <= last {
                                stats.sessions_skipped += 1;
                                continue;
                            }
                        }

                        match insert_or_update_session(
                            &conn,
                            &session,
                            pt.display_name(),
                            None,
                            None,
                            None,   // provider_version
                            3,      // schema_version (V3)
                            "json", // file_format
                            None,   // workspace_path
                        ) {
                            Ok(updated) => {
                                if updated {
                                    stats.sessions_updated += 1;
                                } else {
                                    stats.sessions_added += 1;
                                }
                            }
                            Err(e) => {
                                stats.errors.push(format!("{}: {}", session.title(), e));
                            }
                        }
                    }

                    let session_count = stats.sessions_added + stats.sessions_updated;
                    if session_count > 0 {
                        println!(
                            "   {} {}: {} sessions",
                            "[+]".green(),
                            provider.name(),
                            session_count.to_string().cyan()
                        );
                    }
                }
                Err(e) => {
                    stats.errors.push(format!("{}: {}", provider.name(), e));
                }
            }
        }
    }

    // Harvest from VS Code workspaces
    if include_providers.is_none()
        || include_providers
            .as_ref()
            .map(|p| {
                p.iter()
                    .any(|x| x == "copilot" || x == "vscode" || x == "workspace")
            })
            .unwrap_or(false)
    {
        println!("\n{} Harvesting from VS Code workspaces...", "[*]".blue());

        if let Ok(workspaces) = discover_workspaces() {
            for ws in &workspaces {
                if ws.chat_session_count == 0 {
                    continue;
                }

                stats.workspaces_scanned += 1;

                if let Ok(sessions) = get_chat_sessions_from_workspace(&ws.workspace_path) {
                    for swp in sessions {
                        stats.sessions_found += 1;

                        // Check if session should be skipped (incremental)
                        if let Some(last) = last_harvest {
                            if swp.session.last_message_date <= last {
                                stats.sessions_skipped += 1;
                                continue;
                            }
                        }

                        let ws_name = ws.project_path.clone();
                        let ws_path = ws.workspace_path.to_string_lossy().to_string();

                        match insert_or_update_session(
                            &conn,
                            &swp.session,
                            "GitHub Copilot",
                            Some(&ws.hash),
                            ws_name.as_deref(),
                            None,           // provider_version
                            3,              // schema_version (V3)
                            "json",         // file_format
                            Some(&ws_path), // workspace_path
                        ) {
                            Ok(updated) => {
                                if updated {
                                    stats.sessions_updated += 1;
                                } else {
                                    stats.sessions_added += 1;
                                }
                            }
                            Err(e) => {
                                stats.errors.push(format!("{}: {}", swp.session.title(), e));
                            }
                        }
                    }
                }
            }

            println!(
                "   {} Workspaces: {} scanned",
                "[+]".green(),
                stats.workspaces_scanned.to_string().cyan()
            );
        }
    }

    // Harvest from web-based cloud providers (ChatGPT, Claude, etc.)
    let include_list: Vec<String> = include_providers.clone().unwrap_or_default();
    harvest_web_providers(&conn, &mut stats, &include_list, &exclude_providers)?;

    // Update metadata
    update_harvest_metadata(&conn)?;

    // Print summary
    println!("\n{} Harvest Complete:", "[+]".green().bold());
    println!(
        "   {} providers scanned",
        stats.providers_scanned.to_string().cyan()
    );
    println!(
        "   {} workspaces scanned",
        stats.workspaces_scanned.to_string().cyan()
    );
    println!(
        "   {} sessions found",
        stats.sessions_found.to_string().cyan()
    );
    println!(
        "   {} sessions added",
        stats.sessions_added.to_string().green()
    );
    println!(
        "   {} sessions updated",
        stats.sessions_updated.to_string().yellow()
    );
    if stats.sessions_skipped > 0 {
        println!(
            "   {} sessions skipped (unchanged)",
            stats.sessions_skipped.to_string().dimmed()
        );
    }

    if !stats.errors.is_empty() {
        println!("\n{} Errors ({}):", "[!]".red(), stats.errors.len());
        for (i, err) in stats.errors.iter().take(5).enumerate() {
            println!("   {}. {}", i + 1, err);
        }
        if stats.errors.len() > 5 {
            println!("   ... and {} more errors", stats.errors.len() - 5);
        }
    }

    // Auto-commit if requested
    if auto_commit && (stats.sessions_added > 0 || stats.sessions_updated > 0) {
        println!("\n{} Auto-committing changes...", "[*]".blue());
        let commit_msg = message.unwrap_or("Harvest: update chat sessions");
        if let Err(e) = git_commit_harvest(&db_path, commit_msg) {
            println!("{} Git commit failed: {}", "[!]".yellow(), e);
        } else {
            println!("{} Changes committed", "[+]".green());
        }
    }

    println!("\nDatabase: {}", db_path.display());

    Ok(())
}

/// Show harvest database status
pub fn harvest_status(path: Option<&str>) -> Result<()> {
    let db_path = get_db_path(path)?;

    println!("\n{} Harvest Database Status", "[H]".magenta().bold());
    println!("{}", "=".repeat(60));

    if !db_path.exists() {
        println!(
            "{} Database not found: {}",
            "[!]".yellow(),
            db_path.display()
        );
        println!("   Run 'csm harvest init' to create one");
        return Ok(());
    }

    let conn = Connection::open(&db_path)?;

    // Get session counts by provider
    let mut stmt = conn.prepare(
        "SELECT provider, COUNT(*) as count, SUM(message_count) as messages 
         FROM sessions 
         GROUP BY provider 
         ORDER BY count DESC",
    )?;

    let provider_stats: Vec<(String, i64, i64)> = stmt
        .query_map([], |row| {
            Ok((
                row.get(0)?,
                row.get(1)?,
                row.get::<_, Option<i64>>(2)?.unwrap_or(0),
            ))
        })?
        .filter_map(|r| r.ok())
        .collect();

    // Get total counts
    let total_sessions: i64 = conn
        .query_row("SELECT COUNT(*) FROM sessions", [], |row| row.get(0))
        .unwrap_or(0);

    let total_messages: i64 = conn
        .query_row(
            "SELECT COALESCE(SUM(message_count), 0) FROM sessions",
            [],
            |row| row.get(0),
        )
        .unwrap_or(0);

    // Get last harvest time
    let last_harvest: Option<i64> = conn
        .query_row("SELECT MAX(harvested_at) FROM sessions", [], |row| {
            row.get(0)
        })
        .ok()
        .flatten();

    // Get oldest and newest sessions
    let oldest: Option<i64> = conn
        .query_row("SELECT MIN(created_at) FROM sessions", [], |row| row.get(0))
        .ok()
        .flatten();

    let newest: Option<i64> = conn
        .query_row("SELECT MAX(updated_at) FROM sessions", [], |row| row.get(0))
        .ok()
        .flatten();

    println!("{} Database: {}", "[*]".blue(), db_path.display());
    println!(
        "{} {}: {}",
        "[*]".blue(),
        "Total Sessions".truecolor(171, 157, 242),
        total_sessions.to_string().truecolor(252, 152, 103)
    );
    println!(
        "{} {}: {}",
        "[*]".blue(),
        "Total Messages".truecolor(171, 157, 242),
        total_messages.to_string().truecolor(252, 152, 103)
    );

    if let Some(ts) = last_harvest {
        let dt = DateTime::from_timestamp_millis(ts)
            .map(|d| d.format("%Y-%m-%d %H:%M:%S").to_string())
            .unwrap_or_else(|| "Unknown".to_string());
        println!("{} Last Harvest: {}", "[*]".blue(), dt);
    }

    if let (Some(old), Some(new)) = (oldest, newest) {
        let old_dt = DateTime::from_timestamp_millis(old)
            .map(|d| d.format("%Y-%m-%d").to_string())
            .unwrap_or_default();
        let new_dt = DateTime::from_timestamp_millis(new)
            .map(|d| d.format("%Y-%m-%d").to_string())
            .unwrap_or_default();
        println!("{} Date Range: {} to {}", "[*]".blue(), old_dt, new_dt);
    }

    if !provider_stats.is_empty() {
        println!("\n{} Sessions by Provider:", "[*]".blue());
        for (provider, count, messages) in &provider_stats {
            println!(
                "   {} {}: {} sessions, {} messages",
                "[+]".green(),
                provider.bold(),
                count.to_string().cyan(),
                messages.to_string().dimmed()
            );
        }
    }

    // Check git status
    let db_dir = db_path.parent().unwrap_or(Path::new("."));
    if db_dir.join(".git").exists()
        || db_path
            .parent()
            .map(|p| p.join(".git").exists())
            .unwrap_or(false)
    {
        println!("\n{} Git Status:", "[*]".blue());

        let output = Command::new("git")
            .current_dir(db_dir)
            .args([
                "status",
                "--porcelain",
                db_path.file_name().unwrap().to_str().unwrap(),
            ])
            .output();

        match output {
            Ok(out) => {
                let status = String::from_utf8_lossy(&out.stdout);
                if status.is_empty() {
                    println!("   {} No uncommitted changes", "[+]".green());
                } else {
                    println!("   {} Uncommitted changes detected", "[!]".yellow());
                    println!("   Run 'csm harvest git commit' to save changes");
                }
            }
            Err(_) => {
                println!("   {} Unable to check git status", "[!]".yellow());
            }
        }
    } else {
        println!("\n{} Git tracking not enabled", "[i]".dimmed());
        println!("   Run 'csm harvest git init' to enable version tracking");
    }

    Ok(())
}

/// List sessions in the harvest database
pub fn harvest_list(
    path: Option<&str>,
    provider: Option<&str>,
    limit: usize,
    search: Option<&str>,
) -> Result<()> {
    let db_path = get_db_path(path)?;

    if !db_path.exists() {
        println!(
            "{} Database not found: {}",
            "[!]".yellow(),
            db_path.display()
        );
        return Ok(());
    }

    let conn = Connection::open(&db_path)?;

    let mut query = String::from(
        "SELECT id, provider, title, message_count, created_at, updated_at, workspace_name 
         FROM sessions WHERE 1=1",
    );
    let mut params_vec: Vec<Box<dyn rusqlite::ToSql>> = Vec::new();

    if let Some(p) = provider {
        query.push_str(" AND LOWER(provider) LIKE ?");
        params_vec.push(Box::new(format!("%{}%", p.to_lowercase())));
    }

    if let Some(s) = search {
        query.push_str(" AND (LOWER(title) LIKE ? OR LOWER(id) LIKE ?)");
        let pattern = format!("%{}%", s.to_lowercase());
        params_vec.push(Box::new(pattern.clone()));
        params_vec.push(Box::new(pattern));
    }

    query.push_str(" ORDER BY updated_at DESC LIMIT ?");
    params_vec.push(Box::new(limit as i64));

    let mut stmt = conn.prepare(&query)?;

    // Build params slice
    let params_slice: Vec<&dyn rusqlite::ToSql> = params_vec.iter().map(|b| b.as_ref()).collect();

    let sessions: Vec<HarvestQueryResult> = stmt
        .query_map(params_slice.as_slice(), |row| {
            Ok((
                row.get(0)?,
                row.get(1)?,
                row.get(2)?,
                row.get(3)?,
                row.get(4)?,
                row.get(5)?,
                row.get(6)?,
            ))
        })?
        .filter_map(|r| r.ok())
        .collect();

    println!("\n{} Harvested Sessions", "[H]".magenta().bold());
    println!("{}", "=".repeat(60));

    if sessions.is_empty() {
        println!("{} No sessions found", "[i]".dimmed());
        return Ok(());
    }

    for (id, prov, title, msg_count, _created, updated, ws_name) in &sessions {
        let date = DateTime::from_timestamp_millis(*updated)
            .map(|d| d.format("%Y-%m-%d %H:%M").to_string())
            .unwrap_or_default();

        println!("\n{} {}", "[S]".cyan(), title.bold());
        println!("   ID: {}", &id[..16.min(id.len())].dimmed());
        println!(
            "   Provider: {} | Messages: {} | Updated: {}",
            prov.cyan(),
            msg_count.to_string().green(),
            date.dimmed()
        );
        if let Some(ws) = ws_name {
            println!("   Workspace: {}", ws.dimmed());
        }
    }

    println!(
        "\n{} Showing {} of available sessions",
        "[i]".dimmed(),
        sessions.len()
    );

    Ok(())
}

/// Export sessions from the harvest database
pub fn harvest_export(
    path: Option<&str>,
    output: &str,
    format: &str,
    provider: Option<&str>,
    session_ids: Option<&[String]>,
) -> Result<()> {
    let db_path = get_db_path(path)?;
    let output_path = PathBuf::from(output);

    if !db_path.exists() {
        anyhow::bail!("Database not found: {}", db_path.display());
    }

    let conn = Connection::open(&db_path)?;

    println!("\n{} Exporting Sessions", "[H]".magenta().bold());
    println!("{}", "=".repeat(60));

    // Build query
    let mut query = String::from("SELECT session_json FROM sessions WHERE 1=1");
    let mut params_vec: Vec<Box<dyn rusqlite::ToSql>> = Vec::new();

    if let Some(p) = provider {
        query.push_str(" AND LOWER(provider) LIKE ?");
        params_vec.push(Box::new(format!("%{}%", p.to_lowercase())));
    }

    if let Some(ids) = session_ids {
        let placeholders: Vec<&str> = ids.iter().map(|_| "?").collect();
        query.push_str(&format!(" AND id IN ({})", placeholders.join(",")));
        for id in ids {
            params_vec.push(Box::new(id.clone()));
        }
    }

    let mut stmt = conn.prepare(&query)?;
    let params_slice: Vec<&dyn rusqlite::ToSql> = params_vec.iter().map(|b| b.as_ref()).collect();

    let sessions: Vec<String> = stmt
        .query_map(params_slice.as_slice(), |row| row.get(0))?
        .filter_map(|r| r.ok())
        .collect();

    if sessions.is_empty() {
        println!("{} No sessions to export", "[i]".dimmed());
        return Ok(());
    }

    // Create output directory if needed
    if let Some(parent) = output_path.parent() {
        if !parent.exists() {
            fs::create_dir_all(parent)?;
        }
    }

    match format.to_lowercase().as_str() {
        "json" => {
            // Export as JSON array
            let parsed: Vec<serde_json::Value> = sessions
                .iter()
                .filter_map(|s| serde_json::from_str(s).ok())
                .collect();
            let json_output = serde_json::to_string_pretty(&parsed)?;
            fs::write(&output_path, json_output)?;
        }
        "jsonl" => {
            // Export as JSON Lines
            let content: String = sessions
                .iter()
                .filter_map(|s| serde_json::from_str::<serde_json::Value>(s).ok())
                .map(|v| serde_json::to_string(&v).unwrap_or_default())
                .collect::<Vec<_>>()
                .join("\n");
            fs::write(&output_path, content)?;
        }
        "md" | "markdown" => {
            // Export as Markdown
            let mut md_content = String::from("# Chat Sessions Export\n\n");
            md_content.push_str(&format!(
                "Exported: {}\n\n",
                Utc::now().format("%Y-%m-%d %H:%M:%S")
            ));

            for session_json in &sessions {
                if let Ok(session) = parse_session_json(session_json) {
                    md_content.push_str(&format!("## {}\n\n", session.title()));
                    md_content.push_str(&format!("Messages: {}\n\n", session.request_count()));

                    for request in &session.requests {
                        if let Some(msg) = &request.message {
                            if let Some(text) = &msg.text {
                                md_content.push_str(&format!("### User\n\n{}\n\n", text));
                            }
                        }
                        // Extract response text from the JSON value
                        if let Some(response) = &request.response {
                            let response_text = response
                                .get("text")
                                .and_then(|v| v.as_str())
                                .or_else(|| response.get("content").and_then(|v| v.as_str()))
                                .or_else(|| {
                                    // Try to get from value array (older format)
                                    response
                                        .get("value")
                                        .and_then(|v| v.as_array())
                                        .and_then(|arr| arr.first())
                                        .and_then(|v| v.get("value"))
                                        .and_then(|v| v.as_str())
                                });

                            if let Some(text) = response_text {
                                md_content.push_str(&format!("### Assistant\n\n{}\n\n", text));
                            }
                        }
                    }
                    md_content.push_str("---\n\n");
                }
            }
            fs::write(&output_path, md_content)?;
        }
        _ => {
            anyhow::bail!("Unknown format: {}. Supported: json, jsonl, md", format);
        }
    }

    println!(
        "{} Exported {} sessions to {}",
        "[+]".green(),
        sessions.len().to_string().cyan(),
        output_path.display()
    );

    Ok(())
}

/// Git operations for harvest database
pub fn harvest_git_init(path: Option<&str>) -> Result<()> {
    let db_path = get_db_path(path)?;
    init_git_tracking(&db_path)
}

pub fn harvest_git_commit(path: Option<&str>, message: Option<&str>) -> Result<()> {
    let db_path = get_db_path(path)?;
    let msg = message.unwrap_or("Update harvest database");
    git_commit_harvest(&db_path, msg)
}

pub fn harvest_git_log(path: Option<&str>, count: usize) -> Result<()> {
    let db_path = get_db_path(path)?;
    let db_dir = db_path.parent().unwrap_or(Path::new("."));
    let db_name = db_path.file_name().unwrap().to_str().unwrap();

    println!("\n{} Harvest Git History", "[H]".magenta().bold());
    println!("{}", "=".repeat(60));

    let output = Command::new("git")
        .current_dir(db_dir)
        .args([
            "log",
            "--oneline",
            &format!("-{}", count),
            "--follow",
            "--",
            db_name,
        ])
        .output()
        .context("Failed to run git log")?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        if stderr.contains("does not have any commits") {
            println!("{} No commits yet", "[i]".dimmed());
        } else {
            anyhow::bail!("Git log failed: {}", stderr);
        }
        return Ok(());
    }

    let log = String::from_utf8_lossy(&output.stdout);
    if log.trim().is_empty() {
        println!("{} No commits found for {}", "[i]".dimmed(), db_name);
    } else {
        for line in log.lines() {
            let parts: Vec<&str> = line.splitn(2, ' ').collect();
            if parts.len() == 2 {
                println!("{} {} {}", "[C]".yellow(), parts[0].cyan(), parts[1]);
            } else {
                println!("{}", line);
            }
        }
    }

    Ok(())
}

pub fn harvest_git_diff(path: Option<&str>, commit: Option<&str>) -> Result<()> {
    let db_path = get_db_path(path)?;
    let db_dir = db_path.parent().unwrap_or(Path::new("."));
    let db_name = db_path.file_name().unwrap().to_str().unwrap();

    println!("\n{} Harvest Database Changes", "[H]".magenta().bold());
    println!("{}", "=".repeat(60));

    let mut args = vec!["diff", "--stat"];
    if let Some(c) = commit {
        args.push(c);
    }
    args.push("--");
    args.push(db_name);

    let output = Command::new("git")
        .current_dir(db_dir)
        .args(&args)
        .output()
        .context("Failed to run git diff")?;

    let diff = String::from_utf8_lossy(&output.stdout);
    if diff.trim().is_empty() {
        println!("{} No changes", "[+]".green());
    } else {
        println!("{}", diff);
    }

    Ok(())
}

pub fn harvest_git_restore(path: Option<&str>, commit: &str) -> Result<()> {
    let db_path = get_db_path(path)?;
    let db_dir = db_path.parent().unwrap_or(Path::new("."));
    let db_name = db_path.file_name().unwrap().to_str().unwrap();

    println!("\n{} Restoring Harvest Database", "[H]".magenta().bold());
    println!("{}", "=".repeat(60));

    // Create backup first
    let backup_path = db_path.with_extension("db.backup");
    if db_path.exists() {
        fs::copy(&db_path, &backup_path)?;
        println!(
            "{} Created backup: {}",
            "[+]".green(),
            backup_path.display()
        );
    }

    // Restore from commit
    let output = Command::new("git")
        .current_dir(db_dir)
        .args(["checkout", commit, "--", db_name])
        .output()
        .context("Failed to run git checkout")?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        anyhow::bail!("Git restore failed: {}", stderr);
    }

    println!(
        "{} Restored database from commit: {}",
        "[+]".green(),
        commit
    );

    Ok(())
}

// ============================================================================
// Helper Functions
// ============================================================================

fn get_db_path(path: Option<&str>) -> Result<PathBuf> {
    if let Some(p) = path {
        return Ok(PathBuf::from(p));
    }

    // Check environment variable
    if let Ok(p) = std::env::var("CSM_HARVEST_DB") {
        return Ok(PathBuf::from(p));
    }

    // Default to current directory
    Ok(std::env::current_dir()?.join("chat_sessions.db"))
}

fn create_harvest_database(path: &Path) -> Result<()> {
    let conn = Connection::open(path)?;

    // Use larger page size and WAL mode for better performance with large session data
    conn.execute_batch(
        "PRAGMA page_size = 8192;
         PRAGMA journal_mode = WAL;
         PRAGMA synchronous = NORMAL;",
    )?;

    conn.execute_batch(
        r#"
        -- Sessions table (original harvest format)
        CREATE TABLE IF NOT EXISTS sessions (
            id TEXT PRIMARY KEY,
            provider TEXT NOT NULL,
            provider_type TEXT,
            provider_version TEXT,
            schema_version INTEGER DEFAULT 3,
            file_format TEXT DEFAULT 'json',
            workspace_id TEXT,
            workspace_name TEXT,
            workspace_path TEXT,
            title TEXT NOT NULL,
            message_count INTEGER DEFAULT 0,
            created_at INTEGER NOT NULL,
            updated_at INTEGER NOT NULL,
            harvested_at INTEGER NOT NULL,
            session_json TEXT NOT NULL
        );

        CREATE INDEX IF NOT EXISTS idx_sessions_provider ON sessions(provider);
        CREATE INDEX IF NOT EXISTS idx_sessions_workspace ON sessions(workspace_id);
        CREATE INDEX IF NOT EXISTS idx_sessions_updated ON sessions(updated_at);
        CREATE INDEX IF NOT EXISTS idx_sessions_workspace_path ON sessions(workspace_path);
        
        -- Enhanced messages table with raw markdown and metadata
        CREATE TABLE IF NOT EXISTS messages_v2 (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            session_id TEXT NOT NULL,
            message_index INTEGER NOT NULL,
            request_id TEXT,
            response_id TEXT,
            role TEXT NOT NULL,
            content_raw TEXT NOT NULL,
            content_markdown TEXT,
            model_id TEXT,
            timestamp INTEGER,
            is_canceled INTEGER DEFAULT 0,
            metadata_json TEXT,
            created_at INTEGER DEFAULT (strftime('%s', 'now') * 1000),
            FOREIGN KEY (session_id) REFERENCES sessions(id) ON DELETE CASCADE,
            UNIQUE(session_id, message_index, role)
        );
        
        CREATE INDEX IF NOT EXISTS idx_messages_v2_session ON messages_v2(session_id);
        CREATE INDEX IF NOT EXISTS idx_messages_v2_role ON messages_v2(role);
        CREATE INDEX IF NOT EXISTS idx_messages_v2_timestamp ON messages_v2(timestamp);
        
        -- Tool invocations within messages (file edits, terminal commands, etc.)
        CREATE TABLE IF NOT EXISTS tool_invocations (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            message_id INTEGER NOT NULL,
            session_id TEXT NOT NULL,
            tool_name TEXT NOT NULL,
            tool_call_id TEXT,
            invocation_index INTEGER DEFAULT 0,
            input_json TEXT,
            output_json TEXT,
            status TEXT DEFAULT 'pending',
            is_confirmed INTEGER DEFAULT 0,
            timestamp INTEGER,
            FOREIGN KEY (message_id) REFERENCES messages_v2(id) ON DELETE CASCADE,
            FOREIGN KEY (session_id) REFERENCES sessions(id) ON DELETE CASCADE
        );
        
        CREATE INDEX IF NOT EXISTS idx_tool_invocations_message ON tool_invocations(message_id);
        CREATE INDEX IF NOT EXISTS idx_tool_invocations_session ON tool_invocations(session_id);
        CREATE INDEX IF NOT EXISTS idx_tool_invocations_tool ON tool_invocations(tool_name);
        
        -- File changes/diffs associated with tool invocations
        CREATE TABLE IF NOT EXISTS file_changes (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            tool_invocation_id INTEGER,
            session_id TEXT NOT NULL,
            message_index INTEGER,
            file_path TEXT NOT NULL,
            change_type TEXT NOT NULL,
            old_content TEXT,
            new_content TEXT,
            diff_unified TEXT,
            line_start INTEGER,
            line_end INTEGER,
            timestamp INTEGER,
            FOREIGN KEY (tool_invocation_id) REFERENCES tool_invocations(id) ON DELETE CASCADE,
            FOREIGN KEY (session_id) REFERENCES sessions(id) ON DELETE CASCADE
        );
        
        CREATE INDEX IF NOT EXISTS idx_file_changes_tool ON file_changes(tool_invocation_id);
        CREATE INDEX IF NOT EXISTS idx_file_changes_session ON file_changes(session_id);
        CREATE INDEX IF NOT EXISTS idx_file_changes_path ON file_changes(file_path);
        
        -- Message-level checkpoints for versioning
        CREATE TABLE IF NOT EXISTS message_checkpoints (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            session_id TEXT NOT NULL,
            message_index INTEGER NOT NULL,
            checkpoint_number INTEGER NOT NULL,
            content_hash TEXT NOT NULL,
            snapshot_json TEXT,
            file_state_json TEXT,
            created_at INTEGER DEFAULT (strftime('%s', 'now') * 1000),
            FOREIGN KEY (session_id) REFERENCES sessions(id) ON DELETE CASCADE,
            UNIQUE(session_id, message_index, checkpoint_number)
        );
        
        CREATE INDEX IF NOT EXISTS idx_message_checkpoints_session ON message_checkpoints(session_id);
        CREATE INDEX IF NOT EXISTS idx_sessions_title ON sessions(title);

        -- Messages table for full-text search
        CREATE TABLE IF NOT EXISTS messages (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            session_id TEXT NOT NULL,
            message_index INTEGER NOT NULL,
            role TEXT NOT NULL,
            content TEXT NOT NULL,
            created_at INTEGER,
            FOREIGN KEY (session_id) REFERENCES sessions(id) ON DELETE CASCADE,
            UNIQUE(session_id, message_index)
        );
        
        CREATE INDEX IF NOT EXISTS idx_messages_session ON messages(session_id);
        CREATE INDEX IF NOT EXISTS idx_messages_role ON messages(role);
        
        -- Checkpoints for version tracking
        CREATE TABLE IF NOT EXISTS checkpoints (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            session_id TEXT NOT NULL,
            checkpoint_number INTEGER NOT NULL,
            message TEXT,
            message_count INTEGER NOT NULL,
            content_hash TEXT NOT NULL,
            snapshot TEXT,
            created_at TEXT NOT NULL DEFAULT (datetime('now')),
            FOREIGN KEY (session_id) REFERENCES sessions(id) ON DELETE CASCADE,
            UNIQUE(session_id, checkpoint_number)
        );
        
        CREATE INDEX IF NOT EXISTS idx_checkpoints_session ON checkpoints(session_id);
        
        -- Share links for importing shared conversations
        CREATE TABLE IF NOT EXISTS share_links (
            id TEXT PRIMARY KEY,
            session_id TEXT,
            provider TEXT NOT NULL,
            url TEXT NOT NULL UNIQUE,
            share_id TEXT NOT NULL,
            title TEXT,
            imported INTEGER DEFAULT 0,
            imported_at INTEGER,
            created_at INTEGER NOT NULL,
            FOREIGN KEY (session_id) REFERENCES sessions(id) ON DELETE SET NULL
        );
        
        CREATE INDEX IF NOT EXISTS idx_share_links_provider ON share_links(provider);
        CREATE INDEX IF NOT EXISTS idx_share_links_imported ON share_links(imported);

        -- Harvest metadata
        CREATE TABLE IF NOT EXISTS harvest_metadata (
            key TEXT PRIMARY KEY,
            value TEXT NOT NULL
        );

        INSERT OR REPLACE INTO harvest_metadata (key, value) 
        VALUES ('version', '2.1'),
               ('created_at', datetime('now'));
               
        -- Full-text search for messages (standalone FTS table)
        CREATE VIRTUAL TABLE IF NOT EXISTS messages_fts USING fts5(
            content_raw
        );
        
        -- Triggers to keep FTS index in sync with messages_v2
        -- Note: messages_fts is a standalone FTS5 table, so use regular DELETE (not the
        -- external-content 'delete' command which causes SQL logic errors on standalone tables)
        CREATE TRIGGER IF NOT EXISTS messages_v2_ai AFTER INSERT ON messages_v2 BEGIN
            INSERT INTO messages_fts(rowid, content_raw) VALUES (new.id, new.content_raw);
        END;
        
        CREATE TRIGGER IF NOT EXISTS messages_v2_ad AFTER DELETE ON messages_v2 BEGIN
            DELETE FROM messages_fts WHERE rowid = old.id;
        END;
        
        CREATE TRIGGER IF NOT EXISTS messages_v2_au AFTER UPDATE ON messages_v2 BEGIN
            DELETE FROM messages_fts WHERE rowid = old.id;
            INSERT INTO messages_fts(rowid, content_raw) VALUES (new.id, new.content_raw);
        END;
        "#,
    )?;

    Ok(())
}

fn insert_or_update_session(
    conn: &Connection,
    session: &ChatSession,
    provider: &str,
    workspace_id: Option<&str>,
    workspace_name: Option<&str>,
    provider_version: Option<&str>,
    schema_version: u32,
    file_format: &str,
    workspace_path: Option<&str>,
) -> Result<bool> {
    let session_id = session
        .session_id
        .clone()
        .unwrap_or_else(|| uuid::Uuid::new_v4().to_string());

    let now = Utc::now().timestamp_millis();
    let session_json = serde_json::to_string(session)?;

    // Check if session exists
    let existing: Option<i64> = conn
        .query_row(
            "SELECT updated_at FROM sessions WHERE id = ?",
            [&session_id],
            |row| row.get(0),
        )
        .ok();

    let updated = existing.is_some();

    conn.execute(
        r#"
        INSERT OR REPLACE INTO sessions 
        (id, provider, provider_type, workspace_id, workspace_name, title, 
         message_count, created_at, updated_at, harvested_at, session_json,
         provider_version, schema_version, file_format, workspace_path)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        "#,
        params![
            session_id,
            provider,
            provider,
            workspace_id,
            workspace_name,
            session.title(),
            session.request_count() as i64,
            session.creation_date,
            session.last_message_date,
            now,
            session_json,
            provider_version,
            schema_version as i64,
            file_format,
            workspace_path,
        ],
    )?;

    // Populate enhanced message tables
    populate_enhanced_messages(conn, &session_id, session)?;

    Ok(updated)
}

/// Populate the enhanced messages_v2, tool_invocations, and file_changes tables
fn populate_enhanced_messages(
    conn: &Connection,
    session_id: &str,
    session: &ChatSession,
) -> Result<()> {
    // Delete existing messages for this session to avoid duplicates
    conn.execute("DELETE FROM messages_v2 WHERE session_id = ?", [session_id])?;
    conn.execute(
        "DELETE FROM tool_invocations WHERE session_id = ?",
        [session_id],
    )?;
    conn.execute(
        "DELETE FROM file_changes WHERE session_id = ?",
        [session_id],
    )?;

    for (idx, request) in session.requests.iter().enumerate() {
        let timestamp = request.timestamp;
        let request_id = request.request_id.as_deref();
        let response_id = request.response_id.as_deref();
        let model_id = request.model_id.as_deref();
        let is_canceled = request.is_canceled.unwrap_or(false);

        // Insert user message
        if let Some(ref message) = request.message {
            let content = message.text.clone().unwrap_or_default();
            if !content.is_empty() {
                let metadata = serde_json::json!({
                    "variable_data": request.variable_data,
                });

                conn.execute(
                    r#"
                    INSERT OR REPLACE INTO messages_v2 
                    (session_id, message_index, request_id, response_id, role, 
                     content_raw, content_markdown, model_id, timestamp, is_canceled, metadata_json)
                    VALUES (?, ?, ?, ?, 'user', ?, ?, ?, ?, 0, ?)
                    "#,
                    params![
                        session_id,
                        (idx * 2) as i64,
                        request_id,
                        response_id,
                        &content,
                        &content, // content_markdown same as raw for user messages
                        model_id,
                        timestamp,
                        serde_json::to_string(&metadata).ok(),
                    ],
                )?;
            }
        }

        // Insert assistant response with tool invocations
        if let Some(ref response) = request.response {
            let (content, tool_invocations) = extract_response_content_and_tools(response);

            if !content.is_empty() || !tool_invocations.is_empty() {
                let metadata = serde_json::json!({
                    "content_references": request.content_references,
                    "code_citations": request.code_citations,
                    "response_markdown_info": request.response_markdown_info,
                });

                conn.execute(
                    r#"
                    INSERT OR REPLACE INTO messages_v2 
                    (session_id, message_index, request_id, response_id, role, 
                     content_raw, content_markdown, model_id, timestamp, is_canceled, metadata_json)
                    VALUES (?, ?, ?, ?, 'assistant', ?, ?, ?, ?, ?, ?)
                    "#,
                    params![
                        session_id,
                        (idx * 2 + 1) as i64,
                        request_id,
                        response_id,
                        &content,
                        &content,
                        model_id,
                        timestamp,
                        is_canceled as i64,
                        serde_json::to_string(&metadata).ok(),
                    ],
                )?;

                // Get the message_id we just inserted
                let message_id: i64 = conn.last_insert_rowid();

                // Insert tool invocations and file changes
                for (inv_idx, invocation) in tool_invocations.iter().enumerate() {
                    insert_tool_invocation(
                        conn, message_id, session_id, inv_idx, invocation, timestamp,
                    )?;
                }
            }
        }
    }

    Ok(())
}

/// Extract response content and tool invocations from the response JSON
fn extract_response_content_and_tools(
    response: &serde_json::Value,
) -> (String, Vec<serde_json::Value>) {
    let mut text_parts = Vec::new();
    let mut tool_invocations = Vec::new();

    if let Some(items) = response.as_array() {
        for item in items {
            let kind = item.get("kind").and_then(|k| k.as_str()).unwrap_or("");

            match kind {
                "toolInvocationSerialized" => {
                    tool_invocations.push(item.clone());
                }
                "thinking" => {
                    // Skip thinking blocks
                    continue;
                }
                _ => {
                    if let Some(value) = item.get("value").and_then(|v| v.as_str()) {
                        // Filter out empty code block markers (```\n or just ```)
                        let trimmed = value.trim();
                        if !trimmed.is_empty() && !is_empty_code_block(trimmed) {
                            text_parts.push(value.to_string());
                        }
                    }
                }
            }
        }
    }

    (text_parts.join("\n\n"), tool_invocations)
}

/// Insert a tool invocation and any associated file changes
fn insert_tool_invocation(
    conn: &Connection,
    message_id: i64,
    session_id: &str,
    inv_idx: usize,
    invocation: &serde_json::Value,
    timestamp: Option<i64>,
) -> Result<()> {
    let tool_name = invocation
        .get("toolId")
        .and_then(|t| t.as_str())
        .unwrap_or("unknown");
    let tool_call_id = invocation.get("toolCallId").and_then(|t| t.as_str());
    let is_complete = invocation
        .get("isComplete")
        .and_then(|c| c.as_bool())
        .unwrap_or(false);
    let is_confirmed = invocation.get("isConfirmed");
    let tool_data = invocation.get("toolSpecificData");

    let input_json = tool_data.map(|d| serde_json::to_string(d).unwrap_or_default());
    let status = if is_complete { "complete" } else { "pending" };
    let confirmed = match is_confirmed {
        Some(v) => v
            .get("type")
            .and_then(|t| t.as_i64())
            .map(|t| t > 0)
            .unwrap_or(false),
        None => false,
    };

    conn.execute(
        r#"
        INSERT INTO tool_invocations 
        (message_id, session_id, tool_name, tool_call_id, invocation_index, 
         input_json, status, is_confirmed, timestamp)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
        "#,
        params![
            message_id,
            session_id,
            tool_name,
            tool_call_id,
            inv_idx as i64,
            input_json,
            status,
            confirmed as i64,
            timestamp,
        ],
    )?;

    let tool_invocation_id = conn.last_insert_rowid();

    // Extract and insert file changes based on tool type
    if let Some(data) = tool_data {
        insert_file_changes(conn, tool_invocation_id, session_id, data, timestamp)?;
    }

    Ok(())
}

/// Insert file changes from tool-specific data
fn insert_file_changes(
    conn: &Connection,
    tool_invocation_id: i64,
    session_id: &str,
    tool_data: &serde_json::Value,
    timestamp: Option<i64>,
) -> Result<()> {
    let kind = tool_data.get("kind").and_then(|k| k.as_str()).unwrap_or("");

    match kind {
        "terminal" => {
            // Terminal command execution
            if let Some(cmd_line) = tool_data.get("commandLine") {
                let original = cmd_line.get("original").and_then(|o| o.as_str());
                let edited = cmd_line.get("toolEdited").and_then(|e| e.as_str());
                let output = tool_data
                    .get("terminalCommandOutput")
                    .map(|o| serde_json::to_string(o).unwrap_or_default());

                conn.execute(
                    r#"
                    INSERT INTO file_changes 
                    (tool_invocation_id, session_id, file_path, change_type, 
                     old_content, new_content, diff_unified, timestamp)
                    VALUES (?, ?, '[terminal]', 'command', ?, ?, ?, ?)
                    "#,
                    params![
                        tool_invocation_id,
                        session_id,
                        original,
                        edited.or(original),
                        output,
                        timestamp,
                    ],
                )?;
            }
        }
        "replaceFile" | "editFile" => {
            // File edit with old/new strings
            let file_path = tool_data
                .get("uri")
                .or_else(|| tool_data.get("filePath"))
                .and_then(|p| p.as_str())
                .unwrap_or("[unknown]");
            let old_string = tool_data.get("oldString").and_then(|s| s.as_str());
            let new_string = tool_data.get("newString").and_then(|s| s.as_str());

            // Generate unified diff if we have both old and new content
            let diff = if let (Some(old), Some(new)) = (old_string, new_string) {
                Some(generate_unified_diff(old, new, file_path))
            } else {
                None
            };

            conn.execute(
                r#"
                INSERT INTO file_changes 
                (tool_invocation_id, session_id, file_path, change_type, 
                 old_content, new_content, diff_unified, timestamp)
                VALUES (?, ?, ?, 'edit', ?, ?, ?, ?)
                "#,
                params![
                    tool_invocation_id,
                    session_id,
                    file_path,
                    old_string,
                    new_string,
                    diff,
                    timestamp,
                ],
            )?;
        }
        "createFile" => {
            let file_path = tool_data
                .get("uri")
                .or_else(|| tool_data.get("filePath"))
                .and_then(|p| p.as_str())
                .unwrap_or("[unknown]");
            let content = tool_data.get("content").and_then(|c| c.as_str());

            conn.execute(
                r#"
                INSERT INTO file_changes 
                (tool_invocation_id, session_id, file_path, change_type, 
                 new_content, timestamp)
                VALUES (?, ?, ?, 'create', ?, ?)
                "#,
                params![
                    tool_invocation_id,
                    session_id,
                    file_path,
                    content,
                    timestamp,
                ],
            )?;
        }
        "readFile" => {
            let file_path = tool_data
                .get("uri")
                .or_else(|| tool_data.get("filePath"))
                .and_then(|p| p.as_str())
                .unwrap_or("[unknown]");

            conn.execute(
                r#"
                INSERT INTO file_changes 
                (tool_invocation_id, session_id, file_path, change_type, timestamp)
                VALUES (?, ?, ?, 'read', ?)
                "#,
                params![tool_invocation_id, session_id, file_path, timestamp,],
            )?;
        }
        _ => {
            // Other tool types - store as generic change
            if !kind.is_empty() {
                let data_json = serde_json::to_string(tool_data).ok();
                conn.execute(
                    r#"
                    INSERT INTO file_changes 
                    (tool_invocation_id, session_id, file_path, change_type, 
                     diff_unified, timestamp)
                    VALUES (?, ?, ?, ?, ?, ?)
                    "#,
                    params![
                        tool_invocation_id,
                        session_id,
                        format!("[{}]", kind),
                        kind,
                        data_json,
                        timestamp,
                    ],
                )?;
            }
        }
    }

    Ok(())
}

/// Generate a simple unified diff between two strings
fn generate_unified_diff(old: &str, new: &str, file_path: &str) -> String {
    let old_lines: Vec<&str> = old.lines().collect();
    let new_lines: Vec<&str> = new.lines().collect();

    let mut diff = format!("--- a/{}\n+++ b/{}\n", file_path, file_path);

    // Simple line-by-line diff (not a full Myers diff, but good enough for storage)
    let max_lines = old_lines.len().max(new_lines.len());
    let mut in_hunk = false;
    let mut hunk_start = 0;
    let mut hunk_lines = Vec::new();

    for i in 0..max_lines {
        let old_line = old_lines.get(i).copied();
        let new_line = new_lines.get(i).copied();

        match (old_line, new_line) {
            (Some(o), Some(n)) if o == n => {
                if in_hunk {
                    hunk_lines.push(format!(" {}", o));
                }
            }
            (Some(o), Some(n)) => {
                if !in_hunk {
                    in_hunk = true;
                    hunk_start = i + 1;
                }
                hunk_lines.push(format!("-{}", o));
                hunk_lines.push(format!("+{}", n));
            }
            (Some(o), None) => {
                if !in_hunk {
                    in_hunk = true;
                    hunk_start = i + 1;
                }
                hunk_lines.push(format!("-{}", o));
            }
            (None, Some(n)) => {
                if !in_hunk {
                    in_hunk = true;
                    hunk_start = i + 1;
                }
                hunk_lines.push(format!("+{}", n));
            }
            (None, None) => break,
        }
    }

    if !hunk_lines.is_empty() {
        diff.push_str(&format!(
            "@@ -{},{} +{},{} @@\n",
            hunk_start,
            old_lines.len(),
            hunk_start,
            new_lines.len()
        ));
        for line in hunk_lines {
            diff.push_str(&line);
            diff.push('\n');
        }
    }

    diff
}

/// Harvest sessions from web-based cloud providers (ChatGPT, Claude, etc.)
fn harvest_web_providers(
    conn: &Connection,
    stats: &mut HarvestStats,
    include_providers: &[String],
    exclude_providers: &[String],
) -> Result<()> {
    use crate::browser::extract_provider_cookies;

    println!("\n{} Harvesting from web providers...", "[*]".blue());

    // Define web providers to harvest from
    let web_provider_configs: Vec<(&str, &str, &str)> = vec![
        ("ChatGPT", "chatgpt", "__Secure-next-auth.session-token"),
        ("Claude", "claude", "sessionKey"),
    ];

    let mut web_sessions_harvested = 0;

    for (display_name, provider_key, _cookie_name) in &web_provider_configs {
        // Check provider filters
        if !include_providers.is_empty()
            && !include_providers
                .iter()
                .any(|p| p.eq_ignore_ascii_case(provider_key))
        {
            continue;
        }
        if exclude_providers
            .iter()
            .any(|p| p.eq_ignore_ascii_case(provider_key))
        {
            continue;
        }

        print!("   {} Checking {} ... ", "[-]".yellow(), display_name);

        // Try to extract cookies for this provider
        if let Some(creds) = extract_provider_cookies(provider_key) {
            if let Some(session_token) = &creds.session_token {
                println!("{}", "authenticated".green());

                // Create provider and fetch conversations
                let result = match *provider_key {
                    "chatgpt" => harvest_chatgpt_sessions(conn, session_token, stats),
                    "claude" => harvest_claude_sessions(conn, session_token, stats),
                    _ => Ok(0),
                };

                match result {
                    Ok(count) => {
                        if count > 0 {
                            println!(
                                "      {} Harvested {} sessions from {}",
                                "[+]".green(),
                                count.to_string().cyan(),
                                display_name
                            );
                            web_sessions_harvested += count;
                        }
                    }
                    Err(e) => {
                        println!(
                            "      {} Failed to harvest {}: {:?}",
                            "[!]".red(),
                            display_name,
                            e
                        );
                    }
                }
            } else {
                println!("{}", "no session token".yellow());
            }
        } else {
            println!("{}", "not authenticated".yellow());
        }
    }

    if web_sessions_harvested > 0 {
        println!(
            "   {} Total web sessions harvested: {}",
            "[+]".green(),
            web_sessions_harvested.to_string().cyan()
        );
    }

    Ok(())
}

/// Harvest sessions from ChatGPT web interface
fn harvest_chatgpt_sessions(
    conn: &Connection,
    session_token: &str,
    stats: &mut HarvestStats,
) -> Result<usize> {
    use crate::providers::cloud::chatgpt::ChatGPTProvider;
    use crate::providers::cloud::common::{CloudProvider, FetchOptions};

    let provider = ChatGPTProvider::with_session_token(session_token.to_string());

    // List all conversations
    let options = FetchOptions {
        limit: Some(100),
        include_archived: false,
        after: None,
        before: None,
        session_token: Some(session_token.to_string()),
    };

    let conversations = provider
        .list_conversations(&options)
        .context("Failed to list ChatGPT conversations")?;

    let mut harvested = 0;

    for conv_summary in conversations {
        // Check if we already have this conversation
        let exists: bool = conn
            .query_row(
                "SELECT EXISTS(SELECT 1 FROM sessions WHERE id = ? AND provider = 'chatgpt')",
                params![&conv_summary.id],
                |row| row.get(0),
            )
            .unwrap_or(false);

        if exists {
            // Could add update logic here later
            continue;
        }

        // Fetch full conversation
        match provider.fetch_conversation(&conv_summary.id) {
            Ok(conv) => {
                // Insert into database using existing function
                if let Err(e) =
                    insert_cloud_conversation_to_harvest_db(conn, &conv, "chatgpt", None)
                {
                    eprintln!("Failed to insert ChatGPT session: {}", e);
                    continue;
                }
                harvested += 1;
                stats.sessions_added += 1;
            }
            Err(e) => {
                eprintln!("Failed to fetch conversation {}: {}", conv_summary.id, e);
            }
        }

        // Small delay to avoid rate limiting
        std::thread::sleep(std::time::Duration::from_millis(100));
    }

    Ok(harvested)
}

/// Harvest sessions from Claude web interface
fn harvest_claude_sessions(
    conn: &Connection,
    session_token: &str,
    stats: &mut HarvestStats,
) -> Result<usize> {
    use crate::providers::cloud::anthropic::AnthropicProvider;
    use crate::providers::cloud::common::{CloudProvider, FetchOptions};

    let provider = AnthropicProvider::with_session_token(session_token.to_string());

    // List all conversations
    let options = FetchOptions {
        limit: Some(100),
        include_archived: false,
        after: None,
        before: None,
        session_token: Some(session_token.to_string()),
    };

    let conversations = provider
        .list_conversations(&options)
        .context("Failed to list Claude conversations")?;

    let mut harvested = 0;

    for conv_summary in conversations {
        // Check if we already have this conversation
        let exists: bool = conn
            .query_row(
                "SELECT EXISTS(SELECT 1 FROM sessions WHERE id = ? AND provider = 'claude')",
                params![&conv_summary.id],
                |row| row.get(0),
            )
            .unwrap_or(false);

        if exists {
            continue;
        }

        // Fetch full conversation
        match provider.fetch_conversation(&conv_summary.id) {
            Ok(conv) => {
                if let Err(e) = insert_cloud_conversation_to_harvest_db(conn, &conv, "claude", None)
                {
                    eprintln!("Failed to insert Claude session: {}", e);
                    continue;
                }
                harvested += 1;
                stats.sessions_added += 1;
            }
            Err(e) => {
                eprintln!("Failed to fetch conversation {}: {}", conv_summary.id, e);
            }
        }

        std::thread::sleep(std::time::Duration::from_millis(100));
    }

    Ok(harvested)
}

/// Insert a CloudConversation into the harvest database
fn insert_cloud_conversation_to_harvest_db(
    conn: &Connection,
    conv: &crate::providers::cloud::common::CloudConversation,
    provider: &str,
    workspace_name: Option<&str>,
) -> Result<()> {
    let now = Utc::now().timestamp_millis();
    let created_at = conv.created_at.timestamp_millis();
    let updated_at = conv
        .updated_at
        .map(|dt| dt.timestamp_millis())
        .unwrap_or(created_at);

    // Build a session-like JSON structure for compatibility
    let session_json = serde_json::json!({
        "id": conv.id,
        "title": conv.title,
        "model": conv.model,
        "created_at": conv.created_at.to_rfc3339(),
        "updated_at": conv.updated_at.map(|dt| dt.to_rfc3339()),
        "messages": conv.messages.iter().map(|m| {
            serde_json::json!({
                "id": m.id,
                "role": m.role,
                "content": m.content,
                "timestamp": m.timestamp.map(|dt| dt.to_rfc3339()),
                "model": m.model,
            })
        }).collect::<Vec<_>>(),
    });

    conn.execute(
        r#"
        INSERT OR REPLACE INTO sessions 
        (id, provider, provider_type, workspace_id, workspace_name, title, 
         message_count, created_at, updated_at, harvested_at, session_json)
        VALUES (?, ?, ?, NULL, ?, ?, ?, ?, ?, ?, ?)
        "#,
        params![
            conv.id,
            provider,
            provider,
            workspace_name,
            conv.title.clone().unwrap_or_else(|| "Untitled".to_string()),
            conv.messages.len() as i64,
            created_at,
            updated_at,
            now,
            session_json.to_string(),
        ],
    )?;

    // Also populate messages_v2 table for detailed message storage
    populate_cloud_messages(conn, &conv.id, conv)?;

    Ok(())
}

/// Populate messages_v2 table from a CloudConversation
fn populate_cloud_messages(
    conn: &Connection,
    session_id: &str,
    conv: &crate::providers::cloud::common::CloudConversation,
) -> Result<()> {
    // Delete existing messages for this session to avoid duplicates
    conn.execute("DELETE FROM messages_v2 WHERE session_id = ?", [session_id])?;

    for (idx, message) in conv.messages.iter().enumerate() {
        let timestamp = message.timestamp.map(|dt| dt.timestamp_millis());
        let role = match message.role.as_str() {
            "user" | "human" => "user",
            "assistant" => "assistant",
            "system" => "system",
            other => other,
        };

        conn.execute(
            r#"
            INSERT INTO messages_v2 
            (session_id, message_index, request_id, response_id, role, 
             content_raw, content_markdown, model_id, timestamp, is_canceled, metadata_json)
            VALUES (?, ?, ?, NULL, ?, ?, ?, ?, ?, 0, NULL)
            "#,
            params![
                session_id,
                idx as i64,
                message.id,
                role,
                &message.content,
                &message.content,
                message.model.as_deref(),
                timestamp,
            ],
        )?;
    }

    Ok(())
}

fn update_harvest_metadata(conn: &Connection) -> Result<()> {
    conn.execute(
        "INSERT OR REPLACE INTO harvest_metadata (key, value) VALUES ('last_harvest', datetime('now'))",
        [],
    )?;
    Ok(())
}

fn init_git_tracking(db_path: &Path) -> Result<()> {
    let db_dir = db_path.parent().unwrap_or(Path::new("."));
    let db_name = db_path.file_name().unwrap().to_str().unwrap();

    println!("\n{} Initializing Git Tracking", "[G]".green().bold());

    // Check if already a git repo
    if !db_dir.join(".git").exists() {
        let output = Command::new("git")
            .current_dir(db_dir)
            .args(["init"])
            .output()
            .context("Failed to run git init")?;

        if !output.status.success() {
            anyhow::bail!(
                "Git init failed: {}",
                String::from_utf8_lossy(&output.stderr)
            );
        }
        println!("{} Initialized git repository", "[+]".green());
    } else {
        println!("{} Git repository already exists", "[i]".blue());
    }

    // Create .gitignore if needed
    let gitignore_path = db_dir.join(".gitignore");
    if !gitignore_path.exists() {
        fs::write(
            &gitignore_path,
            "*.db-journal\n*.db-wal\n*.db-shm\n*.backup\n",
        )?;
        println!("{} Created .gitignore", "[+]".green());
    }

    // Add database to git
    let output = Command::new("git")
        .current_dir(db_dir)
        .args(["add", db_name])
        .output()?;

    if output.status.success() {
        println!("{} Added {} to git", "[+]".green(), db_name);
    }

    // Initial commit if no commits yet
    let output = Command::new("git")
        .current_dir(db_dir)
        .args(["rev-parse", "HEAD"])
        .output()?;

    if !output.status.success() {
        let output = Command::new("git")
            .current_dir(db_dir)
            .args(["commit", "-m", "Initialize harvest database"])
            .output()?;

        if output.status.success() {
            println!("{} Created initial commit", "[+]".green());
        }
    }

    println!("\n{} Git tracking enabled!", "[+]".green().bold());
    println!("   Run 'csm harvest git commit -m \"message\"' to save changes");
    println!("   Run 'csm harvest git log' to view history");

    Ok(())
}

fn git_commit_harvest(db_path: &Path, message: &str) -> Result<()> {
    let db_dir = db_path.parent().unwrap_or(Path::new("."));
    let db_name = db_path.file_name().unwrap().to_str().unwrap();

    // Stage the database
    let output = Command::new("git")
        .current_dir(db_dir)
        .args(["add", db_name])
        .output()
        .context("Failed to stage database")?;

    if !output.status.success() {
        anyhow::bail!(
            "Git add failed: {}",
            String::from_utf8_lossy(&output.stderr)
        );
    }

    // Commit
    let output = Command::new("git")
        .current_dir(db_dir)
        .args(["commit", "-m", message])
        .output()
        .context("Failed to commit")?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        if stderr.contains("nothing to commit") {
            println!("{} Nothing to commit", "[i]".blue());
            return Ok(());
        }
        anyhow::bail!("Git commit failed: {}", stderr);
    }

    // Get commit hash
    let output = Command::new("git")
        .current_dir(db_dir)
        .args(["rev-parse", "--short", "HEAD"])
        .output()?;

    let hash = String::from_utf8_lossy(&output.stdout).trim().to_string();
    println!("{} Committed: {} - {}", "[+]".green(), hash.cyan(), message);

    Ok(())
}

// ============================================================================
// Share Link Commands
// ============================================================================

/// Import a chat session from a share link URL
pub fn harvest_share(
    db_path: Option<&str>,
    url: &str,
    name: Option<&str>,
    _workspace: Option<&str>,
) -> Result<()> {
    let db_path = get_db_path(db_path)?;

    // Parse the share link
    let share_info = match ShareLinkParser::parse(url) {
        Some(info) => info,
        None => {
            println!("{} Unrecognized share link format", "[!]".yellow());
            println!("   Supported providers: ChatGPT, Claude, Gemini, Perplexity");
            println!("   Example URLs:");
            println!("   - https://chat.openai.com/share/abc123...");
            println!("   - https://claude.ai/share/xyz789...");
            anyhow::bail!("Could not parse share link URL");
        }
    };

    println!("{}", "=".repeat(60).cyan());
    println!("{}", " Share Link Import ".bold().cyan());
    println!("{}", "=".repeat(60).cyan());
    println!();

    println!(
        "{} Detected provider: {}",
        "[i]".blue(),
        share_info.provider.bold()
    );
    println!("{} Share ID: {}", "[i]".blue(), share_info.share_id);

    // Open or create the database with new schema
    let db = ChatDatabase::open(&db_path)?;

    // Check if already imported
    let conn = db.connection();
    let existing: Option<(String, i64)> = conn
        .query_row(
            "SELECT id, imported FROM share_links WHERE url = ?",
            [url],
            |row| Ok((row.get::<_, String>(0)?, row.get::<_, i64>(1)?)),
        )
        .ok();

    if let Some((id, imported)) = existing {
        println!();
        println!(
            "{} This share link has already been registered (ID: {})",
            "[!]".yellow(),
            id
        );

        let status = if imported == 1 { "imported" } else { "pending" };
        println!("{} Current status: {}", "[i]".blue(), status);

        if imported == 1 {
            println!(
                "{} Session already imported - no action needed",
                "[+]".green()
            );
            return Ok(());
        }
    } else {
        // Insert the share link as pending
        let link_id = uuid::Uuid::new_v4().to_string();
        let now = chrono::Utc::now().timestamp();
        conn.execute(
            "INSERT INTO share_links (id, url, provider, share_id, title, imported, created_at) VALUES (?, ?, ?, ?, ?, 0, ?)",
            params![link_id, url, share_info.provider, share_info.share_id, name, now],
        )?;

        println!(
            "{} Registered share link (ID: {})",
            "[+]".green(),
            &link_id[..8]
        );
    }

    println!();
    println!("{}", "-".repeat(60).dimmed());
    println!();

    // TODO: Implement actual content fetching
    // For now, we just register the share link and mark it as pending
    // Actual fetching would require:
    // 1. Browser cookie extraction (already implemented in browser.rs)
    // 2. HTTP request with auth cookies
    // 3. HTML/JSON parsing of the share page
    // 4. Conversion to our universal format

    println!("{} Share link registered as pending", "[i]".blue());
    println!();
    println!("{}", "Note:".bold().yellow());
    println!("   Automatic content fetching from share links is not yet implemented.");
    println!("   For now, you can:");
    println!("   1. Open the share link in your browser");
    println!("   2. Export the conversation manually");
    println!("   3. Import with: csm import <file>");
    println!();
    println!("   Or use 'csm harvest shares' to view pending links.");

    Ok(())
}

/// List share links in the harvest database
pub fn harvest_shares(
    db_path: Option<&str>,
    status_filter: Option<&str>,
    limit: usize,
) -> Result<()> {
    let db_path = get_db_path(db_path)?;

    if !db_path.exists() {
        anyhow::bail!("Harvest database not found. Run 'csm harvest init' first.");
    }

    let db = ChatDatabase::open(&db_path)?;
    let conn = db.connection();

    println!("{}", "=".repeat(70).cyan());
    println!("{}", " Share Links ".bold().cyan());
    println!("{}", "=".repeat(70).cyan());
    println!();

    let query = match status_filter {
        Some("pending") => format!(
            "SELECT id, url, provider, share_id, title, imported, created_at 
             FROM share_links WHERE imported = 0 ORDER BY created_at DESC LIMIT {}",
            limit
        ),
        Some("imported") => format!(
            "SELECT id, url, provider, share_id, title, imported, created_at 
             FROM share_links WHERE imported = 1 ORDER BY created_at DESC LIMIT {}",
            limit
        ),
        Some(_) | None => format!(
            "SELECT id, url, provider, share_id, title, imported, created_at 
             FROM share_links ORDER BY created_at DESC LIMIT {}",
            limit
        ),
    };

    let mut stmt = conn.prepare(&query)?;

    let rows: Vec<_> = stmt
        .query_map([], |row| {
            Ok((
                row.get::<_, String>(0)?,
                row.get::<_, String>(1)?,
                row.get::<_, String>(2)?,
                row.get::<_, Option<String>>(3)?,
                row.get::<_, Option<String>>(4)?,
                row.get::<_, i64>(5)?,
                row.get::<_, i64>(6)?,
            ))
        })?
        .collect::<Result<Vec<_>, _>>()?;

    if rows.is_empty() {
        if let Some(status) = status_filter {
            println!("{} No share links with status '{}'", "[i]".blue(), status);
        } else {
            println!("{} No share links found", "[i]".blue());
        }
        println!("   Use 'csm harvest share <url>' to add a share link");
        return Ok(());
    }

    // Count by status
    let pending_count: i64 = conn
        .query_row(
            "SELECT COUNT(*) FROM share_links WHERE imported = 0",
            [],
            |row| row.get(0),
        )
        .unwrap_or(0);

    let imported_count: i64 = conn
        .query_row(
            "SELECT COUNT(*) FROM share_links WHERE imported = 1",
            [],
            |row| row.get(0),
        )
        .unwrap_or(0);

    println!(
        "{} {} pending, {} imported",
        "[i]".blue(),
        pending_count.to_string().yellow(),
        imported_count.to_string().green()
    );
    println!();

    for (id, url, provider, _share_id, title, imported, created_at) in rows {
        let status = if imported == 1 { "imported" } else { "pending" };
        let status_colored = if imported == 1 {
            status.green()
        } else {
            status.yellow()
        };

        println!(
            "{} [{}] {} - {}",
            format!("#{}", &id[..8]).dimmed(),
            status_colored,
            provider.bold(),
            title.as_deref().unwrap_or("(untitled)")
        );

        // Truncate URL for display
        let display_url = if url.len() > 60 {
            format!("{}...", &url[..57])
        } else {
            url.clone()
        };
        println!("   {} {}", "URL:".dimmed(), display_url.dimmed());

        // Format timestamp
        let timestamp = chrono::DateTime::from_timestamp(created_at, 0)
            .map(|dt| dt.format("%Y-%m-%d %H:%M").to_string())
            .unwrap_or_else(|| created_at.to_string());
        println!("   {} {}", "Added:".dimmed(), timestamp.dimmed());
        println!();
    }

    Ok(())
}

// ============================================================================
// Checkpoint Commands
// ============================================================================

/// Create a checkpoint (version snapshot) of a session
pub fn harvest_checkpoint(
    db_path: Option<&str>,
    session_id: &str,
    message: Option<&str>,
) -> Result<()> {
    let db_path = get_db_path(db_path)?;

    if !db_path.exists() {
        anyhow::bail!("Harvest database not found. Run 'csm harvest init' first.");
    }

    let db = ChatDatabase::open(&db_path)?;
    let conn = db.connection();

    // Find the session
    let session: Option<(i64, String, i64)> = conn
        .query_row(
            "SELECT id, session_id, message_count FROM sessions WHERE session_id = ? OR id = ?",
            params![session_id, session_id.parse::<i64>().unwrap_or(-1)],
            |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),
        )
        .ok();

    let (internal_id, actual_session_id, msg_count) = match session {
        Some(s) => s,
        None => {
            println!("{} Session not found: {}", "[!]".red(), session_id);
            println!("   Use 'csm harvest list' to see available sessions");
            anyhow::bail!("Session not found");
        }
    };

    // Get current checkpoint number
    let checkpoint_num: i64 = conn.query_row(
        "SELECT COALESCE(MAX(checkpoint_number), 0) + 1 FROM checkpoints WHERE session_id = ?",
        [internal_id],
        |row| row.get(0),
    )?;

    // Calculate content hash (simple hash of message count + session_id for now)
    let content_hash = format!(
        "{:x}",
        md5_hash(&format!("{}:{}", actual_session_id, msg_count))
    );

    // Get message snapshot
    let messages: Vec<String> = {
        let mut stmt = conn
            .prepare("SELECT content FROM messages WHERE session_id = ? ORDER BY message_index")?;
        let rows = stmt.query_map([internal_id], |row| row.get::<_, String>(0))?;
        rows.filter_map(|r| r.ok()).collect()
    };

    let snapshot = serde_json::json!({
        "message_count": msg_count,
        "messages": messages,
    });

    let default_message = format!("Checkpoint {}", checkpoint_num);
    let message_text = message.unwrap_or(&default_message);

    // Create checkpoint
    conn.execute(
        "INSERT INTO checkpoints (session_id, checkpoint_number, message, message_count, content_hash, snapshot)
         VALUES (?, ?, ?, ?, ?, ?)",
        params![
            internal_id,
            checkpoint_num,
            message_text,
            msg_count,
            content_hash,
            snapshot.to_string()
        ],
    )?;

    println!("{}", "=".repeat(60).cyan());
    println!("{}", " Checkpoint Created ".bold().cyan());
    println!("{}", "=".repeat(60).cyan());
    println!();
    println!("{} Session: {}", "[+]".green(), actual_session_id);
    println!(
        "{} Checkpoint #{}: {}",
        "[+]".green(),
        checkpoint_num,
        message_text
    );
    println!("{} Messages: {}", "[i]".blue(), msg_count);
    println!("{} Hash: {}", "[i]".blue(), &content_hash[..16]);
    println!();
    println!(
        "   Use 'csm harvest checkpoints {}' to view history",
        session_id
    );

    Ok(())
}

/// List checkpoints for a session
pub fn harvest_checkpoints(db_path: Option<&str>, session_id: &str) -> Result<()> {
    let db_path = get_db_path(db_path)?;

    if !db_path.exists() {
        anyhow::bail!("Harvest database not found. Run 'csm harvest init' first.");
    }

    let db = ChatDatabase::open(&db_path)?;
    let conn = db.connection();

    // Find the session
    let session: Option<(i64, String, String)> = conn
        .query_row(
            "SELECT id, session_id, name FROM sessions WHERE session_id = ? OR id = ?",
            params![session_id, session_id.parse::<i64>().unwrap_or(-1)],
            |row| {
                Ok((
                    row.get(0)?,
                    row.get(1)?,
                    row.get::<_, Option<String>>(2)?.unwrap_or_default(),
                ))
            },
        )
        .ok();

    let (internal_id, actual_session_id, name) = match session {
        Some(s) => s,
        None => {
            println!("{} Session not found: {}", "[!]".red(), session_id);
            anyhow::bail!("Session not found");
        }
    };

    println!("{}", "=".repeat(70).cyan());
    println!("{}", " Session Checkpoints ".bold().cyan());
    println!("{}", "=".repeat(70).cyan());
    println!();
    println!(
        "{} Session: {} {}",
        "[i]".blue(),
        actual_session_id,
        if !name.is_empty() {
            format!("({})", name)
        } else {
            String::new()
        }
    );
    println!();

    let mut stmt = conn.prepare(
        "SELECT checkpoint_number, message, message_count, content_hash, created_at
         FROM checkpoints WHERE session_id = ? ORDER BY checkpoint_number DESC",
    )?;

    let checkpoints: Vec<_> = stmt
        .query_map([internal_id], |row| {
            Ok((
                row.get::<_, i64>(0)?,
                row.get::<_, String>(1)?,
                row.get::<_, i64>(2)?,
                row.get::<_, String>(3)?,
                row.get::<_, String>(4)?,
            ))
        })?
        .collect::<Result<Vec<_>, _>>()?;

    if checkpoints.is_empty() {
        println!("{} No checkpoints found for this session", "[i]".blue());
        println!(
            "   Use 'csm harvest checkpoint {} -m \"message\"' to create one",
            session_id
        );
        return Ok(());
    }

    println!("{} {} checkpoints found:", "[i]".blue(), checkpoints.len());
    println!();

    for (num, msg, msg_count, hash, created_at) in checkpoints {
        println!("  {} #{} - {}", "*".cyan(), num.to_string().bold(), msg);
        println!(
            "       {} messages | {} | {}",
            msg_count,
            &hash[..12],
            created_at.dimmed()
        );
    }

    println!();
    println!(
        "   Use 'csm harvest restore {} <checkpoint>' to restore",
        session_id
    );

    Ok(())
}

/// Restore a session to a previous checkpoint
pub fn harvest_restore_checkpoint(
    db_path: Option<&str>,
    session_id: &str,
    checkpoint_number: i64,
) -> Result<()> {
    let db_path = get_db_path(db_path)?;

    if !db_path.exists() {
        anyhow::bail!("Harvest database not found. Run 'csm harvest init' first.");
    }

    let db = ChatDatabase::open(&db_path)?;
    let conn = db.connection();

    // Find the session
    let session: Option<(i64, String)> = conn
        .query_row(
            "SELECT id, session_id FROM sessions WHERE session_id = ? OR id = ?",
            params![session_id, session_id.parse::<i64>().unwrap_or(-1)],
            |row| Ok((row.get(0)?, row.get(1)?)),
        )
        .ok();

    let (internal_id, actual_session_id) = match session {
        Some(s) => s,
        None => {
            println!("{} Session not found: {}", "[!]".red(), session_id);
            anyhow::bail!("Session not found");
        }
    };

    // Find the checkpoint
    let checkpoint: Option<(String, i64)> = conn
        .query_row(
            "SELECT snapshot, message_count FROM checkpoints 
         WHERE session_id = ? AND checkpoint_number = ?",
            params![internal_id, checkpoint_number],
            |row| Ok((row.get::<_, String>(0)?, row.get::<_, i64>(1)?)),
        )
        .ok();

    let (snapshot_json, original_msg_count) = match checkpoint {
        Some(c) => c,
        None => {
            println!(
                "{} Checkpoint #{} not found for session {}",
                "[!]".red(),
                checkpoint_number,
                session_id
            );
            println!(
                "   Use 'csm harvest checkpoints {}' to see available checkpoints",
                session_id
            );
            anyhow::bail!("Checkpoint not found");
        }
    };

    // Parse snapshot
    let snapshot: serde_json::Value =
        serde_json::from_str(&snapshot_json).context("Failed to parse checkpoint snapshot")?;

    let messages = snapshot["messages"]
        .as_array()
        .context("Invalid snapshot format")?;

    println!("{}", "=".repeat(60).cyan());
    println!("{}", " Restore Checkpoint ".bold().yellow());
    println!("{}", "=".repeat(60).cyan());
    println!();
    println!("{} Session: {}", "[i]".blue(), actual_session_id);
    println!(
        "{} Restoring to checkpoint #{}",
        "[!]".yellow(),
        checkpoint_number
    );
    println!(
        "{} Messages to restore: {}",
        "[i]".blue(),
        original_msg_count
    );
    println!();

    // Delete current messages
    let deleted = conn.execute("DELETE FROM messages WHERE session_id = ?", [internal_id])?;

    println!("{} Removed {} current messages", "[-]".red(), deleted);

    // Restore messages from snapshot
    for (idx, msg) in messages.iter().enumerate() {
        if let Some(content) = msg.as_str() {
            conn.execute(
                "INSERT INTO messages (session_id, message_index, role, content) VALUES (?, ?, 'unknown', ?)",
                params![internal_id, idx as i64, content],
            )?;
        }
    }

    // Update session message count
    conn.execute(
        "UPDATE sessions SET message_count = ?, updated_at = datetime('now') WHERE id = ?",
        params![original_msg_count, internal_id],
    )?;

    println!(
        "{} Restored {} messages from checkpoint",
        "[+]".green(),
        messages.len()
    );
    println!();
    println!(
        "{} Session restored to checkpoint #{}",
        "[+]".green().bold(),
        checkpoint_number
    );

    Ok(())
}

// ============================================================================
// Compact Command
// ============================================================================

/// Compact the harvest database by stripping session_json request blobs.
///
/// Sessions that have been expanded into messages_v2 have their data duplicated:
/// once in the raw session_json TEXT blob and again in the normalized messages_v2,
/// tool_invocations, and file_changes tables. This command replaces session_json
/// with a minimal metadata stub (keeping session_id, title, dates, etc.) and then
/// runs VACUUM to reclaim disk space.
pub fn harvest_compact(db_path: Option<&str>, dry_run: bool) -> Result<()> {
    let db_path = get_db_path(db_path)?;

    if !db_path.exists() {
        anyhow::bail!("Harvest database not found. Run 'csm harvest init' first.");
    }

    println!("\n{} Harvest Database Compact", "[H]".magenta().bold());
    println!("{}", "=".repeat(60));

    let file_size_before = std::fs::metadata(&db_path)?.len();
    println!(
        "{} Database: {} ({:.2} MB)",
        "[*]".blue(),
        db_path.display(),
        file_size_before as f64 / 1_048_576.0
    );

    let conn = Connection::open(&db_path)?;

    // Count sessions that have been expanded into messages_v2
    let expanded_count: i64 = conn.query_row(
        "SELECT COUNT(DISTINCT s.id) FROM sessions s
         INNER JOIN messages_v2 m ON m.session_id = s.id",
        [],
        |row| row.get(0),
    )?;

    let total_sessions: i64 =
        conn.query_row("SELECT COUNT(*) FROM sessions", [], |row| row.get(0))?;

    // Measure current session_json size
    let json_size: i64 = conn
        .query_row(
            "SELECT COALESCE(SUM(LENGTH(session_json)), 0) FROM sessions",
            [],
            |row| row.get(0),
        )
        .unwrap_or(0);

    // Measure expanded session_json size (those with messages_v2 data)
    let expanded_json_size: i64 = conn
        .query_row(
            "SELECT COALESCE(SUM(LENGTH(s.session_json)), 0) FROM sessions s
             WHERE s.id IN (SELECT DISTINCT session_id FROM messages_v2)",
            [],
            |row| row.get(0),
        )
        .unwrap_or(0);

    println!(
        "{} Total sessions: {}",
        "[*]".blue(),
        total_sessions.to_string().truecolor(252, 152, 103)
    );
    println!(
        "{} Sessions with messages_v2 data: {}",
        "[*]".blue(),
        expanded_count.to_string().truecolor(252, 152, 103)
    );
    println!(
        "{} Current session_json size: {:.2} MB",
        "[*]".blue(),
        json_size as f64 / 1_048_576.0
    );
    println!(
        "{} Compactable session_json size: {:.2} MB",
        "[*]".blue(),
        expanded_json_size as f64 / 1_048_576.0
    );

    if expanded_count == 0 {
        println!(
            "\n{} Nothing to compact — no sessions have messages_v2 data.",
            "[i]".dimmed()
        );
        return Ok(());
    }

    if dry_run {
        println!(
            "\n{} Dry run — would compact {} sessions, freeing ~{:.2} MB of JSON blobs.",
            "[i]".yellow(),
            expanded_count,
            expanded_json_size as f64 / 1_048_576.0
        );
        return Ok(());
    }

    // Strip requests from session_json, keeping only metadata
    println!("\n{} Compacting session_json blobs...", "[*]".blue());

    let compacted = conn.execute(
        r#"UPDATE sessions SET session_json = json_object(
            'session_id', json_extract(session_json, '$.session_id'),
            'version', json_extract(session_json, '$.version'),
            'creation_date', json_extract(session_json, '$.creation_date'),
            'last_message_date', json_extract(session_json, '$.last_message_date'),
            'custom_title', json_extract(session_json, '$.custom_title'),
            'initial_location', json_extract(session_json, '$.initial_location'),
            'is_imported', json_extract(session_json, '$.is_imported'),
            'requester_username', json_extract(session_json, '$.requester_username'),
            'responder_username', json_extract(session_json, '$.responder_username'),
            'request_count', message_count,
            '_compacted', 1
        ) WHERE id IN (SELECT DISTINCT session_id FROM messages_v2)"#,
        [],
    )?;

    println!(
        "   {} Compacted {} session JSON blobs",
        "[+]".green(),
        compacted
    );

    // VACUUM to reclaim space
    println!("{} Running VACUUM to reclaim disk space...", "[*]".blue());
    conn.execute_batch("VACUUM")?;

    let file_size_after = std::fs::metadata(&db_path)?.len();
    let saved = if file_size_before > file_size_after {
        file_size_before - file_size_after
    } else {
        0
    };

    println!();
    println!("{} Compact complete!", "[+]".green().bold());
    println!("   Before: {:.2} MB", file_size_before as f64 / 1_048_576.0);
    println!("   After:  {:.2} MB", file_size_after as f64 / 1_048_576.0);
    println!("   Saved:  {:.2} MB", saved as f64 / 1_048_576.0);

    Ok(())
}

// ============================================================================
// Search Commands
// ============================================================================

/// Rebuild the FTS index from messages_v2 table
pub fn harvest_rebuild_fts(db_path: Option<&str>) -> Result<()> {
    let db_path = get_db_path(db_path)?;

    if !db_path.exists() {
        anyhow::bail!("Harvest database not found. Run 'csm harvest init' first.");
    }

    let conn = Connection::open(&db_path)?;

    println!("{}", "=".repeat(70).cyan());
    println!("{} Rebuilding Full-Text Search Index", "[*]".bold());
    println!("{}", "=".repeat(70).cyan());
    println!();

    // Drop existing FTS table and triggers
    println!("{} Dropping old FTS index...", "[*]".blue());
    conn.execute_batch(
        r#"
        DROP TRIGGER IF EXISTS messages_v2_ai;
        DROP TRIGGER IF EXISTS messages_v2_ad;
        DROP TRIGGER IF EXISTS messages_v2_au;
        DROP TABLE IF EXISTS messages_fts;
        "#,
    )?;

    // Create new FTS table with content_raw and session_id for filtering
    println!("{} Creating new FTS index...", "[*]".blue());
    conn.execute_batch(
        r#"
        CREATE VIRTUAL TABLE IF NOT EXISTS messages_fts USING fts5(
            content_raw,
            content='messages_v2',
            content_rowid='id'
        );
        
        CREATE TRIGGER IF NOT EXISTS messages_v2_ai AFTER INSERT ON messages_v2 BEGIN
            INSERT INTO messages_fts(rowid, content_raw) VALUES (new.id, new.content_raw);
        END;
        
        CREATE TRIGGER IF NOT EXISTS messages_v2_ad AFTER DELETE ON messages_v2 BEGIN
            INSERT INTO messages_fts(messages_fts, rowid, content_raw) VALUES ('delete', old.id, old.content_raw);
        END;
        
        CREATE TRIGGER IF NOT EXISTS messages_v2_au AFTER UPDATE ON messages_v2 BEGIN
            INSERT INTO messages_fts(messages_fts, rowid, content_raw) VALUES ('delete', old.id, old.content_raw);
            INSERT INTO messages_fts(rowid, content_raw) VALUES (new.id, new.content_raw);
        END;
        "#,
    )?;

    // Count total messages
    let total_messages: i64 =
        conn.query_row("SELECT COUNT(*) FROM messages_v2", [], |row| row.get(0))?;

    // Populate FTS from existing messages
    println!("{} Indexing {} messages...", "[*]".blue(), total_messages);

    conn.execute(
        "INSERT INTO messages_fts(rowid, content_raw) SELECT id, content_raw FROM messages_v2",
        [],
    )?;

    // Verify the index
    let indexed: i64 = conn.query_row("SELECT COUNT(*) FROM messages_fts", [], |row| row.get(0))?;

    println!();
    println!("{} FTS index rebuilt successfully!", "[+]".green().bold());
    println!("   {} messages indexed", indexed);

    Ok(())
}

/// Full-text search across all sessions
pub fn harvest_search(
    db_path: Option<&str>,
    query: &str,
    provider_filter: Option<&str>,
    limit: usize,
) -> Result<()> {
    let db_path = get_db_path(db_path)?;

    if !db_path.exists() {
        anyhow::bail!("Harvest database not found. Run 'csm harvest init' first.");
    }

    let db = ChatDatabase::open(&db_path)?;
    let conn = db.connection();

    println!("{}", "=".repeat(70).cyan());
    println!("{} Search: {}", "[?]".bold(), query.bold());
    println!("{}", "=".repeat(70).cyan());
    println!();

    // Results: (session_id, provider, title, snippet)
    let results: Vec<(String, String, String, String)> = {
        // Check if FTS table exists
        let fts_exists: bool = conn
            .query_row(
                "SELECT 1 FROM sqlite_master WHERE type='table' AND name='messages_fts'",
                [],
                |_| Ok(true),
            )
            .unwrap_or(false);

        if fts_exists {
            // Use FTS5 search with built-in snippet() for fast highlighting
            // and rank for relevance ordering, deduplicated per session
            let sql = format!(
                "SELECT s.id, s.provider, s.title,
                        snippet(messages_fts, 0, '>>>', '<<<', '...', 32) as snip
                 FROM messages_fts fts
                 JOIN messages_v2 m ON m.id = fts.rowid
                 JOIN sessions s ON m.session_id = s.id
                 WHERE messages_fts MATCH ?
                 {}
                 GROUP BY s.id
                 ORDER BY rank
                 LIMIT {}",
                if provider_filter.is_some() {
                    "AND s.provider = ?"
                } else {
                    ""
                },
                limit
            );

            let mut stmt = conn.prepare(&sql)?;

            if let Some(provider) = provider_filter {
                stmt.query_map(params![query, provider], |row| {
                    Ok((
                        row.get::<_, String>(0)?,
                        row.get::<_, String>(1)?,
                        row.get::<_, Option<String>>(2)?.unwrap_or_default(),
                        row.get::<_, String>(3)?,
                    ))
                })?
                .collect::<Result<Vec<_>, _>>()?
            } else {
                stmt.query_map([query], |row| {
                    Ok((
                        row.get::<_, String>(0)?,
                        row.get::<_, String>(1)?,
                        row.get::<_, Option<String>>(2)?.unwrap_or_default(),
                        row.get::<_, String>(3)?,
                    ))
                })?
                .collect::<Result<Vec<_>, _>>()?
            }
        } else {
            // Fall back to LIKE search with session deduplication
            let search_pattern = format!("%{}%", query);
            let sql = format!(
                "SELECT s.id, s.provider, s.title,
                        SUBSTR(m.content_raw,
                            MAX(1, INSTR(LOWER(m.content_raw), LOWER(?)) - 50),
                            150) as snip
                 FROM messages_v2 m
                 JOIN sessions s ON m.session_id = s.id
                 WHERE m.content_raw LIKE ?
                 {}
                 GROUP BY s.id
                 ORDER BY s.updated_at DESC
                 LIMIT {}",
                if provider_filter.is_some() {
                    "AND s.provider = ?"
                } else {
                    ""
                },
                limit
            );

            let mut stmt = conn.prepare(&sql)?;

            if let Some(provider) = provider_filter {
                stmt.query_map(params![query, search_pattern, provider], |row| {
                    Ok((
                        row.get::<_, String>(0)?,
                        row.get::<_, String>(1)?,
                        row.get::<_, Option<String>>(2)?.unwrap_or_default(),
                        row.get::<_, String>(3)?,
                    ))
                })?
                .collect::<Result<Vec<_>, _>>()?
            } else {
                stmt.query_map(params![query, search_pattern], |row| {
                    Ok((
                        row.get::<_, String>(0)?,
                        row.get::<_, String>(1)?,
                        row.get::<_, Option<String>>(2)?.unwrap_or_default(),
                        row.get::<_, String>(3)?,
                    ))
                })?
                .collect::<Result<Vec<_>, _>>()?
            }
        }
    };

    if results.is_empty() {
        println!("{} No results found for '{}'", "[i]".blue(), query);
        return Ok(());
    }

    println!("{} Found {} result(s):", "[i]".blue(), results.len());
    println!();

    for (session_id, provider, title, snippet) in results {
        let display_name = if title.is_empty() {
            session_id.clone()
        } else {
            format!("{} ({})", title, &session_id[..8.min(session_id.len())])
        };

        println!(
            "{} {} [{}]",
            "*".cyan(),
            display_name.bold(),
            provider.dimmed()
        );

        // Display the snippet (already extracted by SQL or FTS5 snippet())
        let clean_snippet = snippet.replace('\n', " ").replace('\r', "");
        println!("   {}", clean_snippet.dimmed());
        println!();
    }

    Ok(())
}

/// Create a search result snippet with the query highlighted
fn create_search_snippet(content: &str, query: &str, max_len: usize) -> String {
    let content_lower = content.to_lowercase();
    let query_lower = query.to_lowercase();

    if let Some(pos) = content_lower.find(&query_lower) {
        let start = pos.saturating_sub(max_len / 2);
        let end = (pos + query.len() + max_len / 2).min(content.len());

        let mut snippet = String::new();
        if start > 0 {
            snippet.push_str("...");
        }
        snippet.push_str(&content[start..end]);
        if end < content.len() {
            snippet.push_str("...");
        }

        // Replace newlines with spaces for display
        snippet.replace('\n', " ").replace('\r', "")
    } else {
        // Fallback: just show first max_len chars
        if content.len() > max_len {
            format!("{}...", &content[..max_len])
        } else {
            content.to_string()
        }
    }
}

/// Simple MD5 hash for content checksums
fn md5_hash(data: &str) -> u128 {
    // Simple hash implementation (not cryptographically secure, just for checksums)
    let mut hash: u128 = 0;
    for (i, byte) in data.bytes().enumerate() {
        hash = hash.wrapping_add((byte as u128).wrapping_mul((i as u128).wrapping_add(1)));
        hash = hash.rotate_left(7);
    }
    hash
}

/// Sync sessions between the harvest database and provider workspaces
///
/// This command provides bidirectional sync capabilities:
/// - `--push`: Write sessions from the database to provider workspace directories
/// - `--pull`: Import sessions from provider workspaces into the database (similar to harvest run)
///
/// Sync supports filtering by provider, workspace, or specific session IDs.
pub fn harvest_sync(
    path: Option<&str>,
    push: bool,
    pull: bool,
    provider: Option<&str>,
    workspace: Option<&str>,
    sessions: Option<&[String]>,
    format: Option<&str>,
    force: bool,
    dry_run: bool,
) -> Result<()> {
    // Validate arguments
    if !push && !pull {
        anyhow::bail!("Must specify either --push or --pull (or both)");
    }

    // Determine database path
    let db_path = get_db_path(path)?;

    if !db_path.exists() {
        anyhow::bail!(
            "Harvest database not found at {:?}. Run 'harvest run' first.",
            db_path
        );
    }

    println!(
        "{} Sync Operation",
        if dry_run {
            "[DRY RUN]".yellow()
        } else {
            "[SYNC]".green()
        }
    );
    println!("   Database: {}", db_path.display().to_string().cyan());

    if push {
        println!("\n{} Push: Database → Provider Workspaces", "[→]".blue());
        sync_push(
            &db_path, provider, workspace, sessions, format, force, dry_run,
        )?;
    }

    if pull {
        println!("\n{} Pull: Provider Workspaces → Database", "[←]".blue());
        sync_pull(&db_path, provider, workspace, sessions, force, dry_run)?;
    }

    if dry_run {
        println!(
            "\n{} Dry run complete. No changes were made.",
            "[!]".yellow()
        );
    } else {
        println!("\n{} Sync complete.", "[✓]".green());
    }

    Ok(())
}

/// Push sessions from the database to provider workspace directories
fn sync_push(
    db_path: &Path,
    provider: Option<&str>,
    workspace: Option<&str>,
    sessions: Option<&[String]>,
    format: Option<&str>,
    force: bool,
    dry_run: bool,
) -> Result<()> {
    let conn = Connection::open(db_path)?;

    // Build query with filters
    let mut sql = String::from(
        r#"SELECT id, provider, workspace_path, workspace_name, session_json, file_format 
           FROM sessions WHERE workspace_path IS NOT NULL"#,
    );
    let mut params_vec: Vec<String> = Vec::new();

    if let Some(p) = provider {
        sql.push_str(" AND provider = ?");
        params_vec.push(p.to_string());
    }

    if let Some(w) = workspace {
        sql.push_str(" AND (workspace_path LIKE ? OR workspace_name LIKE ?)");
        params_vec.push(format!("%{}%", w));
        params_vec.push(format!("%{}%", w));
    }

    if let Some(sess_ids) = sessions {
        if !sess_ids.is_empty() {
            let placeholders: Vec<&str> = sess_ids.iter().map(|_| "?").collect();
            sql.push_str(&format!(" AND id IN ({})", placeholders.join(",")));
            for id in sess_ids {
                params_vec.push(id.clone());
            }
        }
    }

    let mut stmt = conn.prepare(&sql)?;

    // Build params array for rusqlite
    let params_refs: Vec<&dyn rusqlite::ToSql> = params_vec
        .iter()
        .map(|s| s as &dyn rusqlite::ToSql)
        .collect();

    let rows = stmt.query_map(params_refs.as_slice(), |row| {
        Ok((
            row.get::<_, String>(0)?,         // id
            row.get::<_, String>(1)?,         // provider
            row.get::<_, String>(2)?,         // workspace_path
            row.get::<_, Option<String>>(3)?, // workspace_name
            row.get::<_, String>(4)?,         // session_json
            row.get::<_, Option<String>>(5)?, // file_format
        ))
    })?;

    let target_format = format.unwrap_or("jsonl");
    let mut pushed = 0;
    let mut skipped = 0;
    let mut errors = 0;

    for row_result in rows {
        match row_result {
            Ok((
                session_id,
                provider_name,
                workspace_path,
                workspace_name,
                session_json,
                stored_format,
            )) => {
                // Determine target directory
                let ws_path = PathBuf::from(&workspace_path);
                let chat_dir = ws_path.join(".vscode").join("chat");

                // Skip if directory doesn't exist and we're not creating it
                if !chat_dir.exists() {
                    if !force {
                        println!(
                            "   {} Skipped {} - workspace chat dir not found: {}",
                            "[~]".yellow(),
                            session_id.dimmed(),
                            chat_dir.display()
                        );
                        skipped += 1;
                        continue;
                    }
                    // Create directory if force is set
                    if !dry_run {
                        fs::create_dir_all(&chat_dir)?;
                    }
                }

                // Determine output format and filename
                let (output_ext, needs_conversion) = match target_format {
                    "jsonl" => ("jsonl", stored_format.as_deref() != Some("jsonl")),
                    "json" => ("json", stored_format.as_deref() == Some("jsonl")),
                    _ => ("jsonl", true), // Default to JSONL for modern VS Code
                };

                let session_file = chat_dir.join(format!("{}.{}", session_id, output_ext));

                // Check if file exists
                if session_file.exists() && !force {
                    println!(
                        "   {} Skipped {} - file exists (use --force to overwrite)",
                        "[~]".yellow(),
                        session_id.dimmed()
                    );
                    skipped += 1;
                    continue;
                }

                // Parse and potentially convert the session
                let output_content = if needs_conversion && target_format == "jsonl" {
                    // Convert JSON to JSONL format
                    match serde_json::from_str::<ChatSession>(&session_json) {
                        Ok(session) => convert_session_to_jsonl(&session)?,
                        Err(e) => {
                            println!(
                                "   {} Error parsing session {}: {}",
                                "[!]".red(),
                                session_id,
                                e
                            );
                            errors += 1;
                            continue;
                        }
                    }
                } else {
                    // Use as-is or simple format
                    session_json.clone()
                };

                if dry_run {
                    println!(
                        "   {} Would write {} ({}) → {}",
                        "[+]".green(),
                        workspace_name.as_deref().unwrap_or(&provider_name),
                        session_id.dimmed(),
                        session_file.display()
                    );
                } else {
                    fs::write(&session_file, &output_content)?;
                    println!(
                        "   {} Pushed {} ({}) → {}",
                        "[+]".green(),
                        workspace_name.as_deref().unwrap_or(&provider_name),
                        session_id.dimmed(),
                        session_file.display()
                    );
                }
                pushed += 1;
            }
            Err(e) => {
                println!("   {} Database error: {}", "[!]".red(), e);
                errors += 1;
            }
        }
    }

    println!(
        "\n   {} Push summary: {} pushed, {} skipped, {} errors",
        "[=]".cyan(),
        pushed.to_string().green(),
        skipped.to_string().yellow(),
        errors.to_string().red()
    );

    Ok(())
}

/// Pull sessions from provider workspaces into the database
fn sync_pull(
    db_path: &Path,
    provider: Option<&str>,
    workspace: Option<&str>,
    sessions: Option<&[String]>,
    force: bool,
    dry_run: bool,
) -> Result<()> {
    let conn = if dry_run {
        // For dry run, still open the DB to check existing sessions
        Connection::open(db_path)?
    } else {
        Connection::open(db_path)?
    };

    // Discover workspaces
    let workspaces = discover_workspaces()?;
    let mut pulled = 0;
    let mut skipped = 0;
    let mut errors = 0;

    for ws in workspaces {
        // Filter by workspace if specified
        if let Some(ws_filter) = workspace {
            let ws_path_str = ws.workspace_path.to_string_lossy();
            let ws_name = ws.project_path.as_deref().unwrap_or("");
            if !ws_path_str.contains(ws_filter) && !ws_name.contains(ws_filter) {
                continue;
            }
        }

        // Filter by provider if specified (for Copilot workspaces, it's "GitHub Copilot")
        if let Some(p) = provider {
            if !p.eq_ignore_ascii_case("copilot")
                && !p.eq_ignore_ascii_case("github copilot")
                && !p.eq_ignore_ascii_case("vscode")
            {
                continue;
            }
        }

        // Get sessions from this workspace
        match get_chat_sessions_from_workspace(&ws.workspace_path) {
            Ok(ws_sessions) => {
                for swp in ws_sessions {
                    // Filter by session ID if specified
                    if let Some(sess_ids) = sessions {
                        let sid = swp.session.session_id.as_deref().unwrap_or("");
                        if !sess_ids.iter().any(|id| id == sid) {
                            continue;
                        }
                    }

                    let session_id = swp
                        .session
                        .session_id
                        .clone()
                        .unwrap_or_else(|| uuid::Uuid::new_v4().to_string());

                    // Check if session already exists
                    let exists: bool = conn
                        .query_row("SELECT 1 FROM sessions WHERE id = ?", [&session_id], |_| {
                            Ok(true)
                        })
                        .unwrap_or(false);

                    if exists && !force {
                        skipped += 1;
                        continue;
                    }

                    let ws_name = ws.project_path.clone();
                    let ws_path = ws.workspace_path.to_string_lossy().to_string();

                    if dry_run {
                        println!(
                            "   {} Would pull {} from {}",
                            "[+]".green(),
                            session_id.dimmed(),
                            ws_name.as_deref().unwrap_or(&ws_path)
                        );
                        pulled += 1;
                    } else {
                        match insert_or_update_session(
                            &conn,
                            &swp.session,
                            "GitHub Copilot",
                            Some(&ws.hash),
                            ws_name.as_deref(),
                            None,           // provider_version
                            3,              // schema_version (V3)
                            "json",         // file_format (detect from swp.path extension)
                            Some(&ws_path), // workspace_path
                        ) {
                            Ok(_) => {
                                println!(
                                    "   {} Pulled {} from {}",
                                    "[+]".green(),
                                    session_id.dimmed(),
                                    ws_name.as_deref().unwrap_or(&ws_path)
                                );
                                pulled += 1;
                            }
                            Err(e) => {
                                println!("   {} Error pulling {}: {}", "[!]".red(), session_id, e);
                                errors += 1;
                            }
                        }
                    }
                }
            }
            Err(e) => {
                println!(
                    "   {} Error reading workspace {}: {}",
                    "[!]".red(),
                    ws.workspace_path.display(),
                    e
                );
                errors += 1;
            }
        }
    }

    println!(
        "\n   {} Pull summary: {} pulled, {} skipped, {} errors",
        "[=]".cyan(),
        pulled.to_string().green(),
        skipped.to_string().yellow(),
        errors.to_string().red()
    );

    Ok(())
}

/// Convert a ChatSession to JSONL format (VS Code 1.109+)
fn convert_session_to_jsonl(session: &ChatSession) -> Result<String> {
    use serde_json::json;

    let mut lines = Vec::new();

    // First line: session metadata
    let session_meta = json!({
        "version": 3,
        "sessionId": session.session_id,
        "title": session.title(),
        "createdAt": session.creation_date,
        "lastInteractionAt": session.last_message_date,
        "customTitle": session.custom_title.as_deref(),
    });
    lines.push(serde_json::to_string(&session_meta)?);

    // Subsequent lines: each request as a separate JSON object
    for request in &session.requests {
        let request_json = serde_json::to_string(request)?;
        lines.push(request_json);
    }

    Ok(lines.join("\n"))
}