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
// Copyright (c) 2024-2026 Nervosys LLC
// SPDX-License-Identifier: AGPL-3.0-only
//! Workspace listing commands

use anyhow::Result;
use tabled::{settings::Style as TableStyle, Table, Tabled};

use crate::models::Workspace;
use crate::storage::{read_empty_window_sessions, VsCodeSessionFormat};
use crate::workspace::discover_workspaces;

#[derive(Tabled)]
struct WorkspaceRow {
    #[tabled(rename = "Hash")]
    hash: String,
    #[tabled(rename = "Project Path")]
    project_path: String,
    #[tabled(rename = "Sessions")]
    sessions: usize,
    #[tabled(rename = "Has Chats")]
    has_chats: String,
}

#[derive(Tabled)]
struct SessionRow {
    #[tabled(rename = "Project Path")]
    project_path: String,
    #[tabled(rename = "Session File")]
    session_file: String,
    #[tabled(rename = "Last Modified")]
    last_modified: String,
    #[tabled(rename = "Messages")]
    messages: usize,
}

#[derive(Tabled)]
struct SessionRowWithSize {
    #[tabled(rename = "Project Path")]
    project_path: String,
    #[tabled(rename = "Session File")]
    session_file: String,
    #[tabled(rename = "Last Modified")]
    last_modified: String,
    #[tabled(rename = "Messages")]
    messages: usize,
    #[tabled(rename = "Size")]
    size: String,
}

/// List all VS Code workspaces
pub fn list_workspaces() -> Result<()> {
    let workspaces = discover_workspaces()?;

    if workspaces.is_empty() {
        println!("No workspaces found.");
        return Ok(());
    }

    let rows: Vec<WorkspaceRow> = workspaces
        .iter()
        .map(|ws| WorkspaceRow {
            hash: format!("{}...", &ws.hash[..12.min(ws.hash.len())]),
            project_path: ws
                .project_path
                .clone()
                .unwrap_or_else(|| "(none)".to_string()),
            sessions: ws.chat_session_count,
            has_chats: if ws.has_chat_sessions {
                "Yes".to_string()
            } else {
                "No".to_string()
            },
        })
        .collect();

    let table = Table::new(rows)
        .with(TableStyle::ascii_rounded())
        .to_string();

    println!("{}", table);
    println!("\nTotal workspaces: {}", workspaces.len());

    // Show empty window sessions count (ALL SESSIONS)
    if let Ok(empty_count) = crate::storage::count_empty_window_sessions() {
        if empty_count > 0 {
            println!("Empty window sessions (ALL SESSIONS): {}", empty_count);
        }
    }

    Ok(())
}

/// Format file size in human-readable format
fn format_file_size(bytes: u64) -> String {
    if bytes < 1024 {
        format!("{} B", bytes)
    } else if bytes < 1024 * 1024 {
        format!("{:.1} KB", bytes as f64 / 1024.0)
    } else if bytes < 1024 * 1024 * 1024 {
        format!("{:.1} MB", bytes as f64 / (1024.0 * 1024.0))
    } else {
        format!("{:.2} GB", bytes as f64 / (1024.0 * 1024.0 * 1024.0))
    }
}

/// List all chat sessions
pub fn list_sessions(
    project_path: Option<&str>,
    show_size: bool,
    provider: Option<&str>,
    all_providers: bool,
) -> Result<()> {
    // If provider filtering is requested, use the multi-provider approach
    if provider.is_some() || all_providers {
        return list_sessions_multi_provider(project_path, show_size, provider, all_providers);
    }

    // Default behavior: VS Code only (backward compatible)
    let workspaces = discover_workspaces()?;

    let filtered_workspaces: Vec<&Workspace> = if let Some(path) = project_path {
        let normalized = crate::workspace::normalize_path(path);
        workspaces
            .iter()
            .filter(|ws| {
                ws.project_path
                    .as_ref()
                    .map(|p| crate::workspace::normalize_path(p) == normalized)
                    .unwrap_or(false)
            })
            .collect()
    } else {
        workspaces.iter().collect()
    };

    if show_size {
        let mut rows: Vec<SessionRowWithSize> = Vec::new();
        let mut total_size: u64 = 0;

        // Add empty window sessions (ALL SESSIONS) if no specific project filter
        if project_path.is_none() {
            if let Ok(empty_sessions) = read_empty_window_sessions() {
                for session in empty_sessions {
                    let modified =
                        chrono::DateTime::from_timestamp_millis(session.last_message_date)
                            .map(|dt| dt.format("%Y-%m-%d %H:%M").to_string())
                            .unwrap_or_else(|| "unknown".to_string());

                    let session_id = session.session_id.as_deref().unwrap_or("unknown");
                    rows.push(SessionRowWithSize {
                        project_path: "(ALL SESSIONS)".to_string(),
                        session_file: format!("{}.json", session_id),
                        last_modified: modified,
                        messages: session.request_count(),
                        size: "N/A".to_string(),
                    });
                }
            }
        }

        for ws in &filtered_workspaces {
            if !ws.has_chat_sessions {
                continue;
            }

            let sessions = crate::workspace::get_chat_sessions_from_workspace(&ws.workspace_path)?;

            for session_with_path in sessions {
                let metadata = session_with_path.path.metadata().ok();
                let file_size = metadata.as_ref().map(|m| m.len()).unwrap_or(0);
                total_size += file_size;

                let modified = metadata
                    .and_then(|m| m.modified().ok())
                    .map(|t| {
                        let datetime: chrono::DateTime<chrono::Utc> = t.into();
                        datetime.format("%Y-%m-%d %H:%M").to_string()
                    })
                    .unwrap_or_else(|| "unknown".to_string());

                rows.push(SessionRowWithSize {
                    project_path: ws
                        .project_path
                        .clone()
                        .unwrap_or_else(|| "(none)".to_string()),
                    session_file: session_with_path
                        .path
                        .file_name()
                        .map(|n| n.to_string_lossy().to_string())
                        .unwrap_or_else(|| "unknown".to_string()),
                    last_modified: modified,
                    messages: session_with_path.session.request_count(),
                    size: format_file_size(file_size),
                });
            }
        }

        if rows.is_empty() {
            println!("No chat sessions found.");
            return Ok(());
        }

        let table = Table::new(&rows)
            .with(TableStyle::ascii_rounded())
            .to_string();
        println!("{}", table);
        println!(
            "\nTotal sessions: {} ({})",
            rows.len(),
            format_file_size(total_size)
        );
    } else {
        let mut rows: Vec<SessionRow> = Vec::new();

        // Add empty window sessions (ALL SESSIONS) if no specific project filter
        if project_path.is_none() {
            if let Ok(empty_sessions) = read_empty_window_sessions() {
                for session in empty_sessions {
                    let modified =
                        chrono::DateTime::from_timestamp_millis(session.last_message_date)
                            .map(|dt| dt.format("%Y-%m-%d %H:%M").to_string())
                            .unwrap_or_else(|| "unknown".to_string());

                    let session_id = session.session_id.as_deref().unwrap_or("unknown");
                    rows.push(SessionRow {
                        project_path: "(ALL SESSIONS)".to_string(),
                        session_file: format!("{}.json", session_id),
                        last_modified: modified,
                        messages: session.request_count(),
                    });
                }
            }
        }

        for ws in &filtered_workspaces {
            if !ws.has_chat_sessions {
                continue;
            }

            let sessions = crate::workspace::get_chat_sessions_from_workspace(&ws.workspace_path)?;

            for session_with_path in sessions {
                let modified = session_with_path
                    .path
                    .metadata()
                    .ok()
                    .and_then(|m| m.modified().ok())
                    .map(|t| {
                        let datetime: chrono::DateTime<chrono::Utc> = t.into();
                        datetime.format("%Y-%m-%d %H:%M").to_string()
                    })
                    .unwrap_or_else(|| "unknown".to_string());

                rows.push(SessionRow {
                    project_path: ws
                        .project_path
                        .clone()
                        .unwrap_or_else(|| "(none)".to_string()),
                    session_file: session_with_path
                        .path
                        .file_name()
                        .map(|n| n.to_string_lossy().to_string())
                        .unwrap_or_else(|| "unknown".to_string()),
                    last_modified: modified,
                    messages: session_with_path.session.request_count(),
                });
            }
        }

        if rows.is_empty() {
            println!("No chat sessions found.");
            return Ok(());
        }

        let table = Table::new(&rows)
            .with(TableStyle::ascii_rounded())
            .to_string();
        println!("{}", table);
        println!("\nTotal sessions: {}", rows.len());
    }

    Ok(())
}

/// List sessions from multiple providers
fn list_sessions_multi_provider(
    project_path: Option<&str>,
    show_size: bool,
    provider: Option<&str>,
    all_providers: bool,
) -> Result<()> {
    // Determine which storage paths to scan
    let storage_paths = if all_providers {
        get_agent_storage_paths(Some("all"))?
    } else if let Some(p) = provider {
        get_agent_storage_paths(Some(p))?
    } else {
        get_agent_storage_paths(None)?
    };

    if storage_paths.is_empty() {
        if let Some(p) = provider {
            println!("No storage found for provider: {}", p);
        } else {
            println!("No workspaces found");
        }
        return Ok(());
    }

    let target_path = project_path.map(crate::workspace::normalize_path);

    #[derive(Tabled)]
    struct SessionRowMulti {
        #[tabled(rename = "Provider")]
        provider: String,
        #[tabled(rename = "Project Path")]
        project_path: String,
        #[tabled(rename = "Session File")]
        session_file: String,
        #[tabled(rename = "Modified")]
        last_modified: String,
        #[tabled(rename = "Msgs")]
        messages: usize,
    }

    #[derive(Tabled)]
    struct SessionRowMultiWithSize {
        #[tabled(rename = "Provider")]
        provider: String,
        #[tabled(rename = "Project Path")]
        project_path: String,
        #[tabled(rename = "Session File")]
        session_file: String,
        #[tabled(rename = "Modified")]
        last_modified: String,
        #[tabled(rename = "Msgs")]
        messages: usize,
        #[tabled(rename = "Size")]
        size: String,
    }

    let mut rows: Vec<SessionRowMulti> = Vec::new();
    let mut rows_with_size: Vec<SessionRowMultiWithSize> = Vec::new();
    let mut total_size: u64 = 0;

    for (provider_name, storage_path) in &storage_paths {
        if !storage_path.exists() {
            continue;
        }

        for entry in std::fs::read_dir(storage_path)?.filter_map(|e| e.ok()) {
            let workspace_dir = entry.path();
            if !workspace_dir.is_dir() {
                continue;
            }

            let chat_sessions_dir = workspace_dir.join("chatSessions");
            if !chat_sessions_dir.exists() {
                continue;
            }

            // Get project path from workspace.json
            let workspace_json = workspace_dir.join("workspace.json");
            let project = std::fs::read_to_string(&workspace_json)
                .ok()
                .and_then(|c| serde_json::from_str::<crate::models::WorkspaceJson>(&c).ok())
                .and_then(|ws| {
                    ws.folder
                        .map(|f| crate::workspace::decode_workspace_folder(&f))
                });

            // Filter by project path if specified
            if let Some(ref target) = target_path {
                if project
                    .as_ref()
                    .map(|p| crate::workspace::normalize_path(p) != *target)
                    .unwrap_or(true)
                {
                    continue;
                }
            }

            let project_display = project.clone().unwrap_or_else(|| "(none)".to_string());

            // List session files
            for session_entry in std::fs::read_dir(&chat_sessions_dir)?.filter_map(|e| e.ok()) {
                let session_path = session_entry.path();
                if !session_path.is_file() {
                    continue;
                }

                let ext = session_path.extension().and_then(|e| e.to_str());
                if ext != Some("json") && ext != Some("jsonl") {
                    continue;
                }

                let metadata = session_path.metadata().ok();
                let file_size = metadata.as_ref().map(|m| m.len()).unwrap_or(0);
                total_size += file_size;

                let modified = metadata
                    .and_then(|m| m.modified().ok())
                    .map(|t| {
                        let datetime: chrono::DateTime<chrono::Utc> = t.into();
                        datetime.format("%Y-%m-%d %H:%M").to_string()
                    })
                    .unwrap_or_else(|| "unknown".to_string());

                let session_file = session_path
                    .file_name()
                    .map(|n| n.to_string_lossy().to_string())
                    .unwrap_or_else(|| "unknown".to_string());

                // Try to get message count from the session file
                let messages = std::fs::read_to_string(&session_path)
                    .ok()
                    .map(|c| c.matches("\"message\":").count())
                    .unwrap_or(0);

                if show_size {
                    rows_with_size.push(SessionRowMultiWithSize {
                        provider: provider_name.clone(),
                        project_path: truncate_string(&project_display, 30),
                        session_file: truncate_string(&session_file, 20),
                        last_modified: modified,
                        messages,
                        size: format_file_size(file_size),
                    });
                } else {
                    rows.push(SessionRowMulti {
                        provider: provider_name.clone(),
                        project_path: truncate_string(&project_display, 30),
                        session_file: truncate_string(&session_file, 20),
                        last_modified: modified,
                        messages,
                    });
                }
            }
        }
    }

    if show_size {
        if rows_with_size.is_empty() {
            println!("No chat sessions found.");
            return Ok(());
        }
        let table = Table::new(&rows_with_size)
            .with(TableStyle::ascii_rounded())
            .to_string();
        println!("{}", table);
        println!(
            "\nTotal sessions: {} ({})",
            rows_with_size.len(),
            format_file_size(total_size)
        );
    } else {
        if rows.is_empty() {
            println!("No chat sessions found.");
            return Ok(());
        }
        let table = Table::new(&rows)
            .with(TableStyle::ascii_rounded())
            .to_string();
        println!("{}", table);
        println!("\nTotal sessions: {}", rows.len());
    }

    Ok(())
}

/// Find workspaces by search pattern
pub fn find_workspaces(pattern: &str) -> Result<()> {
    let workspaces = discover_workspaces()?;

    // Resolve "." to current directory name
    let pattern = if pattern == "." {
        std::env::current_dir()
            .ok()
            .and_then(|p| p.file_name().map(|n| n.to_string_lossy().to_string()))
            .unwrap_or_else(|| pattern.to_string())
    } else {
        pattern.to_string()
    };
    let pattern_lower = pattern.to_lowercase();

    let matching: Vec<&Workspace> = workspaces
        .iter()
        .filter(|ws| {
            ws.project_path
                .as_ref()
                .map(|p| p.to_lowercase().contains(&pattern_lower))
                .unwrap_or(false)
                || ws.hash.to_lowercase().contains(&pattern_lower)
        })
        .collect();

    if matching.is_empty() {
        println!("No workspaces found matching '{}'", pattern);
        return Ok(());
    }

    let rows: Vec<WorkspaceRow> = matching
        .iter()
        .map(|ws| WorkspaceRow {
            hash: format!("{}...", &ws.hash[..12.min(ws.hash.len())]),
            project_path: ws
                .project_path
                .clone()
                .unwrap_or_else(|| "(none)".to_string()),
            sessions: ws.chat_session_count,
            has_chats: if ws.has_chat_sessions {
                "Yes".to_string()
            } else {
                "No".to_string()
            },
        })
        .collect();

    let table = Table::new(rows)
        .with(TableStyle::ascii_rounded())
        .to_string();

    println!("{}", table);
    println!("\nFound {} matching workspace(s)", matching.len());

    // Show session paths for each matching workspace
    for ws in &matching {
        if ws.has_chat_sessions {
            let project = ws.project_path.as_deref().unwrap_or("(none)");
            println!("\nSessions for {}:", project);

            if let Ok(sessions) =
                crate::workspace::get_chat_sessions_from_workspace(&ws.workspace_path)
            {
                for session_with_path in sessions {
                    println!("  {}", session_with_path.path.display());
                }
            }
        }
    }

    Ok(())
}

/// Find sessions by search pattern
#[allow(dead_code)]
pub fn find_sessions(pattern: &str, project_path: Option<&str>) -> Result<()> {
    let workspaces = discover_workspaces()?;
    let pattern_lower = pattern.to_lowercase();

    let filtered_workspaces: Vec<&Workspace> = if let Some(path) = project_path {
        let normalized = crate::workspace::normalize_path(path);
        workspaces
            .iter()
            .filter(|ws| {
                ws.project_path
                    .as_ref()
                    .map(|p| crate::workspace::normalize_path(p) == normalized)
                    .unwrap_or(false)
            })
            .collect()
    } else {
        workspaces.iter().collect()
    };

    let mut rows: Vec<SessionRow> = Vec::new();

    for ws in filtered_workspaces {
        if !ws.has_chat_sessions {
            continue;
        }

        let sessions = crate::workspace::get_chat_sessions_from_workspace(&ws.workspace_path)?;

        for session_with_path in sessions {
            // Check if session matches the pattern
            let session_id_matches = session_with_path
                .session
                .session_id
                .as_ref()
                .map(|id| id.to_lowercase().contains(&pattern_lower))
                .unwrap_or(false);
            let title_matches = session_with_path
                .session
                .title()
                .to_lowercase()
                .contains(&pattern_lower);
            let content_matches = session_with_path.session.requests.iter().any(|r| {
                r.message
                    .as_ref()
                    .map(|m| {
                        m.text
                            .as_ref()
                            .map(|t| t.to_lowercase().contains(&pattern_lower))
                            .unwrap_or(false)
                    })
                    .unwrap_or(false)
            });

            if !session_id_matches && !title_matches && !content_matches {
                continue;
            }

            let modified = session_with_path
                .path
                .metadata()
                .ok()
                .and_then(|m| m.modified().ok())
                .map(|t| {
                    let datetime: chrono::DateTime<chrono::Utc> = t.into();
                    datetime.format("%Y-%m-%d %H:%M").to_string()
                })
                .unwrap_or_else(|| "unknown".to_string());

            rows.push(SessionRow {
                project_path: ws
                    .project_path
                    .clone()
                    .unwrap_or_else(|| "(none)".to_string()),
                session_file: session_with_path
                    .path
                    .file_name()
                    .map(|n| n.to_string_lossy().to_string())
                    .unwrap_or_else(|| "unknown".to_string()),
                last_modified: modified,
                messages: session_with_path.session.request_count(),
            });
        }
    }

    if rows.is_empty() {
        println!("No sessions found matching '{}'", pattern);
        return Ok(());
    }

    let table = Table::new(&rows)
        .with(TableStyle::ascii_rounded())
        .to_string();

    println!("{}", table);
    println!("\nFound {} matching session(s)", rows.len());

    Ok(())
}

/// Read only the first `max_bytes` of a file as a string.
/// Returns None if the file cannot be read.
fn read_file_header(path: &std::path::Path, max_bytes: usize) -> Option<String> {
    use std::io::Read;
    let file = std::fs::File::open(path).ok()?;
    let mut reader = std::io::BufReader::new(file);
    let mut buffer = vec![0u8; max_bytes];
    let bytes_read = reader.read(&mut buffer).ok()?;
    buffer.truncate(bytes_read);
    String::from_utf8(buffer).ok()
}

/// Case-insensitive substring search without allocating a lowercased copy.
/// Uses byte-level comparison for ASCII patterns (which covers all common search terms).
fn contains_case_insensitive(haystack: &str, needle_lower: &str) -> bool {
    if needle_lower.is_empty() {
        return true;
    }
    let needle_bytes = needle_lower.as_bytes();
    let haystack_bytes = haystack.as_bytes();
    if needle_bytes.len() > haystack_bytes.len() {
        return false;
    }
    // Sliding window byte comparison with ASCII lowering
    'outer: for i in 0..=(haystack_bytes.len() - needle_bytes.len()) {
        for j in 0..needle_bytes.len() {
            if haystack_bytes[i + j].to_ascii_lowercase() != needle_bytes[j] {
                continue 'outer;
            }
        }
        return true;
    }
    false
}

/// Optimized session search with filtering
///
/// This function is optimized for speed by:
/// 1. Filtering workspaces first (by name/path)
/// 2. Filtering by file modification date before reading content
/// 3. Title-only search reads only first 4KB of each file (10-100x faster)
/// 4. Case-insensitive search avoids String::to_lowercase() allocation
/// 5. Content search is opt-in (expensive)
/// 6. Parallel file scanning with rayon
pub fn find_sessions_filtered(
    pattern: &str,
    workspace_filter: Option<&str>,
    title_only: bool,
    search_content: bool,
    after: Option<&str>,
    before: Option<&str>,
    date: Option<&str>,
    all_workspaces: bool,
    provider: Option<&str>,
    all_providers: bool,
    limit: usize,
) -> Result<()> {
    use chrono::{NaiveDate, Utc};
    use rayon::prelude::*;
    use std::sync::atomic::{AtomicUsize, Ordering};

    let pattern_lower = pattern.to_lowercase();

    // Parse date filters upfront
    let after_date = after.and_then(|s| NaiveDate::parse_from_str(s, "%Y-%m-%d").ok());
    let before_date = before.and_then(|s| NaiveDate::parse_from_str(s, "%Y-%m-%d").ok());
    let target_date = date.and_then(|s| NaiveDate::parse_from_str(s, "%Y-%m-%d").ok());

    // Determine which storage paths to scan based on provider filter
    let storage_paths = if all_providers {
        get_agent_storage_paths(Some("all"))?
    } else if let Some(p) = provider {
        get_agent_storage_paths(Some(p))?
    } else {
        // Default to VS Code only
        let vscode_path = crate::workspace::get_workspace_storage_path()?;
        if vscode_path.exists() {
            vec![("vscode".to_string(), vscode_path)]
        } else {
            vec![]
        }
    };

    if storage_paths.is_empty() {
        if let Some(p) = provider {
            println!("No storage found for provider: {}", p);
        } else {
            println!("No workspaces found");
        }
        return Ok(());
    }

    // Collect workspace directories with minimal I/O
    // If --all flag is set, don't filter by workspace
    let ws_filter_lower = if all_workspaces {
        None
    } else {
        workspace_filter.map(|s| s.to_lowercase())
    };

    let workspace_dirs: Vec<_> = storage_paths
        .iter()
        .flat_map(|(provider_name, storage_path)| {
            if !storage_path.exists() {
                return vec![];
            }
            std::fs::read_dir(storage_path)
                .into_iter()
                .flatten()
                .filter_map(|e| e.ok())
                .filter(|e| e.path().is_dir())
                .filter_map(|entry| {
                    let workspace_dir = entry.path();
                    let workspace_json_path = workspace_dir.join("workspace.json");

                    // Quick check: does chatSessions exist?
                    let chat_sessions_dir = workspace_dir.join("chatSessions");
                    if !chat_sessions_dir.exists() {
                        return None;
                    }

                    // Parse workspace.json for project path (needed for filtering)
                    let project_path =
                        std::fs::read_to_string(&workspace_json_path)
                            .ok()
                            .and_then(|content| {
                                serde_json::from_str::<crate::models::WorkspaceJson>(&content)
                                    .ok()
                                    .and_then(|ws| {
                                        ws.folder
                                            .map(|f| crate::workspace::decode_workspace_folder(&f))
                                    })
                            });

                    // Apply workspace filter early
                    if let Some(ref filter) = ws_filter_lower {
                        let hash = entry.file_name().to_string_lossy().to_lowercase();
                        let path_matches = project_path
                            .as_ref()
                            .map(|p| p.to_lowercase().contains(filter))
                            .unwrap_or(false);
                        if !hash.contains(filter) && !path_matches {
                            return None;
                        }
                    }

                    let ws_name = project_path
                        .as_ref()
                        .and_then(|p| std::path::Path::new(p).file_name())
                        .map(|n| n.to_string_lossy().to_string())
                        .unwrap_or_else(|| {
                            entry.file_name().to_string_lossy()[..8.min(entry.file_name().len())]
                                .to_string()
                        });

                    Some((chat_sessions_dir, ws_name, provider_name.clone()))
                })
                .collect::<Vec<_>>()
        })
        .collect();

    if workspace_dirs.is_empty() {
        if let Some(ws) = workspace_filter {
            println!("No workspaces found matching '{}'", ws);
        } else {
            println!("No workspaces with chat sessions found");
        }
        return Ok(());
    }

    // Collect all session file paths
    let session_files: Vec<_> = workspace_dirs
        .iter()
        .flat_map(|(chat_dir, ws_name, provider_name)| {
            std::fs::read_dir(chat_dir)
                .into_iter()
                .flatten()
                .filter_map(|e| e.ok())
                .filter(|e| {
                    e.path()
                        .extension()
                        .map(|ext| ext == "json" || ext == "jsonl")
                        .unwrap_or(false)
                })
                .map(|e| (e.path(), ws_name.clone(), provider_name.clone()))
                .collect::<Vec<_>>()
        })
        .collect();

    let total_files = session_files.len();
    let scanned = AtomicUsize::new(0);
    let skipped_by_date = AtomicUsize::new(0);

    // Process files in parallel
    let mut results: Vec<_> = session_files
        .par_iter()
        .filter_map(|(path, ws_name, provider_name)| {
            // Date filter using file metadata (very fast)
            if after_date.is_some() || before_date.is_some() {
                if let Ok(metadata) = path.metadata() {
                    if let Ok(modified) = metadata.modified() {
                        let file_date: chrono::DateTime<Utc> = modified.into();
                        let file_naive = file_date.date_naive();

                        if let Some(after) = after_date {
                            if file_naive < after {
                                skipped_by_date.fetch_add(1, Ordering::Relaxed);
                                return None;
                            }
                        }
                        if let Some(before) = before_date {
                            if file_naive > before {
                                skipped_by_date.fetch_add(1, Ordering::Relaxed);
                                return None;
                            }
                        }
                    }
                }
            }

            scanned.fetch_add(1, Ordering::Relaxed);

            // Optimization: for title-only search (no --content flag), read only
            // the first 4KB of the file to extract the title. This is 10-100x
            // faster for large session files (which can be megabytes).
            let (title, content_for_search) = if title_only || !search_content {
                // Fast path: only need the title
                let header = match read_file_header(path, 4096) {
                    Some(h) => h,
                    None => return None,
                };
                let title =
                    extract_title_from_content(&header).unwrap_or_else(|| "Untitled".to_string());
                (title, None)
            } else {
                // Full read path: need content for search
                let content = match std::fs::read_to_string(path) {
                    Ok(c) => c,
                    Err(_) => return None,
                };

                // Check for internal message timestamps if --date filter is used
                if let Some(target) = target_date {
                    let has_matching_timestamp =
                        content.split("\"timestamp\":").skip(1).any(|part| {
                            let num_str: String = part
                                .chars()
                                .skip_while(|c| c.is_whitespace())
                                .take_while(|c| c.is_ascii_digit())
                                .collect();
                            if let Ok(ts_ms) = num_str.parse::<i64>() {
                                if let Some(dt) = chrono::DateTime::from_timestamp_millis(ts_ms) {
                                    return dt.date_naive() == target;
                                }
                            }
                            false
                        });

                    if !has_matching_timestamp {
                        skipped_by_date.fetch_add(1, Ordering::Relaxed);
                        return None;
                    }
                }

                let title =
                    extract_title_from_content(&content).unwrap_or_else(|| "Untitled".to_string());
                (title, Some(content))
            };

            let title_lower = title.to_lowercase();

            // Check session ID from filename
            let session_id = path
                .file_stem()
                .map(|n| n.to_string_lossy().to_string())
                .unwrap_or_default();
            let id_matches =
                !pattern_lower.is_empty() && session_id.to_lowercase().contains(&pattern_lower);

            // Check title match
            let title_matches = !pattern_lower.is_empty() && title_lower.contains(&pattern_lower);

            // Content search if requested (uses pre-loaded content_for_search)
            let content_matches = if search_content
                && !title_only
                && !id_matches
                && !title_matches
                && !pattern_lower.is_empty()
            {
                if let Some(ref content) = content_for_search {
                    // Use case-insensitive byte search for speed
                    contains_case_insensitive(content, &pattern_lower)
                } else {
                    // Content wasn't loaded (title-only mode), do a lazy read
                    match std::fs::read_to_string(path) {
                        Ok(c) => contains_case_insensitive(&c, &pattern_lower),
                        Err(_) => false,
                    }
                }
            } else {
                false
            };

            // Empty pattern matches everything (for listing)
            let matches =
                pattern_lower.is_empty() || id_matches || title_matches || content_matches;
            if !matches {
                return None;
            }

            let match_type = if pattern_lower.is_empty() {
                ""
            } else if id_matches {
                "ID"
            } else if title_matches {
                "title"
            } else {
                "content"
            };

            // Count messages from content if available, otherwise estimate from file size
            let message_count = if let Some(ref content) = content_for_search {
                content.matches("\"message\":").count()
            } else {
                // Estimate from file size (avoid reading full file just for count)
                path.metadata()
                    .ok()
                    .map(|m| {
                        // Rough estimate: ~500 bytes per message on average
                        (m.len() / 500).max(1) as usize
                    })
                    .unwrap_or(0)
            };

            // Get modification time
            let modified = path
                .metadata()
                .ok()
                .and_then(|m| m.modified().ok())
                .map(|t| {
                    let datetime: chrono::DateTime<chrono::Utc> = t.into();
                    datetime.format("%Y-%m-%d %H:%M").to_string()
                })
                .unwrap_or_else(|| "unknown".to_string());

            Some((
                title,
                ws_name.clone(),
                provider_name.clone(),
                modified,
                message_count,
                match_type.to_string(),
            ))
        })
        .collect();

    let scanned_count = scanned.load(Ordering::Relaxed);
    let skipped_count = skipped_by_date.load(Ordering::Relaxed);

    if results.is_empty() {
        println!("No sessions found matching '{}'", pattern);
        if skipped_count > 0 {
            println!("  ({} sessions skipped due to date filter)", skipped_count);
        }
        return Ok(());
    }

    // Sort by modification date (newest first)
    results.sort_by(|a, b| b.3.cmp(&a.3));

    // Apply limit
    results.truncate(limit);

    // Check if we have multiple providers to show provider column
    let show_provider_column = all_providers || storage_paths.len() > 1;

    #[derive(Tabled)]
    struct SearchResultRow {
        #[tabled(rename = "Title")]
        title: String,
        #[tabled(rename = "Workspace")]
        workspace: String,
        #[tabled(rename = "Modified")]
        modified: String,
        #[tabled(rename = "Msgs")]
        messages: usize,
        #[tabled(rename = "Match")]
        match_type: String,
    }

    #[derive(Tabled)]
    struct SearchResultRowWithProvider {
        #[tabled(rename = "Provider")]
        provider: String,
        #[tabled(rename = "Title")]
        title: String,
        #[tabled(rename = "Workspace")]
        workspace: String,
        #[tabled(rename = "Modified")]
        modified: String,
        #[tabled(rename = "Msgs")]
        messages: usize,
        #[tabled(rename = "Match")]
        match_type: String,
    }

    if show_provider_column {
        let rows: Vec<SearchResultRowWithProvider> = results
            .into_iter()
            .map(
                |(title, workspace, provider, modified, messages, match_type)| {
                    SearchResultRowWithProvider {
                        provider,
                        title: truncate_string(&title, 35),
                        workspace: truncate_string(&workspace, 15),
                        modified,
                        messages,
                        match_type,
                    }
                },
            )
            .collect();

        let table = Table::new(&rows)
            .with(TableStyle::ascii_rounded())
            .to_string();

        println!("{}", table);
        println!(
            "\nFound {} session(s) (scanned {} of {} files{})",
            rows.len(),
            scanned_count,
            total_files,
            if skipped_count > 0 {
                format!(", {} skipped by date", skipped_count)
            } else {
                String::new()
            }
        );
        if rows.len() >= limit {
            println!("  (results limited to {}; use --limit to show more)", limit);
        }
    } else {
        let rows: Vec<SearchResultRow> = results
            .into_iter()
            .map(
                |(title, workspace, _provider, modified, messages, match_type)| SearchResultRow {
                    title: truncate_string(&title, 40),
                    workspace: truncate_string(&workspace, 20),
                    modified,
                    messages,
                    match_type,
                },
            )
            .collect();

        let table = Table::new(&rows)
            .with(TableStyle::ascii_rounded())
            .to_string();

        println!("{}", table);
        println!(
            "\nFound {} session(s) (scanned {} of {} files{})",
            rows.len(),
            scanned_count,
            total_files,
            if skipped_count > 0 {
                format!(", {} skipped by date", skipped_count)
            } else {
                String::new()
            }
        );
        if rows.len() >= limit {
            println!("  (results limited to {}; use --limit to show more)", limit);
        }
    }

    Ok(())
}

/// Extract title from full JSON content (more reliable than header-only)
fn extract_title_from_content(content: &str) -> Option<String> {
    // Look for "customTitle" first (user-set title)
    if let Some(start) = content.find("\"customTitle\"") {
        if let Some(colon) = content[start..].find(':') {
            let after_colon = &content[start + colon + 1..];
            let trimmed = after_colon.trim_start();
            if let Some(stripped) = trimmed.strip_prefix('"') {
                if let Some(end) = stripped.find('"') {
                    let title = &stripped[..end];
                    if !title.is_empty() && title != "null" {
                        return Some(title.to_string());
                    }
                }
            }
        }
    }

    // Fall back to first request's message text
    if let Some(start) = content.find("\"text\"") {
        if let Some(colon) = content[start..].find(':') {
            let after_colon = &content[start + colon + 1..];
            let trimmed = after_colon.trim_start();
            if let Some(stripped) = trimmed.strip_prefix('"') {
                if let Some(end) = stripped.find('"') {
                    let title = &stripped[..end];
                    if !title.is_empty() && title.len() < 100 {
                        return Some(title.to_string());
                    }
                }
            }
        }
    }

    None
}

/// Fast title extraction from JSON header
#[allow(dead_code)]
fn extract_title_fast(header: &str) -> Option<String> {
    extract_title_from_content(header)
}

/// Truncate string to max length with ellipsis
fn truncate_string(s: &str, max_len: usize) -> String {
    if s.len() <= max_len {
        s.to_string()
    } else {
        format!("{}...", &s[..max_len.saturating_sub(3)])
    }
}

/// Show workspace details
pub fn show_workspace(workspace: &str) -> Result<()> {
    use colored::Colorize;

    let workspaces = discover_workspaces()?;
    let workspace_lower = workspace.to_lowercase();

    // Find workspace by name or hash
    let matching: Vec<&Workspace> = workspaces
        .iter()
        .filter(|ws| {
            ws.hash.to_lowercase().contains(&workspace_lower)
                || ws
                    .project_path
                    .as_ref()
                    .map(|p| p.to_lowercase().contains(&workspace_lower))
                    .unwrap_or(false)
        })
        .collect();

    if matching.is_empty() {
        println!(
            "{} No workspace found matching '{}'",
            "!".yellow(),
            workspace
        );
        return Ok(());
    }

    for ws in matching {
        println!("\n{}", "=".repeat(60).bright_blue());
        println!("{}", "Workspace Details".bright_blue().bold());
        println!("{}", "=".repeat(60).bright_blue());

        println!("{}: {}", "Hash".bright_white().bold(), ws.hash);
        println!(
            "{}: {}",
            "Path".bright_white().bold(),
            ws.project_path.as_ref().unwrap_or(&"(none)".to_string())
        );
        println!(
            "{}: {}",
            "Has Sessions".bright_white().bold(),
            if ws.has_chat_sessions {
                "Yes".green()
            } else {
                "No".red()
            }
        );
        println!(
            "{}: {}",
            "Workspace Path".bright_white().bold(),
            ws.workspace_path.display()
        );

        if ws.has_chat_sessions {
            let sessions = crate::workspace::get_chat_sessions_from_workspace(&ws.workspace_path)?;
            println!(
                "{}: {}",
                "Session Count".bright_white().bold(),
                sessions.len()
            );

            if !sessions.is_empty() {
                println!("\n{}", "Sessions:".bright_yellow());
                for (i, s) in sessions.iter().enumerate() {
                    let title = s.session.title();
                    let msg_count = s.session.request_count();
                    println!(
                        "  {}. {} ({} messages)",
                        i + 1,
                        title.bright_cyan(),
                        msg_count
                    );
                }
            }
        }
    }

    Ok(())
}

/// Show session details
pub fn show_session(session_id: &str, project_path: Option<&str>) -> Result<()> {
    use colored::Colorize;

    let workspaces = discover_workspaces()?;
    let session_id_lower = session_id.to_lowercase();

    let filtered_workspaces: Vec<&Workspace> = if let Some(path) = project_path {
        let normalized = crate::workspace::normalize_path(path);
        workspaces
            .iter()
            .filter(|ws| {
                ws.project_path
                    .as_ref()
                    .map(|p| crate::workspace::normalize_path(p) == normalized)
                    .unwrap_or(false)
            })
            .collect()
    } else {
        workspaces.iter().collect()
    };

    for ws in filtered_workspaces {
        if !ws.has_chat_sessions {
            continue;
        }

        let sessions = crate::workspace::get_chat_sessions_from_workspace(&ws.workspace_path)?;

        for s in sessions {
            let filename = s
                .path
                .file_name()
                .map(|n| n.to_string_lossy().to_string())
                .unwrap_or_default();

            let matches = s
                .session
                .session_id
                .as_ref()
                .map(|id| id.to_lowercase().contains(&session_id_lower))
                .unwrap_or(false)
                || filename.to_lowercase().contains(&session_id_lower);

            if matches {
                // Detect format from file extension
                let format = VsCodeSessionFormat::from_path(&s.path);

                println!("\n{}", "=".repeat(60).bright_blue());
                println!("{}", "Session Details".bright_blue().bold());
                println!("{}", "=".repeat(60).bright_blue());

                println!(
                    "{}: {}",
                    "Title".bright_white().bold(),
                    s.session.title().bright_cyan()
                );
                println!("{}: {}", "File".bright_white().bold(), filename);
                println!(
                    "{}: {}",
                    "Format".bright_white().bold(),
                    format.to_string().bright_magenta()
                );
                println!(
                    "{}: {}",
                    "Session ID".bright_white().bold(),
                    s.session
                        .session_id
                        .as_ref()
                        .unwrap_or(&"(none)".to_string())
                );
                println!(
                    "{}: {}",
                    "Messages".bright_white().bold(),
                    s.session.request_count()
                );
                println!(
                    "{}: {}",
                    "Workspace".bright_white().bold(),
                    ws.project_path.as_ref().unwrap_or(&"(none)".to_string())
                );

                // Show first few messages as preview
                println!("\n{}", "Preview:".bright_yellow());
                for (i, req) in s.session.requests.iter().take(3).enumerate() {
                    if let Some(msg) = &req.message {
                        if let Some(text) = &msg.text {
                            let preview: String = text.chars().take(100).collect();
                            let truncated = if text.len() > 100 { "..." } else { "" };
                            println!("  {}. {}{}", i + 1, preview.dimmed(), truncated);
                        }
                    }
                }

                return Ok(());
            }
        }
    }

    println!(
        "{} No session found matching '{}'",
        "!".yellow(),
        session_id
    );
    Ok(())
}

/// Get storage paths for agent mode sessions based on provider filter
/// Returns (provider_name, storage_path) tuples
fn get_agent_storage_paths(provider: Option<&str>) -> Result<Vec<(String, std::path::PathBuf)>> {
    let mut paths = Vec::new();

    // VS Code path
    let vscode_path = crate::workspace::get_workspace_storage_path()?;

    // Other provider paths
    let cursor_path = get_cursor_storage_path();
    let claudecode_path = get_claudecode_storage_path();
    let opencode_path = get_opencode_storage_path();
    let openclaw_path = get_openclaw_storage_path();
    let antigravity_path = get_antigravity_storage_path();
    let codexcli_path = get_codexcli_storage_path();
    let droidcli_path = get_droidcli_storage_path();
    let geminicli_path = get_geminicli_storage_path();

    match provider {
        None => {
            // Default: return VS Code path only for backward compatibility
            if vscode_path.exists() {
                paths.push(("vscode".to_string(), vscode_path));
            }
        }
        Some("all") => {
            // All providers that support agent mode
            if vscode_path.exists() {
                paths.push(("vscode".to_string(), vscode_path));
            }
            if let Some(cp) = cursor_path {
                if cp.exists() {
                    paths.push(("cursor".to_string(), cp));
                }
            }
            if let Some(cc) = claudecode_path {
                if cc.exists() {
                    paths.push(("claudecode".to_string(), cc));
                }
            }
            if let Some(oc) = opencode_path {
                if oc.exists() {
                    paths.push(("opencode".to_string(), oc));
                }
            }
            if let Some(ocl) = openclaw_path {
                if ocl.exists() {
                    paths.push(("openclaw".to_string(), ocl));
                }
            }
            if let Some(ag) = antigravity_path {
                if ag.exists() {
                    paths.push(("antigravity".to_string(), ag));
                }
            }
            if let Some(cx) = codexcli_path {
                if cx.exists() {
                    paths.push(("codexcli".to_string(), cx));
                }
            }
            if let Some(dr) = droidcli_path {
                if dr.exists() {
                    paths.push(("droidcli".to_string(), dr));
                }
            }
            if let Some(gc) = geminicli_path {
                if gc.exists() {
                    paths.push(("geminicli".to_string(), gc));
                }
            }
        }
        Some(p) => {
            let p_lower = p.to_lowercase();
            match p_lower.as_str() {
                "vscode" | "vs-code" | "copilot" => {
                    if vscode_path.exists() {
                        paths.push(("vscode".to_string(), vscode_path));
                    }
                }
                "cursor" => {
                    if let Some(cp) = cursor_path {
                        if cp.exists() {
                            paths.push(("cursor".to_string(), cp));
                        }
                    }
                }
                "claudecode" | "claude-code" | "claude" => {
                    if let Some(cc) = claudecode_path {
                        if cc.exists() {
                            paths.push(("claudecode".to_string(), cc));
                        }
                    }
                }
                "opencode" | "open-code" => {
                    if let Some(oc) = opencode_path {
                        if oc.exists() {
                            paths.push(("opencode".to_string(), oc));
                        }
                    }
                }
                "openclaw" | "open-claw" | "claw" => {
                    if let Some(ocl) = openclaw_path {
                        if ocl.exists() {
                            paths.push(("openclaw".to_string(), ocl));
                        }
                    }
                }
                "antigravity" | "anti-gravity" | "ag" => {
                    if let Some(ag) = antigravity_path {
                        if ag.exists() {
                            paths.push(("antigravity".to_string(), ag));
                        }
                    }
                }
                "codexcli" | "codex-cli" | "codex" => {
                    if let Some(cx) = codexcli_path {
                        if cx.exists() {
                            paths.push(("codexcli".to_string(), cx));
                        }
                    }
                }
                "droidcli" | "droid-cli" | "droid" | "factory" => {
                    if let Some(dr) = droidcli_path {
                        if dr.exists() {
                            paths.push(("droidcli".to_string(), dr));
                        }
                    }
                }
                "geminicli" | "gemini-cli" => {
                    if let Some(gc) = geminicli_path {
                        if gc.exists() {
                            paths.push(("geminicli".to_string(), gc));
                        }
                    }
                }
                _ => {
                    // Unknown provider - return empty to trigger error message
                }
            }
        }
    }

    Ok(paths)
}

/// Get Cursor's workspace storage path
fn get_cursor_storage_path() -> Option<std::path::PathBuf> {
    #[cfg(target_os = "windows")]
    {
        if let Some(appdata) = dirs::data_dir() {
            let cursor_path = appdata.join("Cursor").join("User").join("workspaceStorage");
            if cursor_path.exists() {
                return Some(cursor_path);
            }
        }
        if let Ok(roaming) = std::env::var("APPDATA") {
            let roaming_path = std::path::PathBuf::from(roaming)
                .join("Cursor")
                .join("User")
                .join("workspaceStorage");
            if roaming_path.exists() {
                return Some(roaming_path);
            }
        }
    }

    #[cfg(target_os = "macos")]
    {
        if let Some(home) = dirs::home_dir() {
            let cursor_path = home
                .join("Library")
                .join("Application Support")
                .join("Cursor")
                .join("User")
                .join("workspaceStorage");
            if cursor_path.exists() {
                return Some(cursor_path);
            }
        }
    }

    #[cfg(target_os = "linux")]
    {
        if let Some(config) = dirs::config_dir() {
            let cursor_path = config.join("Cursor").join("User").join("workspaceStorage");
            if cursor_path.exists() {
                return Some(cursor_path);
            }
        }
    }

    None
}

/// Get ClaudeCode's storage path (Anthropic's Claude Code CLI)
fn get_claudecode_storage_path() -> Option<std::path::PathBuf> {
    #[cfg(target_os = "windows")]
    {
        // ClaudeCode stores sessions in AppData
        if let Ok(appdata) = std::env::var("APPDATA") {
            let claude_path = std::path::PathBuf::from(&appdata)
                .join("claude-code")
                .join("sessions");
            if claude_path.exists() {
                return Some(claude_path);
            }
            // Alternative path with different naming
            let alt_path = std::path::PathBuf::from(&appdata)
                .join("ClaudeCode")
                .join("workspaceStorage");
            if alt_path.exists() {
                return Some(alt_path);
            }
        }
        if let Some(local) = dirs::data_local_dir() {
            let local_path = local.join("ClaudeCode").join("sessions");
            if local_path.exists() {
                return Some(local_path);
            }
        }
    }

    #[cfg(target_os = "macos")]
    {
        if let Some(home) = dirs::home_dir() {
            let claude_path = home
                .join("Library")
                .join("Application Support")
                .join("claude-code")
                .join("sessions");
            if claude_path.exists() {
                return Some(claude_path);
            }
        }
    }

    #[cfg(target_os = "linux")]
    {
        if let Some(config) = dirs::config_dir() {
            let claude_path = config.join("claude-code").join("sessions");
            if claude_path.exists() {
                return Some(claude_path);
            }
        }
    }

    None
}

/// Get OpenCode's storage path (open-source coding assistant)
fn get_opencode_storage_path() -> Option<std::path::PathBuf> {
    #[cfg(target_os = "windows")]
    {
        if let Ok(appdata) = std::env::var("APPDATA") {
            let opencode_path = std::path::PathBuf::from(&appdata)
                .join("OpenCode")
                .join("workspaceStorage");
            if opencode_path.exists() {
                return Some(opencode_path);
            }
        }
        if let Some(local) = dirs::data_local_dir() {
            let local_path = local.join("OpenCode").join("sessions");
            if local_path.exists() {
                return Some(local_path);
            }
        }
    }

    #[cfg(target_os = "macos")]
    {
        if let Some(home) = dirs::home_dir() {
            let opencode_path = home
                .join("Library")
                .join("Application Support")
                .join("OpenCode")
                .join("workspaceStorage");
            if opencode_path.exists() {
                return Some(opencode_path);
            }
        }
    }

    #[cfg(target_os = "linux")]
    {
        if let Some(config) = dirs::config_dir() {
            let opencode_path = config.join("opencode").join("workspaceStorage");
            if opencode_path.exists() {
                return Some(opencode_path);
            }
        }
    }

    None
}

/// Get OpenClaw's storage path
fn get_openclaw_storage_path() -> Option<std::path::PathBuf> {
    #[cfg(target_os = "windows")]
    {
        if let Ok(appdata) = std::env::var("APPDATA") {
            let openclaw_path = std::path::PathBuf::from(&appdata)
                .join("OpenClaw")
                .join("workspaceStorage");
            if openclaw_path.exists() {
                return Some(openclaw_path);
            }
        }
        if let Some(local) = dirs::data_local_dir() {
            let local_path = local.join("OpenClaw").join("sessions");
            if local_path.exists() {
                return Some(local_path);
            }
        }
    }

    #[cfg(target_os = "macos")]
    {
        if let Some(home) = dirs::home_dir() {
            let openclaw_path = home
                .join("Library")
                .join("Application Support")
                .join("OpenClaw")
                .join("workspaceStorage");
            if openclaw_path.exists() {
                return Some(openclaw_path);
            }
        }
    }

    #[cfg(target_os = "linux")]
    {
        if let Some(config) = dirs::config_dir() {
            let openclaw_path = config.join("openclaw").join("workspaceStorage");
            if openclaw_path.exists() {
                return Some(openclaw_path);
            }
        }
    }

    None
}

/// Get Antigravity's storage path
fn get_antigravity_storage_path() -> Option<std::path::PathBuf> {
    #[cfg(target_os = "windows")]
    {
        if let Ok(appdata) = std::env::var("APPDATA") {
            let antigrav_path = std::path::PathBuf::from(&appdata)
                .join("Antigravity")
                .join("workspaceStorage");
            if antigrav_path.exists() {
                return Some(antigrav_path);
            }
        }
        if let Some(local) = dirs::data_local_dir() {
            let local_path = local.join("Antigravity").join("sessions");
            if local_path.exists() {
                return Some(local_path);
            }
        }
    }

    #[cfg(target_os = "macos")]
    {
        if let Some(home) = dirs::home_dir() {
            let antigrav_path = home
                .join("Library")
                .join("Application Support")
                .join("Antigravity")
                .join("workspaceStorage");
            if antigrav_path.exists() {
                return Some(antigrav_path);
            }
        }
    }

    #[cfg(target_os = "linux")]
    {
        if let Some(config) = dirs::config_dir() {
            let antigrav_path = config.join("antigravity").join("workspaceStorage");
            if antigrav_path.exists() {
                return Some(antigrav_path);
            }
        }
    }

    None
}

/// Get Codex CLI's storage path (OpenAI Codex CLI)
/// Stores JSONL session files in ~/.codex/sessions/
fn get_codexcli_storage_path() -> Option<std::path::PathBuf> {
    if let Some(home) = dirs::home_dir() {
        let codex_path = home.join(".codex").join("sessions");
        if codex_path.exists() {
            return Some(codex_path);
        }
    }

    #[cfg(target_os = "windows")]
    {
        if let Ok(appdata) = std::env::var("APPDATA") {
            let codex_path = std::path::PathBuf::from(&appdata)
                .join("codex")
                .join("sessions");
            if codex_path.exists() {
                return Some(codex_path);
            }
        }
        if let Some(local) = dirs::data_local_dir() {
            let local_path = local.join("codex").join("sessions");
            if local_path.exists() {
                return Some(local_path);
            }
        }
    }

    None
}

/// Get Droid CLI's storage path (Factory Droid CLI)
/// Stores JSONL session files in ~/.factory/sessions/
fn get_droidcli_storage_path() -> Option<std::path::PathBuf> {
    if let Some(home) = dirs::home_dir() {
        let droid_path = home.join(".factory").join("sessions");
        if droid_path.exists() {
            return Some(droid_path);
        }
    }

    #[cfg(target_os = "windows")]
    {
        if let Ok(appdata) = std::env::var("APPDATA") {
            let droid_path = std::path::PathBuf::from(&appdata)
                .join("factory")
                .join("sessions");
            if droid_path.exists() {
                return Some(droid_path);
            }
        }
        if let Some(local) = dirs::data_local_dir() {
            let local_path = local.join("factory").join("sessions");
            if local_path.exists() {
                return Some(local_path);
            }
        }
    }

    None
}

/// Get Gemini CLI's storage path (Google Gemini CLI)
/// Stores JSON session files in ~/.gemini/tmp/
fn get_geminicli_storage_path() -> Option<std::path::PathBuf> {
    if let Some(home) = dirs::home_dir() {
        let gemini_path = home.join(".gemini").join("tmp");
        if gemini_path.exists() {
            return Some(gemini_path);
        }
    }

    #[cfg(target_os = "windows")]
    {
        if let Ok(appdata) = std::env::var("APPDATA") {
            let gemini_path = std::path::PathBuf::from(&appdata)
                .join("gemini")
                .join("tmp");
            if gemini_path.exists() {
                return Some(gemini_path);
            }
        }
        if let Some(local) = dirs::data_local_dir() {
            let local_path = local.join("gemini").join("tmp");
            if local_path.exists() {
                return Some(local_path);
            }
        }
    }

    None
}

/// List agent mode sessions (chatEditingSessions / Copilot Edits)
pub fn list_agents_sessions(
    project_path: Option<&str>,
    show_size: bool,
    provider: Option<&str>,
) -> Result<()> {
    // Get storage paths based on provider filter
    let storage_paths = get_agent_storage_paths(provider)?;

    if storage_paths.is_empty() {
        if let Some(p) = provider {
            println!("No storage found for provider: {}", p);
            println!("\nSupported providers: vscode, cursor, claudecode, opencode, openclaw, antigravity, codexcli, droidcli, geminicli");
        } else {
            println!("No workspaces found");
        }
        return Ok(());
    }

    #[derive(Tabled)]
    struct AgentSessionRow {
        #[tabled(rename = "Provider")]
        provider: String,
        #[tabled(rename = "Project")]
        project: String,
        #[tabled(rename = "Session ID")]
        session_id: String,
        #[tabled(rename = "Last Modified")]
        last_modified: String,
        #[tabled(rename = "Files")]
        file_count: usize,
    }

    #[derive(Tabled)]
    struct AgentSessionRowWithSize {
        #[tabled(rename = "Provider")]
        provider: String,
        #[tabled(rename = "Project")]
        project: String,
        #[tabled(rename = "Session ID")]
        session_id: String,
        #[tabled(rename = "Last Modified")]
        last_modified: String,
        #[tabled(rename = "Files")]
        file_count: usize,
        #[tabled(rename = "Size")]
        size: String,
    }

    let target_path = project_path.map(crate::workspace::normalize_path);
    let mut total_size: u64 = 0;
    let mut rows_with_size: Vec<AgentSessionRowWithSize> = Vec::new();
    let mut rows: Vec<AgentSessionRow> = Vec::new();

    for (provider_name, storage_path) in &storage_paths {
        if !storage_path.exists() {
            continue;
        }

        for entry in std::fs::read_dir(storage_path)?.filter_map(|e| e.ok()) {
            let workspace_dir = entry.path();
            if !workspace_dir.is_dir() {
                continue;
            }

            let agent_sessions_dir = workspace_dir.join("chatEditingSessions");
            if !agent_sessions_dir.exists() {
                continue;
            }

            // Get project path from workspace.json
            let workspace_json = workspace_dir.join("workspace.json");
            let project = std::fs::read_to_string(&workspace_json)
                .ok()
                .and_then(|c| serde_json::from_str::<crate::models::WorkspaceJson>(&c).ok())
                .and_then(|ws| {
                    ws.folder
                        .map(|f| crate::workspace::decode_workspace_folder(&f))
                });

            // Filter by project path if specified
            if let Some(ref target) = target_path {
                if project
                    .as_ref()
                    .map(|p| crate::workspace::normalize_path(p) != *target)
                    .unwrap_or(true)
                {
                    continue;
                }
            }

            let project_name = project
                .as_ref()
                .and_then(|p| std::path::Path::new(p).file_name())
                .map(|n| n.to_string_lossy().to_string())
                .unwrap_or_else(|| entry.file_name().to_string_lossy()[..8].to_string());

            // List agent session directories
            for session_entry in std::fs::read_dir(&agent_sessions_dir)?.filter_map(|e| e.ok()) {
                let session_dir = session_entry.path();
                if !session_dir.is_dir() {
                    continue;
                }

                let session_id = session_entry.file_name().to_string_lossy().to_string();
                let short_id = if session_id.len() > 8 {
                    format!("{}...", &session_id[..8])
                } else {
                    session_id.clone()
                };

                // Get last modified time and file count
                let mut last_mod = std::time::SystemTime::UNIX_EPOCH;
                let mut file_count = 0;
                let mut session_size: u64 = 0;

                if let Ok(files) = std::fs::read_dir(&session_dir) {
                    for file in files.filter_map(|f| f.ok()) {
                        file_count += 1;
                        if let Ok(meta) = file.metadata() {
                            session_size += meta.len();
                            if let Ok(mod_time) = meta.modified() {
                                if mod_time > last_mod {
                                    last_mod = mod_time;
                                }
                            }
                        }
                    }
                }

                total_size += session_size;

                let modified = if last_mod != std::time::SystemTime::UNIX_EPOCH {
                    let datetime: chrono::DateTime<chrono::Utc> = last_mod.into();
                    datetime.format("%Y-%m-%d %H:%M").to_string()
                } else {
                    "unknown".to_string()
                };

                if show_size {
                    rows_with_size.push(AgentSessionRowWithSize {
                        provider: provider_name.clone(),
                        project: project_name.clone(),
                        session_id: short_id,
                        last_modified: modified,
                        file_count,
                        size: format_file_size(session_size),
                    });
                } else {
                    rows.push(AgentSessionRow {
                        provider: provider_name.clone(),
                        project: project_name.clone(),
                        session_id: short_id,
                        last_modified: modified,
                        file_count,
                    });
                }
            }
        }
    }

    if show_size {
        if rows_with_size.is_empty() {
            println!("No agent mode sessions found.");
            return Ok(());
        }
        let table = Table::new(&rows_with_size)
            .with(TableStyle::ascii_rounded())
            .to_string();
        println!("{}", table);
        println!(
            "\nTotal agent sessions: {} ({})",
            rows_with_size.len(),
            format_file_size(total_size)
        );
    } else {
        if rows.is_empty() {
            println!("No agent mode sessions found.");
            return Ok(());
        }
        let table = Table::new(&rows)
            .with(TableStyle::ascii_rounded())
            .to_string();
        println!("{}", table);
        println!("\nTotal agent sessions: {}", rows.len());
    }

    Ok(())
}

/// Show agent mode session details
pub fn show_agent_session(session_id: &str, project_path: Option<&str>) -> Result<()> {
    use colored::*;

    let storage_path = crate::workspace::get_workspace_storage_path()?;
    let session_id_lower = session_id.to_lowercase();
    let target_path = project_path.map(crate::workspace::normalize_path);

    for entry in std::fs::read_dir(&storage_path)?.filter_map(|e| e.ok()) {
        let workspace_dir = entry.path();
        if !workspace_dir.is_dir() {
            continue;
        }

        let agent_sessions_dir = workspace_dir.join("chatEditingSessions");
        if !agent_sessions_dir.exists() {
            continue;
        }

        // Get project path
        let workspace_json = workspace_dir.join("workspace.json");
        let project = std::fs::read_to_string(&workspace_json)
            .ok()
            .and_then(|c| serde_json::from_str::<crate::models::WorkspaceJson>(&c).ok())
            .and_then(|ws| {
                ws.folder
                    .map(|f| crate::workspace::decode_workspace_folder(&f))
            });

        // Filter by project path if specified
        if let Some(ref target) = target_path {
            if project
                .as_ref()
                .map(|p| crate::workspace::normalize_path(p) != *target)
                .unwrap_or(true)
            {
                continue;
            }
        }

        for session_entry in std::fs::read_dir(&agent_sessions_dir)?.filter_map(|e| e.ok()) {
            let full_id = session_entry.file_name().to_string_lossy().to_string();
            if !full_id.to_lowercase().contains(&session_id_lower) {
                continue;
            }

            let session_dir = session_entry.path();

            println!("\n{}", "=".repeat(60).bright_blue());
            println!("{}", "Agent Session Details".bright_blue().bold());
            println!("{}", "=".repeat(60).bright_blue());

            println!(
                "{}: {}",
                "Session ID".bright_white().bold(),
                full_id.bright_cyan()
            );
            println!(
                "{}: {}",
                "Project".bright_white().bold(),
                project.as_deref().unwrap_or("(none)")
            );
            println!(
                "{}: {}",
                "Path".bright_white().bold(),
                session_dir.display()
            );

            // List files in the session
            println!("\n{}", "Session Files:".bright_yellow());
            let mut total_size: u64 = 0;
            if let Ok(files) = std::fs::read_dir(&session_dir) {
                for file in files.filter_map(|f| f.ok()) {
                    let _path = file.path();
                    let name = file.file_name().to_string_lossy().to_string();
                    let size = file.metadata().map(|m| m.len()).unwrap_or(0);
                    total_size += size;
                    println!("  {} ({})", name.dimmed(), format_file_size(size));
                }
            }
            println!(
                "\n{}: {}",
                "Total Size".bright_white().bold(),
                format_file_size(total_size)
            );

            return Ok(());
        }
    }

    println!(
        "{} No agent session found matching '{}'",
        "!".yellow(),
        session_id
    );
    Ok(())
}

/// Show timeline of session activity with gap visualization
pub fn show_timeline(
    project_path: Option<&str>,
    include_agents: bool,
    provider: Option<&str>,
    all_providers: bool,
) -> Result<()> {
    use colored::*;
    use std::collections::BTreeMap;

    // Determine which storage paths to scan
    let storage_paths = if all_providers {
        get_agent_storage_paths(Some("all"))?
    } else if let Some(p) = provider {
        get_agent_storage_paths(Some(p))?
    } else {
        // Default to VS Code only
        let vscode_path = crate::workspace::get_workspace_storage_path()?;
        if vscode_path.exists() {
            vec![("vscode".to_string(), vscode_path)]
        } else {
            vec![]
        }
    };

    if storage_paths.is_empty() {
        if let Some(p) = provider {
            println!("No storage found for provider: {}", p);
        } else {
            println!("No workspaces found");
        }
        return Ok(());
    }

    let target_path = project_path.map(crate::workspace::normalize_path);

    // Collect all session dates (date -> (chat_count, agent_count, provider))
    let mut date_activity: BTreeMap<chrono::NaiveDate, (usize, usize)> = BTreeMap::new();
    let mut project_name = String::new();
    let mut providers_scanned: Vec<String> = Vec::new();

    for (provider_name, storage_path) in &storage_paths {
        if !storage_path.exists() {
            continue;
        }
        providers_scanned.push(provider_name.clone());

        for entry in std::fs::read_dir(storage_path)?.filter_map(|e| e.ok()) {
            let workspace_dir = entry.path();
            if !workspace_dir.is_dir() {
                continue;
            }

            // Get project path
            let workspace_json = workspace_dir.join("workspace.json");
            let project = std::fs::read_to_string(&workspace_json)
                .ok()
                .and_then(|c| serde_json::from_str::<crate::models::WorkspaceJson>(&c).ok())
                .and_then(|ws| {
                    ws.folder
                        .map(|f| crate::workspace::decode_workspace_folder(&f))
                });

            // Filter by project path if specified
            if let Some(ref target) = target_path {
                if project
                    .as_ref()
                    .map(|p| crate::workspace::normalize_path(p) != *target)
                    .unwrap_or(true)
                {
                    continue;
                }
                if project_name.is_empty() {
                    project_name = std::path::Path::new(target)
                        .file_name()
                        .map(|n| n.to_string_lossy().to_string())
                        .unwrap_or_else(|| target.clone());
                }
            }

            // Scan chatSessions
            let chat_sessions_dir = workspace_dir.join("chatSessions");
            if chat_sessions_dir.exists() {
                if let Ok(files) = std::fs::read_dir(&chat_sessions_dir) {
                    for file in files.filter_map(|f| f.ok()) {
                        if let Ok(meta) = file.metadata() {
                            if let Ok(modified) = meta.modified() {
                                let datetime: chrono::DateTime<chrono::Utc> = modified.into();
                                let date = datetime.date_naive();
                                let entry = date_activity.entry(date).or_insert((0, 0));
                                entry.0 += 1;
                            }
                        }
                    }
                }
            }

            // Scan chatEditingSessions (agent mode) if requested
            if include_agents {
                let agent_sessions_dir = workspace_dir.join("chatEditingSessions");
                if agent_sessions_dir.exists() {
                    if let Ok(dirs) = std::fs::read_dir(&agent_sessions_dir) {
                        for dir in dirs.filter_map(|d| d.ok()) {
                            if let Ok(meta) = dir.metadata() {
                                if let Ok(modified) = meta.modified() {
                                    let datetime: chrono::DateTime<chrono::Utc> = modified.into();
                                    let date = datetime.date_naive();
                                    let entry = date_activity.entry(date).or_insert((0, 0));
                                    entry.1 += 1;
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    if date_activity.is_empty() {
        println!("No session activity found.");
        return Ok(());
    }

    let title = if project_name.is_empty() {
        "All Workspaces".to_string()
    } else {
        project_name
    };

    let provider_info = if providers_scanned.len() > 1 || all_providers {
        format!(" ({})", providers_scanned.join(", "))
    } else {
        String::new()
    };

    println!(
        "\n{} Session Timeline: {}{}",
        "[*]".blue(),
        title.cyan(),
        provider_info.dimmed()
    );
    println!("{}", "=".repeat(60));

    let dates: Vec<_> = date_activity.keys().collect();
    let first_date = **dates.first().unwrap();
    let last_date = **dates.last().unwrap();

    println!(
        "Range: {} to {}",
        first_date.format("%Y-%m-%d"),
        last_date.format("%Y-%m-%d")
    );
    println!();

    // Find gaps (more than 1 day between sessions)
    let mut gaps: Vec<(chrono::NaiveDate, chrono::NaiveDate, i64)> = Vec::new();
    let mut prev_date: Option<chrono::NaiveDate> = None;

    for date in dates.iter() {
        if let Some(prev) = prev_date {
            let diff = (**date - prev).num_days();
            if diff > 1 {
                gaps.push((prev, **date, diff));
            }
        }
        prev_date = Some(**date);
    }

    // Show recent activity (last 14 days worth)
    println!("{}", "Recent Activity:".bright_yellow());
    let recent_dates: Vec<_> = date_activity.iter().rev().take(14).collect();
    for (date, (chats, agents)) in recent_dates.iter().rev() {
        let chat_bar = "".repeat((*chats).min(20));
        let agent_bar = if include_agents && *agents > 0 {
            format!(" {}", "".repeat((*agents).min(10)).bright_magenta())
        } else {
            String::new()
        };
        println!(
            "  {}{}{}",
            date.format("%Y-%m-%d"),
            chat_bar.bright_green(),
            agent_bar
        );
    }

    // Show gaps
    if !gaps.is_empty() {
        println!("\n{}", "Gaps (>1 day):".bright_red());
        for (start, end, days) in gaps.iter().take(10) {
            println!(
                "  {}{} ({} days)",
                start.format("%Y-%m-%d"),
                end.format("%Y-%m-%d"),
                days
            );
        }
        if gaps.len() > 10 {
            println!("  ... and {} more gaps", gaps.len() - 10);
        }
    }

    // Summary
    let total_chats: usize = date_activity.values().map(|(c, _)| c).sum();
    let total_agents: usize = date_activity.values().map(|(_, a)| a).sum();
    let total_days = date_activity.len();
    let total_gap_days: i64 = gaps.iter().map(|(_, _, d)| d - 1).sum();

    println!("\n{}", "Summary:".bright_white().bold());
    println!("  Active days: {}", total_days);
    println!("  Chat sessions: {}", total_chats);
    if include_agents {
        println!("  Agent sessions: {}", total_agents);
    }
    println!("  Total gap days: {}", total_gap_days);

    if include_agents {
        println!(
            "\n{} {} = chat, {} = agent",
            "Legend:".dimmed(),
            "".bright_green(),
            "".bright_magenta()
        );
    }

    Ok(())
}

/// Show the VS Code session index (state.vscdb) for a workspace
pub fn show_index(project_path: Option<&str>, all: bool) -> Result<()> {
    if all {
        return show_index_all();
    }

    use colored::Colorize;
    use tabled::{settings::Style as TableStyle, Table, Tabled};

    let path = crate::commands::register::resolve_path(project_path);
    let path_str = path.to_string_lossy().to_string();

    println!(
        "{} Session index for: {}",
        "[CSM]".cyan().bold(),
        path.display()
    );

    let (ws_id, ws_path, _folder) = crate::workspace::find_workspace_by_path(&path_str)?
        .ok_or_else(|| crate::error::CsmError::WorkspaceNotFound(path.display().to_string()))?;

    let db_path = crate::storage::get_workspace_storage_db(&ws_id)?;
    let index = crate::storage::read_chat_session_index(&db_path)?;

    println!(
        "   Workspace: {} ({})",
        ws_id.bright_yellow(),
        ws_path.display()
    );
    println!(
        "   Index version: {}, entries: {}\n",
        index.version,
        index.entries.len()
    );

    #[derive(Tabled)]
    struct IndexRow {
        #[tabled(rename = "Session ID")]
        session_id: String,
        #[tabled(rename = "Title")]
        title: String,
        #[tabled(rename = "isEmpty")]
        is_empty: String,
        #[tabled(rename = "Last Message")]
        last_message: String,
        #[tabled(rename = "ResponseState")]
        response_state: String,
        #[tabled(rename = "Location")]
        location: String,
    }

    let mut rows: Vec<IndexRow> = Vec::new();
    for (_, entry) in &index.entries {
        let last_msg = if entry.last_message_date > 0 {
            let secs = entry.last_message_date / 1000;
            chrono::DateTime::from_timestamp(secs, 0)
                .map(|dt| dt.format("%Y-%m-%d %H:%M").to_string())
                .unwrap_or_else(|| entry.last_message_date.to_string())
        } else {
            "0".to_string()
        };

        let state = match entry.last_response_state {
            0 => "Pending",
            1 => "Complete",
            2 => "Cancelled",
            3 => "Failed",
            4 => "NeedsInput",
            _ => "Unknown",
        };

        rows.push(IndexRow {
            session_id: entry.session_id[..12.min(entry.session_id.len())].to_string(),
            title: if entry.title.len() > 40 {
                format!("{}...", &entry.title[..37])
            } else {
                entry.title.clone()
            },
            is_empty: if entry.is_empty {
                "true".red().to_string()
            } else {
                "false".green().to_string()
            },
            last_message: last_msg,
            response_state: state.to_string(),
            location: entry.initial_location.clone(),
        });
    }

    // Sort by last message date descending
    rows.sort_by(|a, b| b.last_message.cmp(&a.last_message));

    let table = Table::new(&rows)
        .with(TableStyle::ascii_rounded())
        .to_string();
    println!("{}", table);

    // Also check for files on disk not in index
    let chat_dir = ws_path.join("chatSessions");
    if chat_dir.exists() {
        let mut disk_ids: std::collections::HashSet<String> = std::collections::HashSet::new();
        for entry in std::fs::read_dir(&chat_dir)? {
            let entry = entry?;
            let p = entry.path();
            if p.extension()
                .map(crate::storage::is_session_file_extension)
                .unwrap_or(false)
            {
                if let Some(stem) = p.file_stem() {
                    disk_ids.insert(stem.to_string_lossy().to_string());
                }
            }
        }
        let indexed_ids: std::collections::HashSet<String> =
            index.entries.keys().cloned().collect();
        let orphaned: Vec<_> = disk_ids.difference(&indexed_ids).collect();
        let stale: Vec<_> = indexed_ids.difference(&disk_ids).collect();

        if !orphaned.is_empty() {
            println!(
                "\n{} {} session(s) on disk but NOT in index (orphaned):",
                "[!]".yellow(),
                orphaned.len()
            );
            for id in &orphaned {
                println!("   {}", id.red());
            }
        }
        if !stale.is_empty() {
            println!(
                "\n{} {} index entries with NO file on disk (stale):",
                "[!]".yellow(),
                stale.len()
            );
            for id in &stale {
                println!("   {}", id.red());
            }
        }
        if orphaned.is_empty() && stale.is_empty() {
            println!("\n{} Index is in sync with files on disk.", "[OK]".green());
        }
    }

    Ok(())
}

/// Show index summary for all workspaces with chat sessions
fn show_index_all() -> Result<()> {
    use colored::Colorize;

    println!(
        "{} Scanning all workspace indexes...\n",
        "[CSM]".cyan().bold(),
    );

    let workspaces = crate::workspace::discover_workspaces()?;
    let ws_with_sessions: Vec<_> = workspaces
        .iter()
        .filter(|w| w.has_chat_sessions && w.chat_session_count > 0)
        .collect();

    if ws_with_sessions.is_empty() {
        println!("{} No workspaces with chat sessions found.", "[!]".yellow());
        return Ok(());
    }

    let mut total_entries = 0usize;
    let mut total_non_empty = 0usize;
    let mut total_orphaned = 0usize;
    let mut total_stale = 0usize;
    let mut _sync_ok = 0usize;
    let mut sync_issues = 0usize;

    for (i, ws) in ws_with_sessions.iter().enumerate() {
        let display_name = ws
            .project_path
            .as_deref()
            .unwrap_or(&ws.hash);

        let db_path = match crate::storage::get_workspace_storage_db(&ws.hash) {
            Ok(p) => p,
            Err(_) => {
                println!(
                    "[{}/{}] {} {}{} no state.vscdb",
                    i + 1,
                    ws_with_sessions.len(),
                    display_name.cyan(),
                    "".dimmed(),
                    "[!]".yellow()
                );
                continue;
            }
        };

        let index = match crate::storage::read_chat_session_index(&db_path) {
            Ok(idx) => idx,
            Err(_) => {
                println!(
                    "[{}/{}] {}{} no index in state.vscdb",
                    i + 1,
                    ws_with_sessions.len(),
                    display_name.cyan(),
                    "[!]".yellow()
                );
                continue;
            }
        };

        let non_empty = index.entries.values().filter(|e| !e.is_empty).count();
        total_entries += index.entries.len();
        total_non_empty += non_empty;

        // Check sync status
        let chat_dir = ws.workspace_path.join("chatSessions");
        let mut orphaned = 0usize;
        let mut stale = 0usize;
        if chat_dir.exists() {
            let mut disk_ids: std::collections::HashSet<String> = std::collections::HashSet::new();
            if let Ok(entries) = std::fs::read_dir(&chat_dir) {
                for entry in entries.flatten() {
                    let p = entry.path();
                    if p.extension()
                        .map(crate::storage::is_session_file_extension)
                        .unwrap_or(false)
                    {
                        if let Some(stem) = p.file_stem() {
                            disk_ids.insert(stem.to_string_lossy().to_string());
                        }
                    }
                }
            }
            let indexed_ids: std::collections::HashSet<String> =
                index.entries.keys().cloned().collect();
            orphaned = disk_ids.difference(&indexed_ids).count();
            stale = indexed_ids.difference(&disk_ids).count();
        }
        total_orphaned += orphaned;
        total_stale += stale;

        let status = if orphaned == 0 && stale == 0 {
            _sync_ok += 1;
            "[OK]".green().to_string()
        } else {
            sync_issues += 1;
            format!(
                "{}{}",
                if orphaned > 0 {
                    format!("{} orphaned ", orphaned).yellow().to_string()
                } else {
                    String::new()
                },
                if stale > 0 {
                    format!("{} stale", stale).yellow().to_string()
                } else {
                    String::new()
                }
            )
        };

        println!(
            "[{:>3}/{}] {}{} entries ({} with content) {}",
            i + 1,
            ws_with_sessions.len(),
            display_name.cyan(),
            index.entries.len(),
            non_empty.to_string().green(),
            status
        );
    }

    println!(
        "\n{} {} workspaces, {} index entries ({} with content)",
        "[OK]".green().bold(),
        ws_with_sessions.len().to_string().cyan(),
        total_entries.to_string().cyan(),
        total_non_empty.to_string().green()
    );
    if sync_issues > 0 {
        println!(
            "   {} {}/{} workspaces have sync issues ({} orphaned, {} stale)",
            "[!]".yellow(),
            sync_issues,
            ws_with_sessions.len(),
            total_orphaned,
            total_stale
        );
    } else {
        println!(
            "   {} All indexes in sync with files on disk.",
            "[OK]".green()
        );
    }

    Ok(())
}