maproom 0.1.0

Semantic code search powered by embeddings and SQLite
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
//! Encoding progress module for querying chunk/embedding counts and active encoding runs.
//!
//! This module mirrors the pattern established in `status.rs`:
//! query function + response structs + formatters.

use anyhow::Result;
use chrono::{NaiveDateTime, Utc};
use serde::{Deserialize, Serialize};
use std::sync::Arc;

use crate::db::traits::StoreCore;
use crate::db::traits::StoreEncoding;
use crate::db::SqliteStore;

/// Response struct for encoding progress queries.
#[derive(Debug, Serialize, Deserialize)]
pub struct EncodingProgressResponse {
    pub total_chunks: i64,
    pub total_embeddings: i64,
    pub percentage: f64,
    pub chunks_remaining: i64,
    pub repo_filter: Option<String>,
    pub active_run: Option<ActiveRunInfo>,
}

/// Information about an active encoding run.
#[derive(Debug, Serialize, Deserialize)]
pub struct ActiveRunInfo {
    pub run_id: i64,
    pub started_at: String,
    pub total_chunks: i64,
    pub chunks_completed: i64,
    pub chunks_per_second: Option<f64>,
    pub provider: Option<String>,
    pub dimension: Option<i32>,
    pub estimated_seconds_remaining: Option<f64>,
    pub elapsed_seconds: Option<f64>,
}

/// Calculate ETA in seconds based on remaining chunks and throughput.
///
/// Returns `None` when `chunks_per_second` is zero, negative, or `None`.
pub fn calculate_eta(remaining_chunks: i64, chunks_per_second: Option<f64>) -> Option<f64> {
    match chunks_per_second {
        Some(rate) if rate > 0.0 => Some(remaining_chunks as f64 / rate),
        _ => None,
    }
}

/// Calculate elapsed seconds from a timestamp string to now.
///
/// Accepts SQLite `datetime('now')` format: `YYYY-MM-DD HH:MM:SS`
/// and RFC 3339 / ISO 8601 format: `YYYY-MM-DDTHH:MM:SS+00:00`.
pub fn calculate_elapsed_seconds(started_at: &str) -> Result<f64> {
    // Try SQLite datetime format first: "2026-02-05 14:30:00"
    let naive = NaiveDateTime::parse_from_str(started_at, "%Y-%m-%d %H:%M:%S")
        .or_else(|_| {
            // Try ISO 8601 / RFC 3339 with T separator: "2026-02-05T14:30:00"
            NaiveDateTime::parse_from_str(started_at, "%Y-%m-%dT%H:%M:%S")
        })
        .map_err(|e| {
            anyhow::anyhow!(
                "Failed to parse timestamp '{}': {}. Expected format: YYYY-MM-DD HH:MM:SS",
                started_at,
                e
            )
        })?;

    // Treat the parsed time as UTC (SQLite datetime('now') produces UTC)
    let start_utc = naive.and_utc();
    let now = Utc::now();
    let elapsed = now.signed_duration_since(start_utc);
    Ok(elapsed.num_milliseconds() as f64 / 1000.0)
}

/// Check if a timestamp is stale (more than 1 hour old).
///
/// Returns `true` if the timestamp is more than 3600 seconds in the past,
/// or if the timestamp cannot be parsed.
fn is_stale(timestamp: &str) -> bool {
    match calculate_elapsed_seconds(timestamp) {
        Ok(elapsed) => elapsed > 3600.0,
        Err(_) => true, // If we can't parse, treat as stale
    }
}

/// Query the database for encoding progress statistics.
///
/// If `repo_filter` is provided, counts are scoped to that repo.
/// Otherwise, global counts are returned.
pub async fn get_encoding_progress(
    store: Arc<SqliteStore>,
    repo_filter: Option<String>,
) -> Result<EncodingProgressResponse> {
    let (total_chunks, total_embeddings) = match &repo_filter {
        Some(repo_name) => {
            let chunks = store.get_repo_chunk_count(repo_name).await?;
            let embeddings = store.get_repo_embedding_count(repo_name).await?;
            (chunks, embeddings)
        }
        None => {
            let chunks = store.get_global_chunk_count().await?;
            let embeddings = store.get_global_embedding_count().await?;
            (chunks, embeddings)
        }
    };

    let percentage = if total_chunks == 0 {
        0.0
    } else {
        (total_embeddings as f64 / total_chunks as f64) * 100.0
    };

    let chunks_remaining = (total_chunks - total_embeddings).max(0);

    // Check for active encoding run
    let active_run = match store.get_active_encoding_run().await? {
        Some(run) => {
            // Staleness detection: if last_batch_at is >1 hour old, don't show as active
            let stale = match &run.last_batch_at {
                Some(last_batch) => is_stale(last_batch),
                // If there's no last_batch_at, check started_at instead
                None => is_stale(&run.started_at),
            };

            if stale {
                None
            } else {
                let remaining = (run.total_chunks - run.chunks_completed).max(0);
                let estimated_seconds_remaining = calculate_eta(remaining, run.chunks_per_second);

                let elapsed_seconds = calculate_elapsed_seconds(&run.started_at).ok();

                Some(ActiveRunInfo {
                    run_id: run.id,
                    started_at: run.started_at,
                    total_chunks: run.total_chunks,
                    chunks_completed: run.chunks_completed,
                    chunks_per_second: run.chunks_per_second,
                    provider: run.provider,
                    dimension: run.dimension,
                    estimated_seconds_remaining,
                    elapsed_seconds,
                })
            }
        }
        None => None,
    };

    Ok(EncodingProgressResponse {
        total_chunks,
        total_embeddings,
        percentage,
        chunks_remaining,
        repo_filter,
        active_run,
    })
}

/// Format number with thousands separator (mirrors status.rs format_number).
fn format_number(n: i64) -> String {
    let s = n.to_string();
    let mut result = String::new();

    for (count, c) in s.chars().rev().enumerate() {
        if count > 0 && count % 3 == 0 {
            result.insert(0, ',');
        }
        result.insert(0, c);
    }

    result
}

/// Format seconds as a human-readable duration string.
///
/// Examples: "~0s", "~30s", "~2m 30s", "~1h 5m"
fn format_duration(seconds: f64) -> String {
    let total_secs = seconds.round() as u64;
    if total_secs < 60 {
        format!("~{}s", total_secs)
    } else if total_secs < 3600 {
        let mins = total_secs / 60;
        let secs = total_secs % 60;
        if secs == 0 {
            format!("~{}m", mins)
        } else {
            format!("~{}m {}s", mins, secs)
        }
    } else {
        let hours = total_secs / 3600;
        let mins = (total_secs % 3600) / 60;
        if mins == 0 {
            format!("~{}h", hours)
        } else {
            format!("~{}h {}m", hours, mins)
        }
    }
}

/// Format encoding progress as human-readable text.
pub fn format_text(response: &EncodingProgressResponse) -> String {
    let mut output = String::new();

    if let Some(ref repo) = response.repo_filter {
        output.push_str(&format!("Repository: {}\n", repo));
    }

    output.push_str(&format!(
        "Total chunks: {}\n",
        format_number(response.total_chunks)
    ));
    output.push_str(&format!(
        "Embeddings: {} ({:.1}%)\n",
        format_number(response.total_embeddings),
        response.percentage
    ));
    output.push_str(&format!(
        "Remaining: {}\n",
        format_number(response.chunks_remaining)
    ));

    match &response.active_run {
        Some(run) => {
            output.push_str("\nActive Run:\n");

            // Provider line: "ollama (1024 dimensions)" or just provider or just dimension
            match (&run.provider, run.dimension) {
                (Some(provider), Some(dim)) => {
                    output.push_str(&format!(
                        "  Provider:        {} ({} dimensions)\n",
                        provider, dim
                    ));
                }
                (Some(provider), None) => {
                    output.push_str(&format!("  Provider:        {}\n", provider));
                }
                (None, Some(dim)) => {
                    output.push_str(&format!("  Provider:        ({} dimensions)\n", dim));
                }
                (None, None) => {}
            }

            output.push_str(&format!("  Started:         {}\n", run.started_at));

            if let Some(elapsed) = run.elapsed_seconds {
                output.push_str(&format!(
                    "  Elapsed:         {}\n",
                    format_duration(elapsed)
                ));
            }

            output.push_str(&format!(
                "  Batch progress:  {} / {} chunks\n",
                format_number(run.chunks_completed),
                format_number(run.total_chunks)
            ));

            if let Some(cps) = run.chunks_per_second {
                output.push_str(&format!("  Throughput:      {:.1} chunks/s\n", cps));
            }

            if let Some(eta_secs) = run.estimated_seconds_remaining {
                output.push_str(&format!(
                    "  ETA:             {} remaining\n",
                    format_duration(eta_secs)
                ));
            }
        }
        None => {
            output.push_str("\nNo active encoding run.\n");
        }
    }

    output
}

/// Format encoding progress as JSON.
pub fn format_json(response: &EncodingProgressResponse) -> Result<String> {
    serde_json::to_string_pretty(response)
        .map_err(|e| anyhow::anyhow!("Failed to serialize encoding progress to JSON: {}", e))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::db::sqlite::SqliteStore;
    use crate::db::traits::StoreChunks;
    use crate::db::traits::StoreEncoding;
    use crate::db::traits::StoreMigration;
    use crate::db::{ChunkRecord, FileRecord};
    use rusqlite::params;
    use std::sync::atomic::{AtomicUsize, Ordering};

    /// Counter for unique shared in-memory database names.
    static TEST_STORE_COUNTER: AtomicUsize = AtomicUsize::new(0);

    /// Helper to create a test store with migrations applied.
    async fn setup_test_store() -> Arc<SqliteStore> {
        let store = Arc::new(SqliteStore::connect(":memory:").await.unwrap());
        store
    }

    /// Helper to create test data: a repo, worktree, commit, file, and N chunks.
    /// Returns (repo_id, worktree_id, commit_id, file_id).
    async fn setup_test_data(
        store: &Arc<SqliteStore>,
        repo_name: &str,
        num_chunks: usize,
    ) -> (i64, i64, i64, i64) {
        let repo_id = store
            .get_or_create_repo(repo_name, "/test/path")
            .await
            .unwrap();
        let worktree_id = store
            .get_or_create_worktree(repo_id, "main", "/test/path")
            .await
            .unwrap();
        let commit_id = store
            .get_or_create_commit(repo_id, "abc123", None)
            .await
            .unwrap();

        let file = FileRecord {
            repo_id,
            worktree_id,
            commit_id,
            relpath: "test.rs".to_string(),
            language: Some("rust".to_string()),
            content_hash: format!("hash_{}", repo_name),
            size_bytes: 100,
            last_modified: None,
        };
        let file_id = store.upsert_file(&file).await.unwrap();

        for i in 0..num_chunks {
            let chunk = ChunkRecord {
                file_id,
                worktree_id,
                blob_sha: format!("blob_{}_{}", repo_name, i),
                symbol_name: Some(format!("fn_{}", i)),
                kind: "function".to_string(),
                signature: None,
                docstring: None,
                start_line: (i * 10 + 1) as i32,
                end_line: (i * 10 + 10) as i32,
                preview: format!("fn fn_{}() {{}}", i),
                ts_doc_text: String::new(),
                recency_score: 1.0,
                churn_score: 0.5,
                metadata: None,
            };
            store.insert_chunk(&chunk).await.unwrap();
        }

        (repo_id, worktree_id, commit_id, file_id)
    }

    /// Helper to insert embeddings for blob_shas.
    async fn insert_embeddings(store: &Arc<SqliteStore>, blob_shas: Vec<String>) {
        for blob_sha in blob_shas {
            store
                .run(move |conn| {
                    conn.execute(
                        "INSERT INTO code_embeddings (blob_sha, embedding, embedding_dim, model_version)
                         VALUES (?1, ?2, ?3, ?4)",
                        params![blob_sha, vec![0u8; 4096], 1024, "test-model"],
                    )?;
                    Ok(())
                })
                .await
                .unwrap();
        }
    }

    // ==================== Test Case #1: get_global_chunk_count - empty database ====================
    #[tokio::test]
    async fn test_global_chunk_count_empty() {
        let store = setup_test_store().await;
        let count = store.get_global_chunk_count().await.unwrap();
        assert_eq!(count, 0);
    }

    // ==================== Test Case #1: get_global_chunk_count - with data ====================
    #[tokio::test]
    async fn test_global_chunk_count_with_data() {
        let store = setup_test_store().await;
        setup_test_data(&store, "test-repo", 5).await;
        let count = store.get_global_chunk_count().await.unwrap();
        assert_eq!(count, 5);
    }

    // ==================== Test Case #1: get_global_chunk_count - distinct blob_sha ====================
    #[tokio::test]
    async fn test_global_chunk_count_distinct_blob_sha() {
        let store = setup_test_store().await;
        // Create chunks in two repos with some overlapping blob_shas
        let repo_id = store
            .get_or_create_repo("repo1", "/test/path1")
            .await
            .unwrap();
        let wt1 = store
            .get_or_create_worktree(repo_id, "main", "/test/path1")
            .await
            .unwrap();
        let commit_id = store
            .get_or_create_commit(repo_id, "abc123", None)
            .await
            .unwrap();
        let file = FileRecord {
            repo_id,
            worktree_id: wt1,
            commit_id,
            relpath: "test.rs".to_string(),
            language: Some("rust".to_string()),
            content_hash: "hash1".to_string(),
            size_bytes: 100,
            last_modified: None,
        };
        let file_id = store.upsert_file(&file).await.unwrap();

        // Create two chunks with same blob_sha
        let chunk1 = ChunkRecord {
            file_id,
            worktree_id: wt1,
            blob_sha: "shared_blob".to_string(),
            symbol_name: Some("fn1".to_string()),
            kind: "function".to_string(),
            signature: None,
            docstring: None,
            start_line: 1,
            end_line: 10,
            preview: "fn fn1() {}".to_string(),
            ts_doc_text: String::new(),
            recency_score: 1.0,
            churn_score: 0.5,
            metadata: None,
        };
        store.insert_chunk(&chunk1).await.unwrap();

        let chunk2 = ChunkRecord {
            file_id,
            worktree_id: wt1,
            blob_sha: "shared_blob".to_string(),
            symbol_name: Some("fn2".to_string()),
            kind: "function".to_string(),
            signature: None,
            docstring: None,
            start_line: 11,
            end_line: 20,
            preview: "fn fn2() {}".to_string(),
            ts_doc_text: String::new(),
            recency_score: 1.0,
            churn_score: 0.5,
            metadata: None,
        };
        store.insert_chunk(&chunk2).await.unwrap();

        // Should count distinct blob_shas: only 1 despite 2 chunk rows
        let count = store.get_global_chunk_count().await.unwrap();
        assert_eq!(count, 1);
    }

    // ==================== Test Case #2: get_global_embedding_count - empty database ====================
    #[tokio::test]
    async fn test_global_embedding_count_empty() {
        let store = setup_test_store().await;
        let count = store.get_global_embedding_count().await.unwrap();
        assert_eq!(count, 0);
    }

    // ==================== Test Case #2: get_global_embedding_count - with data ====================
    #[tokio::test]
    async fn test_global_embedding_count_with_data() {
        let store = setup_test_store().await;
        setup_test_data(&store, "test-repo", 3).await;
        insert_embeddings(
            &store,
            vec![
                "blob_test-repo_0".to_string(),
                "blob_test-repo_1".to_string(),
            ],
        )
        .await;
        let count = store.get_global_embedding_count().await.unwrap();
        assert_eq!(count, 2);
    }

    // ==================== Test Case #2: embeddings independent of chunks ====================
    #[tokio::test]
    async fn test_global_embedding_count_independent_of_chunks() {
        let store = setup_test_store().await;
        // Insert embeddings without corresponding chunks
        insert_embeddings(&store, vec!["orphan_blob".to_string()]).await;
        let count = store.get_global_embedding_count().await.unwrap();
        assert_eq!(count, 1);
    }

    // ==================== Test Case #3: get_repo_chunk_count - non-existent repo ====================
    #[tokio::test]
    async fn test_repo_chunk_count_nonexistent_repo() {
        let store = setup_test_store().await;
        let count = store.get_repo_chunk_count("nonexistent").await.unwrap();
        assert_eq!(count, 0);
    }

    // ==================== Test Case #3: get_repo_chunk_count - correct count ====================
    #[tokio::test]
    async fn test_repo_chunk_count_correct() {
        let store = setup_test_store().await;
        setup_test_data(&store, "repo-a", 3).await;
        setup_test_data(&store, "repo-b", 5).await;
        let count_a = store.get_repo_chunk_count("repo-a").await.unwrap();
        let count_b = store.get_repo_chunk_count("repo-b").await.unwrap();
        assert_eq!(count_a, 3);
        assert_eq!(count_b, 5);
    }

    // ==================== Test Case #4: get_repo_embedding_count - non-existent repo ====================
    #[tokio::test]
    async fn test_repo_embedding_count_nonexistent_repo() {
        let store = setup_test_store().await;
        let count = store.get_repo_embedding_count("nonexistent").await.unwrap();
        assert_eq!(count, 0);
    }

    // ==================== Test Case #4: get_repo_embedding_count - correct count ====================
    #[tokio::test]
    async fn test_repo_embedding_count_correct() {
        let store = setup_test_store().await;
        setup_test_data(&store, "repo-a", 3).await;
        setup_test_data(&store, "repo-b", 2).await;
        // Embed only repo-a chunks
        insert_embeddings(
            &store,
            vec!["blob_repo-a_0".to_string(), "blob_repo-a_1".to_string()],
        )
        .await;
        let count_a = store.get_repo_embedding_count("repo-a").await.unwrap();
        let count_b = store.get_repo_embedding_count("repo-b").await.unwrap();
        assert_eq!(count_a, 2);
        assert_eq!(count_b, 0);
    }

    // ==================== Test Case #5: create_encoding_run ====================
    #[tokio::test]
    async fn test_create_encoding_run() {
        let store = setup_test_store().await;
        let run_id = store
            .create_encoding_run(100, Some("ollama"), Some(768))
            .await
            .unwrap();
        assert!(run_id > 0);

        // Verify defaults
        let run = store.get_active_encoding_run().await.unwrap().unwrap();
        assert_eq!(run.id, run_id);
        assert_eq!(run.status, "running");
        assert_eq!(run.total_chunks, 100);
        assert_eq!(run.chunks_completed, 0);
        assert_eq!(run.provider, Some("ollama".to_string()));
        assert_eq!(run.dimension, Some(768));
        assert!(!run.started_at.is_empty());
    }

    // ==================== Test Case #6: update_encoding_run_progress ====================
    #[tokio::test]
    async fn test_update_encoding_run_progress() {
        let store = setup_test_store().await;
        let run_id = store
            .create_encoding_run(100, Some("openai"), Some(1536))
            .await
            .unwrap();

        store
            .update_encoding_run_progress(run_id, 50, Some(25.0))
            .await
            .unwrap();

        let run = store.get_active_encoding_run().await.unwrap().unwrap();
        assert_eq!(run.chunks_completed, 50);
        assert_eq!(run.chunks_per_second, Some(25.0));
        assert!(run.last_batch_at.is_some());
    }

    // ==================== Test Case #6: update_encoding_run_progress - nonexistent ====================
    #[tokio::test]
    async fn test_update_encoding_run_progress_nonexistent() {
        let store = setup_test_store().await;
        // Should not error even with non-existent run_id
        let result = store
            .update_encoding_run_progress(999, 50, Some(25.0))
            .await;
        assert!(result.is_ok());
    }

    // ==================== Test Case #7: complete_encoding_run - completed ====================
    #[tokio::test]
    async fn test_complete_encoding_run_completed() {
        let store = setup_test_store().await;
        let run_id = store.create_encoding_run(100, None, None).await.unwrap();

        store
            .complete_encoding_run(run_id, "completed")
            .await
            .unwrap();

        // Should no longer be active
        let active = store.get_active_encoding_run().await.unwrap();
        assert!(active.is_none());

        // Verify status and finished_at via raw query
        store
            .run(move |conn| {
                let (status, finished_at): (String, Option<String>) = conn.query_row(
                    "SELECT status, finished_at FROM encoding_runs WHERE id = ?1",
                    params![run_id],
                    |row| Ok((row.get(0)?, row.get(1)?)),
                )?;
                assert_eq!(status, "completed");
                assert!(finished_at.is_some());
                Ok(())
            })
            .await
            .unwrap();
    }

    // ==================== Test Case #7: complete_encoding_run - failed ====================
    #[tokio::test]
    async fn test_complete_encoding_run_failed() {
        let store = setup_test_store().await;
        let run_id = store.create_encoding_run(100, None, None).await.unwrap();

        store.complete_encoding_run(run_id, "failed").await.unwrap();

        let active = store.get_active_encoding_run().await.unwrap();
        assert!(active.is_none());
    }

    // ==================== Test Case #7: complete_encoding_run - idempotent ====================
    #[tokio::test]
    async fn test_complete_encoding_run_idempotent() {
        let store = setup_test_store().await;
        let run_id = store.create_encoding_run(100, None, None).await.unwrap();

        store
            .complete_encoding_run(run_id, "completed")
            .await
            .unwrap();
        // Call again - should not error
        store
            .complete_encoding_run(run_id, "completed")
            .await
            .unwrap();
    }

    // ==================== Test Case #8: get_active_encoding_run - no runs ====================
    #[tokio::test]
    async fn test_get_active_encoding_run_none() {
        let store = setup_test_store().await;
        let active = store.get_active_encoding_run().await.unwrap();
        assert!(active.is_none());
    }

    // ==================== Test Case #8: get_active_encoding_run - all completed ====================
    #[tokio::test]
    async fn test_get_active_encoding_run_all_completed() {
        let store = setup_test_store().await;
        let run_id = store.create_encoding_run(100, None, None).await.unwrap();
        store
            .complete_encoding_run(run_id, "completed")
            .await
            .unwrap();

        let active = store.get_active_encoding_run().await.unwrap();
        assert!(active.is_none());
    }

    // ==================== Test Case #8: get_active_encoding_run - returns latest ====================
    #[tokio::test]
    async fn test_get_active_encoding_run_returns_latest() {
        let store = setup_test_store().await;
        let _run1 = store
            .create_encoding_run(50, Some("ollama"), Some(768))
            .await
            .unwrap();
        let run2 = store
            .create_encoding_run(100, Some("openai"), Some(1536))
            .await
            .unwrap();

        let active = store.get_active_encoding_run().await.unwrap().unwrap();
        assert_eq!(active.id, run2);
        assert_eq!(active.total_chunks, 100);
        assert_eq!(active.provider, Some("openai".to_string()));
    }

    // ==================== Test Case #9: get_encoding_progress - no data ====================
    #[tokio::test]
    async fn test_encoding_progress_no_data() {
        let store = setup_test_store().await;
        let progress = get_encoding_progress(store, None).await.unwrap();
        assert_eq!(progress.total_chunks, 0);
        assert_eq!(progress.total_embeddings, 0);
        assert_eq!(progress.percentage, 0.0);
        assert_eq!(progress.chunks_remaining, 0);
        assert!(progress.active_run.is_none());
    }

    // ==================== Test Case #10: get_encoding_progress - partial ====================
    #[tokio::test]
    async fn test_encoding_progress_partial() {
        let store = setup_test_store().await;
        setup_test_data(&store, "test-repo", 100).await;
        let mut shas = Vec::new();
        for i in 0..50 {
            shas.push(format!("blob_test-repo_{}", i));
        }
        insert_embeddings(&store, shas).await;

        let progress = get_encoding_progress(store, None).await.unwrap();
        assert_eq!(progress.total_chunks, 100);
        assert_eq!(progress.total_embeddings, 50);
        assert!((progress.percentage - 50.0).abs() < f64::EPSILON);
        assert_eq!(progress.chunks_remaining, 50);
    }

    // ==================== Test Case #11: get_encoding_progress - complete ====================
    #[tokio::test]
    async fn test_encoding_progress_complete() {
        let store = setup_test_store().await;
        setup_test_data(&store, "test-repo", 10).await;
        let shas: Vec<String> = (0..10).map(|i| format!("blob_test-repo_{}", i)).collect();
        insert_embeddings(&store, shas).await;

        let progress = get_encoding_progress(store, None).await.unwrap();
        assert_eq!(progress.total_chunks, 10);
        assert_eq!(progress.total_embeddings, 10);
        assert!((progress.percentage - 100.0).abs() < f64::EPSILON);
        assert_eq!(progress.chunks_remaining, 0);
    }

    // ==================== Test Case #12: get_encoding_progress - with repo filter ====================
    #[tokio::test]
    async fn test_encoding_progress_repo_filter() {
        let store = setup_test_store().await;
        setup_test_data(&store, "repo-a", 10).await;
        setup_test_data(&store, "repo-b", 20).await;
        insert_embeddings(
            &store,
            vec![
                "blob_repo-a_0".to_string(),
                "blob_repo-a_1".to_string(),
                "blob_repo-b_0".to_string(),
            ],
        )
        .await;

        let progress_a = get_encoding_progress(store.clone(), Some("repo-a".to_string()))
            .await
            .unwrap();
        assert_eq!(progress_a.total_chunks, 10);
        assert_eq!(progress_a.total_embeddings, 2);
        assert_eq!(progress_a.repo_filter, Some("repo-a".to_string()));

        let progress_b = get_encoding_progress(store.clone(), Some("repo-b".to_string()))
            .await
            .unwrap();
        assert_eq!(progress_b.total_chunks, 20);
        assert_eq!(progress_b.total_embeddings, 1);
    }

    // ==================== Test Case #12: get_encoding_progress - non-existent repo filter ====================
    #[tokio::test]
    async fn test_encoding_progress_nonexistent_repo() {
        let store = setup_test_store().await;
        setup_test_data(&store, "repo-a", 10).await;

        let progress = get_encoding_progress(store, Some("nonexistent".to_string()))
            .await
            .unwrap();
        assert_eq!(progress.total_chunks, 0);
        assert_eq!(progress.total_embeddings, 0);
        assert_eq!(progress.percentage, 0.0);
    }

    // ==================== Test Case #13: get_encoding_progress - with active run ====================
    #[tokio::test]
    async fn test_encoding_progress_with_active_run() {
        let store = setup_test_store().await;
        setup_test_data(&store, "test-repo", 100).await;
        let run_id = store
            .create_encoding_run(100, Some("ollama"), Some(768))
            .await
            .unwrap();
        store
            .update_encoding_run_progress(run_id, 50, Some(10.0))
            .await
            .unwrap();

        let progress = get_encoding_progress(store, None).await.unwrap();
        let run = progress.active_run.unwrap();
        assert_eq!(run.run_id, run_id);
        assert_eq!(run.total_chunks, 100);
        assert_eq!(run.chunks_completed, 50);
        assert_eq!(run.chunks_per_second, Some(10.0));
        assert_eq!(run.provider, Some("ollama".to_string()));
        assert_eq!(run.dimension, Some(768));
        // ETA: 50 remaining / 10 per sec = 5.0 seconds
        assert!((run.estimated_seconds_remaining.unwrap() - 5.0).abs() < f64::EPSILON);
    }

    // ==================== Test Case #14: get_encoding_progress - division by zero ====================
    #[tokio::test]
    async fn test_encoding_progress_division_by_zero() {
        let store = setup_test_store().await;
        // No chunks at all
        let progress = get_encoding_progress(store, None).await.unwrap();
        assert_eq!(progress.percentage, 0.0);
        assert!(!progress.percentage.is_nan());
        assert!(!progress.percentage.is_infinite());
    }

    // ==================== Test Case #15: format_text - basic output ====================
    #[test]
    fn test_format_text_basic() {
        let response = EncodingProgressResponse {
            total_chunks: 1500,
            total_embeddings: 750,
            percentage: 50.0,
            chunks_remaining: 750,
            repo_filter: None,
            active_run: None,
        };

        let output = format_text(&response);
        assert!(output.contains("Total chunks: 1,500"));
        assert!(output.contains("Embeddings: 750 (50.0%)"));
        assert!(output.contains("Remaining: 750"));
        assert!(output.contains("No active encoding run."));
    }

    // ==================== Test Case #16: format_text - no active run ====================
    #[test]
    fn test_format_text_no_active_run() {
        let response = EncodingProgressResponse {
            total_chunks: 100,
            total_embeddings: 50,
            percentage: 50.0,
            chunks_remaining: 50,
            repo_filter: None,
            active_run: None,
        };

        let output = format_text(&response);
        assert!(output.contains("No active encoding run."));
    }

    // ==================== Test Case #17: format_text - with active run ====================
    #[test]
    fn test_format_text_with_active_run() {
        let response = EncodingProgressResponse {
            total_chunks: 1000,
            total_embeddings: 500,
            percentage: 50.0,
            chunks_remaining: 500,
            repo_filter: None,
            active_run: Some(ActiveRunInfo {
                run_id: 1,
                started_at: "2026-01-01 00:00:00".to_string(),
                total_chunks: 1000,
                chunks_completed: 500,
                chunks_per_second: Some(10.0),
                provider: Some("ollama".to_string()),
                dimension: Some(768),
                estimated_seconds_remaining: Some(50.0),
                elapsed_seconds: Some(135.0),
            }),
        };

        let output = format_text(&response);
        assert!(output.contains("Active Run:"));
        assert!(output.contains("Provider:        ollama (768 dimensions)"));
        assert!(output.contains("Started:         2026-01-01 00:00:00"));
        assert!(output.contains("Elapsed:         ~2m 15s"));
        assert!(output.contains("Batch progress:  500 / 1,000 chunks"));
        assert!(output.contains("Throughput:      10.0 chunks/s"));
        assert!(output.contains("ETA:             ~50s remaining"));
    }

    // ==================== Test Case #18: format_text - zero chunks ====================
    #[test]
    fn test_format_text_zero_chunks() {
        let response = EncodingProgressResponse {
            total_chunks: 0,
            total_embeddings: 0,
            percentage: 0.0,
            chunks_remaining: 0,
            repo_filter: None,
            active_run: None,
        };

        let output = format_text(&response);
        assert!(output.contains("Total chunks: 0"));
        assert!(output.contains("Embeddings: 0 (0.0%)"));
        assert!(output.contains("Remaining: 0"));
    }

    // ==================== Test Case #19: format_json - valid JSON ====================
    #[test]
    fn test_format_json_valid() {
        let response = EncodingProgressResponse {
            total_chunks: 100,
            total_embeddings: 50,
            percentage: 50.0,
            chunks_remaining: 50,
            repo_filter: None,
            active_run: None,
        };

        let json_str = format_json(&response).unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&json_str).unwrap();
        assert_eq!(parsed["total_chunks"], 100);
        assert_eq!(parsed["total_embeddings"], 50);
        assert_eq!(parsed["percentage"], 50.0);
        assert_eq!(parsed["chunks_remaining"], 50);
        assert!(parsed["active_run"].is_null());
    }

    // ==================== Test Case #20: format_json - with active run ====================
    #[test]
    fn test_format_json_with_active_run() {
        let response = EncodingProgressResponse {
            total_chunks: 100,
            total_embeddings: 50,
            percentage: 50.0,
            chunks_remaining: 50,
            repo_filter: Some("test-repo".to_string()),
            active_run: Some(ActiveRunInfo {
                run_id: 1,
                started_at: "2026-01-01 00:00:00".to_string(),
                total_chunks: 100,
                chunks_completed: 50,
                chunks_per_second: Some(10.0),
                provider: Some("ollama".to_string()),
                dimension: Some(768),
                estimated_seconds_remaining: Some(5.0),
                elapsed_seconds: Some(120.0),
            }),
        };

        let json_str = format_json(&response).unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&json_str).unwrap();
        assert!(parsed["active_run"].is_object());
        assert_eq!(parsed["active_run"]["run_id"], 1);
        assert_eq!(parsed["active_run"]["provider"], "ollama");
        assert_eq!(parsed["active_run"]["dimension"], 768);
        assert_eq!(parsed["repo_filter"], "test-repo");
    }

    // ==================== Test Case #21: format_json - without active run ====================
    #[test]
    fn test_format_json_without_active_run() {
        let response = EncodingProgressResponse {
            total_chunks: 0,
            total_embeddings: 0,
            percentage: 0.0,
            chunks_remaining: 0,
            repo_filter: None,
            active_run: None,
        };

        let json_str = format_json(&response).unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&json_str).unwrap();
        assert!(parsed["active_run"].is_null());
    }

    // ==================== format_text with repo filter ====================
    #[test]
    fn test_format_text_with_repo_filter() {
        let response = EncodingProgressResponse {
            total_chunks: 500,
            total_embeddings: 250,
            percentage: 50.0,
            chunks_remaining: 250,
            repo_filter: Some("my-repo".to_string()),
            active_run: None,
        };

        let output = format_text(&response);
        assert!(output.contains("Repository: my-repo"));
    }

    // ==================== format_text - large numbers ====================
    #[test]
    fn test_format_text_large_numbers() {
        let response = EncodingProgressResponse {
            total_chunks: 1_234_567,
            total_embeddings: 987_654,
            percentage: 80.0,
            chunks_remaining: 246_913,
            repo_filter: None,
            active_run: None,
        };

        let output = format_text(&response);
        assert!(output.contains("Total chunks: 1,234,567"));
        assert!(output.contains("Embeddings: 987,654 (80.0%)"));
        assert!(output.contains("Remaining: 246,913"));
    }

    // ==================== format_duration tests ====================
    #[test]
    fn test_format_duration_seconds() {
        assert_eq!(format_duration(0.0), "~0s");
        assert_eq!(format_duration(30.0), "~30s");
        assert_eq!(format_duration(59.0), "~59s");
    }

    #[test]
    fn test_format_duration_minutes() {
        assert_eq!(format_duration(60.0), "~1m");
        assert_eq!(format_duration(90.0), "~1m 30s");
        assert_eq!(format_duration(150.0), "~2m 30s");
    }

    #[test]
    fn test_format_duration_hours() {
        assert_eq!(format_duration(3600.0), "~1h");
        assert_eq!(format_duration(3900.0), "~1h 5m");
        assert_eq!(format_duration(7200.0), "~2h");
    }

    // ==================== format_number tests ====================
    #[test]
    fn test_format_number() {
        assert_eq!(format_number(0), "0");
        assert_eq!(format_number(100), "100");
        assert_eq!(format_number(1000), "1,000");
        assert_eq!(format_number(1234567), "1,234,567");
    }

    // ==================== ETA edge cases ====================
    #[test]
    fn test_eta_zero_throughput() {
        let run = ActiveRunInfo {
            run_id: 1,
            started_at: "2026-01-01 00:00:00".to_string(),
            total_chunks: 100,
            chunks_completed: 50,
            chunks_per_second: Some(0.0),
            provider: None,
            dimension: None,
            estimated_seconds_remaining: None, // Should not be computed with 0 throughput
            elapsed_seconds: None,
        };
        // Verified the logic: when chunks_per_second is 0.0, cps > 0.0 is false, so ETA = None
        assert!(run.estimated_seconds_remaining.is_none());
    }

    // ==================== Test Case #30: migration creates encoding_runs table ====================
    #[tokio::test]
    async fn test_migration_creates_encoding_runs() {
        let store = setup_test_store().await;
        // Verify table exists by inserting/selecting
        store
            .run(|conn| {
                conn.execute(
                    "INSERT INTO encoding_runs (total_chunks) VALUES (?1)",
                    params![100],
                )?;
                let count: i64 = conn.query_row(
                    "SELECT COUNT(*) FROM encoding_runs",
                    [],
                    |row| row.get(0),
                )?;
                assert_eq!(count, 1);

                // Verify schema columns
                let (id, started_at, status, total_chunks, chunks_completed): (
                    i64,
                    String,
                    String,
                    i64,
                    i64,
                ) = conn.query_row(
                    "SELECT id, started_at, status, total_chunks, chunks_completed FROM encoding_runs WHERE id = 1",
                    [],
                    |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?, row.get(4)?)),
                )?;
                assert_eq!(id, 1);
                assert!(!started_at.is_empty());
                assert_eq!(status, "running");
                assert_eq!(total_chunks, 100);
                assert_eq!(chunks_completed, 0);
                Ok(())
            })
            .await
            .unwrap();
    }

    // ==================== Test Case #31: migration is idempotent ====================
    #[tokio::test]
    async fn test_migration_idempotent() {
        let store = setup_test_store().await;
        // Migrate again - should not error
        store.migrate().await.unwrap();

        // Still works
        let count = store.get_global_chunk_count().await.unwrap();
        assert_eq!(count, 0);
    }

    // ==================== mark_stale_runs_as_failed - marks multiple stale runs ====================
    #[tokio::test]
    async fn test_mark_stale_runs_as_failed_multiple() {
        let store = setup_test_store().await;

        // Create multiple running runs
        let run1 = store
            .create_encoding_run(100, Some("ollama"), Some(768))
            .await
            .unwrap();
        let run2 = store
            .create_encoding_run(200, Some("openai"), Some(1536))
            .await
            .unwrap();
        let run3 = store.create_encoding_run(50, None, None).await.unwrap();

        // Complete one so it shouldn't be affected
        store
            .complete_encoding_run(run3, "completed")
            .await
            .unwrap();

        // Mark stale runs as failed
        store.mark_stale_runs_as_failed().await.unwrap();

        // No active runs should remain
        let active = store.get_active_encoding_run().await.unwrap();
        assert!(active.is_none());

        // Verify run1 and run2 are failed, run3 is still completed
        store
            .run(move |conn| {
                let status1: String = conn.query_row(
                    "SELECT status FROM encoding_runs WHERE id = ?1",
                    params![run1],
                    |row| row.get(0),
                )?;
                assert_eq!(status1, "failed");

                let status2: String = conn.query_row(
                    "SELECT status FROM encoding_runs WHERE id = ?1",
                    params![run2],
                    |row| row.get(0),
                )?;
                assert_eq!(status2, "failed");

                let status3: String = conn.query_row(
                    "SELECT status FROM encoding_runs WHERE id = ?1",
                    params![run3],
                    |row| row.get(0),
                )?;
                assert_eq!(status3, "completed");

                // Verify finished_at is set on the failed runs
                let finished1: Option<String> = conn.query_row(
                    "SELECT finished_at FROM encoding_runs WHERE id = ?1",
                    params![run1],
                    |row| row.get(0),
                )?;
                assert!(finished1.is_some());

                let finished2: Option<String> = conn.query_row(
                    "SELECT finished_at FROM encoding_runs WHERE id = ?1",
                    params![run2],
                    |row| row.get(0),
                )?;
                assert!(finished2.is_some());

                Ok(())
            })
            .await
            .unwrap();
    }

    // ==================== mark_stale_runs_as_failed - no running runs ====================
    #[tokio::test]
    async fn test_mark_stale_runs_as_failed_none() {
        let store = setup_test_store().await;

        // No runs at all - should not error
        store.mark_stale_runs_as_failed().await.unwrap();

        // Create and complete a run, then call again - should not error
        let run_id = store.create_encoding_run(100, None, None).await.unwrap();
        store
            .complete_encoding_run(run_id, "completed")
            .await
            .unwrap();
        store.mark_stale_runs_as_failed().await.unwrap();
    }

    // ==================== Test Case #32: concurrent access - no locks ====================
    #[tokio::test]
    async fn test_concurrent_read_write_no_locks() {
        // Use shared in-memory database so concurrent connections share the same data.
        // Plain `:memory:` creates a separate database per connection in the pool.
        let counter = TEST_STORE_COUNTER.fetch_add(1, Ordering::SeqCst);
        let db_name = format!(
            "file:encprog_concurrent_{}?mode=memory&cache=shared",
            counter
        );
        let store = Arc::new(SqliteStore::connect(&db_name).await.unwrap());
        let run_id = store
            .create_encoding_run(1000, Some("ollama"), Some(768))
            .await
            .unwrap();

        // Spawn writer task: updates progress repeatedly
        let writer_store = store.clone();
        let writer = tokio::spawn(async move {
            for i in 1..=10 {
                writer_store
                    .update_encoding_run_progress(run_id, i * 100, Some(50.0))
                    .await
                    .unwrap();
            }
        });

        // Spawn reader task: queries active run repeatedly
        let reader_store = store.clone();
        let reader = tokio::spawn(async move {
            for _ in 0..10 {
                let result = reader_store.get_active_encoding_run().await;
                assert!(result.is_ok(), "Reader should not encounter lock errors");
                // The run should exist (still running)
                let run = result.unwrap();
                assert!(run.is_some(), "Active run should be found during reads");
            }
        });

        // Both tasks should complete without errors
        let (writer_result, reader_result) = tokio::join!(writer, reader);
        writer_result.unwrap();
        reader_result.unwrap();

        // Verify final state
        let run = store.get_active_encoding_run().await.unwrap().unwrap();
        assert_eq!(run.chunks_completed, 1000);
    }

    // ==================== Test Case #22: ETA with zero throughput returns None ====================
    #[test]
    fn test_calculate_eta_zero_throughput() {
        assert_eq!(calculate_eta(100, Some(0.0)), None);
        assert_eq!(calculate_eta(100, None), None);
        assert_eq!(calculate_eta(100, Some(-1.0)), None);
    }

    // ==================== Test Case #23: ETA with positive throughput calculates correctly ====================
    #[test]
    fn test_calculate_eta_positive_throughput() {
        // 100 remaining / 10 per sec = 10 seconds
        let eta = calculate_eta(100, Some(10.0)).unwrap();
        assert!((eta - 10.0).abs() < f64::EPSILON);

        // 500 remaining / 25.0 per sec = 20 seconds
        let eta = calculate_eta(500, Some(25.0)).unwrap();
        assert!((eta - 20.0).abs() < f64::EPSILON);

        // 0 remaining = 0 seconds
        let eta = calculate_eta(0, Some(10.0)).unwrap();
        assert!((eta - 0.0).abs() < f64::EPSILON);
    }

    // ==================== Test Case #24: ETA with very fast throughput (<1s) ====================
    #[test]
    fn test_calculate_eta_very_fast_throughput() {
        // 10 remaining / 1000 per sec = 0.01 seconds
        let eta = calculate_eta(10, Some(1000.0)).unwrap();
        assert!((eta - 0.01).abs() < 1e-10);

        // 1 remaining / 10000 per sec = 0.0001 seconds
        let eta = calculate_eta(1, Some(10000.0)).unwrap();
        assert!((eta - 0.0001).abs() < 1e-10);
    }

    // ==================== Test Case #25: ETA with very slow throughput (hours) ====================
    #[test]
    fn test_calculate_eta_very_slow_throughput() {
        // 10000 remaining / 0.5 per sec = 20000 seconds (~5.5 hours)
        let eta = calculate_eta(10000, Some(0.5)).unwrap();
        assert!((eta - 20000.0).abs() < f64::EPSILON);

        // 1000000 remaining / 0.1 per sec = 10000000 seconds (~115 days)
        let eta = calculate_eta(1000000, Some(0.1)).unwrap();
        assert!((eta - 10000000.0).abs() < 1e-6);
    }

    // ==================== Elapsed time calculation tests ====================
    #[test]
    fn test_calculate_elapsed_seconds_sqlite_format() {
        // Use a timestamp very close to now to get a small positive result
        let now = Utc::now();
        let ts = now.format("%Y-%m-%d %H:%M:%S").to_string();
        let elapsed = calculate_elapsed_seconds(&ts).unwrap();
        // Should be very close to 0 (within 1 second)
        assert!(elapsed >= 0.0 && elapsed < 2.0, "elapsed was {}", elapsed);
    }

    #[test]
    fn test_calculate_elapsed_seconds_iso8601_format() {
        let now = Utc::now();
        let ts = now.format("%Y-%m-%dT%H:%M:%S").to_string();
        let elapsed = calculate_elapsed_seconds(&ts).unwrap();
        assert!(elapsed >= 0.0 && elapsed < 2.0, "elapsed was {}", elapsed);
    }

    #[test]
    fn test_calculate_elapsed_seconds_known_past() {
        // A timestamp 60 seconds in the past
        let past = Utc::now() - chrono::Duration::seconds(60);
        let ts = past.format("%Y-%m-%d %H:%M:%S").to_string();
        let elapsed = calculate_elapsed_seconds(&ts).unwrap();
        // Should be approximately 60 seconds (within 2 seconds tolerance)
        assert!(
            (elapsed - 60.0).abs() < 2.0,
            "elapsed was {}, expected ~60",
            elapsed
        );
    }

    #[test]
    fn test_calculate_elapsed_seconds_invalid_format() {
        let result = calculate_elapsed_seconds("not-a-timestamp");
        assert!(result.is_err());
    }

    // ==================== Staleness detection tests ====================
    #[test]
    fn test_is_stale_recent_timestamp() {
        let now = Utc::now();
        let ts = now.format("%Y-%m-%d %H:%M:%S").to_string();
        assert!(!is_stale(&ts), "Recent timestamp should not be stale");
    }

    #[test]
    fn test_is_stale_old_timestamp() {
        // 2 hours ago
        let old = Utc::now() - chrono::Duration::hours(2);
        let ts = old.format("%Y-%m-%d %H:%M:%S").to_string();
        assert!(is_stale(&ts), "2-hour old timestamp should be stale");
    }

    #[test]
    fn test_is_stale_just_under_threshold() {
        // 59 minutes ago - should not be stale
        let recent = Utc::now() - chrono::Duration::minutes(59);
        let ts = recent.format("%Y-%m-%d %H:%M:%S").to_string();
        assert!(
            !is_stale(&ts),
            "59-minute old timestamp should not be stale"
        );
    }

    #[test]
    fn test_is_stale_just_over_threshold() {
        // 61 minutes ago - should be stale
        let old = Utc::now() - chrono::Duration::minutes(61);
        let ts = old.format("%Y-%m-%d %H:%M:%S").to_string();
        assert!(is_stale(&ts), "61-minute old timestamp should be stale");
    }

    #[test]
    fn test_is_stale_invalid_timestamp() {
        assert!(
            is_stale("invalid"),
            "Invalid timestamp should be treated as stale"
        );
    }

    // ==================== Staleness in get_encoding_progress ====================
    #[tokio::test]
    async fn test_encoding_progress_stale_run_hidden() {
        let store = setup_test_store().await;
        setup_test_data(&store, "test-repo", 100).await;
        let run_id = store
            .create_encoding_run(100, Some("ollama"), Some(768))
            .await
            .unwrap();

        // Manually set last_batch_at to 2 hours ago to simulate staleness
        let two_hours_ago = (Utc::now() - chrono::Duration::hours(2))
            .format("%Y-%m-%d %H:%M:%S")
            .to_string();
        let ts = two_hours_ago.clone();
        store
            .run(move |conn| {
                conn.execute(
                    "UPDATE encoding_runs SET last_batch_at = ?1 WHERE id = ?2",
                    params![ts, run_id],
                )?;
                Ok(())
            })
            .await
            .unwrap();

        let progress = get_encoding_progress(store, None).await.unwrap();
        // Stale run should not appear as active
        assert!(
            progress.active_run.is_none(),
            "Stale run (>1 hour old) should not be shown as active"
        );
    }

    #[tokio::test]
    async fn test_encoding_progress_fresh_run_shown() {
        let store = setup_test_store().await;
        setup_test_data(&store, "test-repo", 100).await;
        let run_id = store
            .create_encoding_run(100, Some("ollama"), Some(768))
            .await
            .unwrap();

        // Update progress so last_batch_at is set to now
        store
            .update_encoding_run_progress(run_id, 50, Some(10.0))
            .await
            .unwrap();

        let progress = get_encoding_progress(store, None).await.unwrap();
        assert!(
            progress.active_run.is_some(),
            "Fresh run should be shown as active"
        );
    }

    // ==================== format_text - active run with elapsed and new format ====================
    #[test]
    fn test_format_text_active_run_full_format() {
        let response = EncodingProgressResponse {
            total_chunks: 2226,
            total_embeddings: 1226,
            percentage: 55.1,
            chunks_remaining: 1000,
            repo_filter: None,
            active_run: Some(ActiveRunInfo {
                run_id: 1,
                started_at: "2026-02-05 14:30:00".to_string(),
                total_chunks: 2226,
                chunks_completed: 1226,
                chunks_per_second: Some(22.3),
                provider: Some("ollama".to_string()),
                dimension: Some(1024),
                estimated_seconds_remaining: Some(44.8),
                elapsed_seconds: Some(135.0),
            }),
        };

        let output = format_text(&response);
        assert!(output.contains("Active Run:"));
        assert!(output.contains("Provider:        ollama (1024 dimensions)"));
        assert!(output.contains("Started:         2026-02-05 14:30:00"));
        assert!(output.contains("Elapsed:         ~2m 15s"));
        assert!(output.contains("Batch progress:  1,226 / 2,226 chunks"));
        assert!(output.contains("Throughput:      22.3 chunks/s"));
        assert!(output.contains("ETA:             ~45s remaining"));
    }

    // ==================== format_text - provider without dimension ====================
    #[test]
    fn test_format_text_provider_without_dimension() {
        let response = EncodingProgressResponse {
            total_chunks: 100,
            total_embeddings: 50,
            percentage: 50.0,
            chunks_remaining: 50,
            repo_filter: None,
            active_run: Some(ActiveRunInfo {
                run_id: 1,
                started_at: "2026-01-01 00:00:00".to_string(),
                total_chunks: 100,
                chunks_completed: 50,
                chunks_per_second: None,
                provider: Some("openai".to_string()),
                dimension: None,
                estimated_seconds_remaining: None,
                elapsed_seconds: None,
            }),
        };

        let output = format_text(&response);
        assert!(output.contains("Provider:        openai"));
        assert!(!output.contains("dimensions"));
        // No throughput or ETA when chunks_per_second is None
        assert!(!output.contains("Throughput:"));
        assert!(!output.contains("ETA:"));
    }

    // ==================== format_json - includes elapsed_seconds ====================
    #[test]
    fn test_format_json_includes_elapsed_seconds() {
        let response = EncodingProgressResponse {
            total_chunks: 100,
            total_embeddings: 50,
            percentage: 50.0,
            chunks_remaining: 50,
            repo_filter: None,
            active_run: Some(ActiveRunInfo {
                run_id: 1,
                started_at: "2026-01-01 00:00:00".to_string(),
                total_chunks: 100,
                chunks_completed: 50,
                chunks_per_second: Some(10.0),
                provider: Some("ollama".to_string()),
                dimension: Some(768),
                estimated_seconds_remaining: Some(5.0),
                elapsed_seconds: Some(120.5),
            }),
        };

        let json_str = format_json(&response).unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&json_str).unwrap();
        assert_eq!(parsed["active_run"]["elapsed_seconds"], 120.5);
        assert_eq!(parsed["active_run"]["estimated_seconds_remaining"], 5.0);
    }

    // ==================== format_duration edge cases for ETA display ====================
    #[test]
    fn test_format_duration_sub_second() {
        // Very fast ETA rounds to 0
        assert_eq!(format_duration(0.01), "~0s");
        assert_eq!(format_duration(0.4), "~0s");
        assert_eq!(format_duration(0.5), "~1s");
    }

    #[test]
    fn test_format_duration_very_long() {
        // 10 hours
        assert_eq!(format_duration(36000.0), "~10h");
        // 25 hours 30 minutes
        assert_eq!(format_duration(91800.0), "~25h 30m");
    }
}

/// Integration tests for end-to-end encoding progress functionality.
///
/// These tests verify the full integration between the embedding pipeline,
/// encoding progress tracking, and progress querying. They complement the
/// unit tests in this module and the pipeline tests in `embedding/pipeline.rs`.
///
/// Tests implemented:
/// - End-to-end progress flow (pipeline writes, progress query reads)
/// - Concurrent pipeline + progress query (test case #32)
/// - Provider/dimension mismatch scenario (test case #33)
#[cfg(test)]
mod integration_tests {
    use super::*;
    use crate::db::sqlite::SqliteStore;
    use crate::db::traits::StoreChunks;
    use crate::db::{ChunkRecord, FileRecord};
    use crate::embedding::cache::EmbeddingCache;
    use crate::embedding::config::CacheConfig;
    use crate::embedding::error::EmbeddingError;
    use crate::embedding::pipeline::{EmbeddingPipeline, PipelineConfig};
    use crate::embedding::provider::{EmbeddingProvider, ProviderMetrics};
    use crate::embedding::service::EmbeddingService;
    use async_trait::async_trait;
    use rusqlite::params;
    use std::sync::atomic::{AtomicUsize, Ordering};
    use std::sync::Arc;

    /// Counter for unique shared in-memory database names.
    static INTEGRATION_STORE_COUNTER: AtomicUsize = AtomicUsize::new(1000);

    /// Mock provider with controllable delay for concurrent testing.
    struct SlowMockProvider {
        delay_ms: u64,
        dimension: usize,
        name: &'static str,
    }

    #[async_trait]
    impl EmbeddingProvider for SlowMockProvider {
        async fn embed(&self, _text: String) -> Result<Vec<f32>, EmbeddingError> {
            if self.delay_ms > 0 {
                tokio::time::sleep(std::time::Duration::from_millis(self.delay_ms)).await;
            }
            Ok(vec![0.1; self.dimension])
        }

        async fn embed_batch(&self, texts: Vec<String>) -> Result<Vec<Vec<f32>>, EmbeddingError> {
            if self.delay_ms > 0 {
                tokio::time::sleep(std::time::Duration::from_millis(self.delay_ms)).await;
            }
            Ok(vec![vec![0.1; self.dimension]; texts.len()])
        }

        fn dimension(&self) -> usize {
            self.dimension
        }

        fn provider_name(&self) -> &'static str {
            self.name
        }

        fn metrics(&self) -> Option<ProviderMetrics> {
            Some(ProviderMetrics {
                total_requests: 1,
                total_tokens: 100,
                failed_requests: 0,
                estimated_cost_usd: 0.0001,
            })
        }
    }

    /// Fast mock provider (no delay).
    struct FastMockProvider {
        dimension: usize,
        name: &'static str,
    }

    #[async_trait]
    impl EmbeddingProvider for FastMockProvider {
        async fn embed(&self, _text: String) -> Result<Vec<f32>, EmbeddingError> {
            Ok(vec![0.1; self.dimension])
        }

        async fn embed_batch(&self, texts: Vec<String>) -> Result<Vec<Vec<f32>>, EmbeddingError> {
            Ok(vec![vec![0.1; self.dimension]; texts.len()])
        }

        fn dimension(&self) -> usize {
            self.dimension
        }

        fn provider_name(&self) -> &'static str {
            self.name
        }

        fn metrics(&self) -> Option<ProviderMetrics> {
            Some(ProviderMetrics {
                total_requests: 1,
                total_tokens: 100,
                failed_requests: 0,
                estimated_cost_usd: 0.0001,
            })
        }
    }

    fn create_service_with_provider(provider: Box<dyn EmbeddingProvider>) -> EmbeddingService {
        let cache_config = CacheConfig {
            max_entries: 1000,
            ttl_seconds: 3600,
            enable_metrics: true,
        };
        let cache = EmbeddingCache::new(cache_config).unwrap();
        EmbeddingService::new(provider, Arc::new(cache))
    }

    fn create_slow_service(
        delay_ms: u64,
        dimension: usize,
        name: &'static str,
    ) -> EmbeddingService {
        let provider = Box::new(SlowMockProvider {
            delay_ms,
            dimension,
            name,
        });
        create_service_with_provider(provider)
    }

    fn create_fast_service(dimension: usize, name: &'static str) -> EmbeddingService {
        let provider = Box::new(FastMockProvider { dimension, name });
        create_service_with_provider(provider)
    }

    /// Helper to create an in-memory test store.
    async fn setup_test_store() -> SqliteStore {
        SqliteStore::connect(":memory:").await.unwrap()
    }

    /// Helper to create a shared in-memory test store (same DB across connections).
    async fn setup_shared_test_store() -> Arc<SqliteStore> {
        let counter = INTEGRATION_STORE_COUNTER.fetch_add(1, Ordering::SeqCst);
        let db_name = format!(
            "file:encprog_integration_{}?mode=memory&cache=shared",
            counter
        );
        Arc::new(SqliteStore::connect(&db_name).await.unwrap())
    }

    /// Helper to create test data: repo, worktree, commit, file, and N chunks.
    async fn setup_test_chunks(store: &SqliteStore, repo_name: &str, num_chunks: usize) {
        let repo_id = store
            .get_or_create_repo(repo_name, "/test/path")
            .await
            .unwrap();
        let worktree_id = store
            .get_or_create_worktree(repo_id, "main", "/test/path")
            .await
            .unwrap();
        let commit_id = store
            .get_or_create_commit(repo_id, "abc123", None)
            .await
            .unwrap();

        let file = FileRecord {
            repo_id,
            worktree_id,
            commit_id,
            relpath: "test.rs".to_string(),
            language: Some("rust".to_string()),
            content_hash: format!("hash_{}", repo_name),
            size_bytes: 100,
            last_modified: None,
        };
        let file_id = store.upsert_file(&file).await.unwrap();

        for i in 0..num_chunks {
            let chunk = ChunkRecord {
                file_id,
                worktree_id,
                blob_sha: format!("blob_{}_{}", repo_name, i),
                symbol_name: Some(format!("fn_{}", i)),
                kind: "function".to_string(),
                signature: Some(format!("fn fn_{}()", i)),
                docstring: Some(format!("Test function {}", i)),
                start_line: (i * 10 + 1) as i32,
                end_line: (i * 10 + 10) as i32,
                preview: format!("fn fn_{}() {{}}", i),
                ts_doc_text: String::new(),
                recency_score: 1.0,
                churn_score: 0.5,
                metadata: None,
            };
            store.insert_chunk(&chunk).await.unwrap();
        }
    }

    /// Helper to insert pre-existing embeddings for specific blob_shas.
    async fn insert_embeddings_with_params(
        store: &SqliteStore,
        blob_shas: Vec<String>,
        dimension: i32,
        model_version: &str,
    ) {
        let embedding_bytes = vec![0u8; (dimension as usize) * 4];
        for blob_sha in blob_shas {
            let emb = embedding_bytes.clone();
            let mv = model_version.to_string();
            store
                .run(move |conn| {
                    conn.execute(
                        "INSERT OR IGNORE INTO code_embeddings (blob_sha, embedding, embedding_dim, model_version)
                         VALUES (?1, ?2, ?3, ?4)",
                        params![blob_sha, emb, dimension, mv],
                    )?;
                    Ok(())
                })
                .await
                .unwrap();
        }
    }

    // ========================================================================
    // Test 1: End-to-end progress flow
    //
    // Pipeline writes progress, progress command reads it correctly.
    // Verifies: run creation, progress updates, completion, ETA calculation.
    // ========================================================================
    #[tokio::test]
    async fn test_end_to_end_progress_flow() {
        let store = setup_test_store().await;
        let store_arc = Arc::new(store);

        // Create 10 test chunks
        setup_test_chunks(&store_arc, "test-repo", 10).await;

        // Verify initial state: no progress, no active run
        let initial = get_encoding_progress(store_arc.clone(), None)
            .await
            .unwrap();
        assert_eq!(initial.total_chunks, 10);
        assert_eq!(initial.total_embeddings, 0);
        assert_eq!(initial.percentage, 0.0);
        assert_eq!(initial.chunks_remaining, 10);
        assert!(initial.active_run.is_none());

        // Run pipeline with small batch size (2) to get multiple batches
        let service = create_fast_service(1536, "openai");
        let config = PipelineConfig {
            batch_size: 2,
            incremental: true,
            dry_run: false,
            sample_size: None,
            batch_delay_ms: 0,
            max_cost_usd: None,
        };
        let pipeline = EmbeddingPipeline::new(service, config);
        let stats = pipeline.run(&store_arc).await.unwrap();

        assert_eq!(stats.total_chunks, 10);
        assert_eq!(stats.provider, "openai");
        assert_eq!(stats.dimension, 1536);

        // After pipeline completes: verify progress shows 100%
        let final_progress = get_encoding_progress(store_arc.clone(), None)
            .await
            .unwrap();
        assert_eq!(final_progress.total_chunks, 10);
        assert_eq!(final_progress.total_embeddings, 10);
        assert!((final_progress.percentage - 100.0).abs() < f64::EPSILON);
        assert_eq!(final_progress.chunks_remaining, 0);

        // Active run should be gone (completed)
        assert!(
            final_progress.active_run.is_none(),
            "Run should be completed, not active"
        );

        // Verify the run is in the database with correct final state
        store_arc
            .run(move |conn| {
                let (status, total_chunks, chunks_completed, provider, dimension, finished_at): (
                    String,
                    i64,
                    i64,
                    Option<String>,
                    Option<i32>,
                    Option<String>,
                ) = conn.query_row(
                    "SELECT status, total_chunks, chunks_completed, provider, dimension, finished_at
                     FROM encoding_runs ORDER BY id DESC LIMIT 1",
                    [],
                    |row| {
                        Ok((
                            row.get(0)?,
                            row.get(1)?,
                            row.get(2)?,
                            row.get(3)?,
                            row.get(4)?,
                            row.get(5)?,
                        ))
                    },
                )?;

                assert_eq!(status, "completed");
                assert_eq!(total_chunks, 10);
                assert_eq!(chunks_completed, 10);
                assert_eq!(provider, Some("openai".to_string()));
                assert_eq!(dimension, Some(1536));
                assert!(finished_at.is_some());

                // Verify chunks_per_second was recorded
                let cps: Option<f64> = conn.query_row(
                    "SELECT chunks_per_second FROM encoding_runs ORDER BY id DESC LIMIT 1",
                    [],
                    |row| row.get(0),
                )?;
                assert!(cps.is_some(), "chunks_per_second should be set");
                assert!(cps.unwrap() > 0.0, "chunks_per_second should be positive");

                Ok(())
            })
            .await
            .unwrap();
    }

    // ========================================================================
    // Test 2: Concurrent pipeline + progress query (test case #32)
    //
    // Start pipeline with slow mock provider, spawn concurrent task querying
    // progress repeatedly. Verify no lock errors and valid data throughout.
    //
    // Note: The pipeline runs on the current task while progress queries are
    // spawned in a concurrent task. This avoids Send issues with the pipeline's
    // internal callback types while still exercising true concurrent DB access.
    // ========================================================================
    #[tokio::test]
    async fn test_concurrent_pipeline_and_progress_query() {
        let store = setup_shared_test_store().await;

        // Create 10 test chunks
        setup_test_chunks(&store, "test-repo", 10).await;

        // Create pipeline with slow provider (50ms delay per batch)
        let service = create_slow_service(50, 1536, "ollama");
        let config = PipelineConfig {
            batch_size: 2,
            incremental: true,
            dry_run: false,
            sample_size: None,
            batch_delay_ms: 0,
            max_cost_usd: None,
        };
        let pipeline = EmbeddingPipeline::new(service, config);

        // Clone store for the progress query task
        let query_store = store.clone();

        // Spawn concurrent progress query task
        let query_handle = tokio::spawn(async move {
            let mut query_count = 0;
            let mut saw_active_run = false;
            let mut last_percentage = -1.0f64;
            let mut progress_increased = false;

            // Query progress repeatedly while pipeline runs
            for _ in 0..50 {
                let result = get_encoding_progress(query_store.clone(), None).await;
                assert!(
                    result.is_ok(),
                    "Progress query should not fail during concurrent access: {:?}",
                    result.err()
                );

                let progress = result.unwrap();
                query_count += 1;

                // Verify data is valid (no corruption)
                assert!(progress.total_chunks >= 0);
                assert!(progress.total_embeddings >= 0);
                assert!(progress.total_embeddings <= progress.total_chunks);
                assert!(progress.percentage >= 0.0);
                assert!(progress.percentage <= 100.0);
                assert!(progress.chunks_remaining >= 0);

                // Track if we ever see an active run
                if let Some(run) = &progress.active_run {
                    saw_active_run = true;
                    assert!(run.chunks_completed >= 0);
                    assert!(run.chunks_completed <= run.total_chunks);
                    if let Some(cps) = run.chunks_per_second {
                        assert!(cps >= 0.0, "chunks_per_second must be non-negative");
                    }
                }

                // Track if progress ever increases
                if progress.percentage > last_percentage {
                    progress_increased = true;
                }
                last_percentage = progress.percentage;

                tokio::time::sleep(std::time::Duration::from_millis(10)).await;
            }

            (query_count, saw_active_run, progress_increased)
        });

        // Run pipeline on the current task (concurrently with the query task)
        let pipeline_result = pipeline.run(&store).await;

        // Wait for query task to finish
        let query_result = query_handle.await;

        // Pipeline should complete successfully
        let stats = pipeline_result.unwrap();
        assert_eq!(stats.total_chunks, 10);

        // Query task should complete without errors
        let (query_count, _saw_active_run, _progress_increased) = query_result.unwrap();
        assert!(
            query_count > 0,
            "Should have queried progress at least once"
        );
        // Note: saw_active_run and progress_increased may be false if the pipeline
        // completes very quickly before the query task starts. This is acceptable
        // since the main goal is verifying no lock errors or data corruption.

        // Final state should be correct
        let final_progress = get_encoding_progress(store.clone(), None).await.unwrap();
        assert_eq!(final_progress.total_chunks, 10);
        assert_eq!(final_progress.total_embeddings, 10);
        assert!((final_progress.percentage - 100.0).abs() < f64::EPSILON);
    }

    // ========================================================================
    // Test 3: Provider/dimension mismatch scenario (test case #33)
    //
    // Create initial embeddings with provider "ollama" dimension 1024,
    // add new chunks, run pipeline with "openai" dimension 1536.
    // Verify old embeddings remain and new run shows new provider.
    // ========================================================================
    #[tokio::test]
    async fn test_provider_dimension_mismatch() {
        let store = setup_test_store().await;
        let store_arc = Arc::new(store);

        // Step 1: Create initial 5 chunks and embed them with "ollama" / 1024
        setup_test_chunks(&store_arc, "test-repo", 5).await;

        let service1 = create_fast_service(1024, "ollama");
        let config1 = PipelineConfig {
            batch_size: 10,
            incremental: true,
            dry_run: false,
            sample_size: None,
            batch_delay_ms: 0,
            max_cost_usd: None,
        };
        let pipeline1 = EmbeddingPipeline::new(service1, config1);
        let stats1 = pipeline1.run(&store_arc).await.unwrap();
        assert_eq!(stats1.total_chunks, 5);
        assert_eq!(stats1.provider, "ollama");
        assert_eq!(stats1.dimension, 1024);

        // Verify: 5 chunks, 5 embeddings, 100%
        let progress_after_first = get_encoding_progress(store_arc.clone(), None)
            .await
            .unwrap();
        assert_eq!(progress_after_first.total_chunks, 5);
        assert_eq!(progress_after_first.total_embeddings, 5);
        assert!((progress_after_first.percentage - 100.0).abs() < f64::EPSILON);

        // Verify first run is completed
        let first_run_status: String = store_arc
            .run(|conn| {
                let status: String = conn.query_row(
                    "SELECT status FROM encoding_runs ORDER BY id ASC LIMIT 1",
                    [],
                    |row| row.get(0),
                )?;
                Ok(status)
            })
            .await
            .unwrap();
        assert_eq!(first_run_status, "completed");

        // Step 2: Add 3 new chunks that don't have embeddings yet
        // We need to create new chunks with different blob_shas
        let repo_id = store_arc
            .run(|conn| {
                let id: i64 = conn.query_row(
                    "SELECT id FROM repos WHERE name = ?1",
                    params!["test-repo"],
                    |row| row.get(0),
                )?;
                Ok(id)
            })
            .await
            .unwrap();

        let worktree_id = store_arc
            .run(move |conn| {
                let id: i64 = conn.query_row(
                    "SELECT id FROM worktrees WHERE repo_id = ?1",
                    params![repo_id],
                    |row| row.get(0),
                )?;
                Ok(id)
            })
            .await
            .unwrap();

        let commit_id = store_arc
            .run(move |conn| {
                let id: i64 = conn.query_row(
                    "SELECT id FROM commits WHERE repo_id = ?1",
                    params![repo_id],
                    |row| row.get(0),
                )?;
                Ok(id)
            })
            .await
            .unwrap();

        let file = FileRecord {
            repo_id,
            worktree_id,
            commit_id,
            relpath: "new_file.rs".to_string(),
            language: Some("rust".to_string()),
            content_hash: "hash_new_file".to_string(),
            size_bytes: 200,
            last_modified: None,
        };
        let new_file_id = store_arc.upsert_file(&file).await.unwrap();

        for i in 0..3 {
            let chunk = ChunkRecord {
                file_id: new_file_id,
                worktree_id,
                blob_sha: format!("blob_new_{}", i),
                symbol_name: Some(format!("fn_new_{}", i)),
                kind: "function".to_string(),
                signature: Some(format!("fn fn_new_{}()", i)),
                docstring: Some(format!("New function {}", i)),
                start_line: i * 10 + 1,
                end_line: i * 10 + 10,
                preview: format!("fn fn_new_{}() {{}}", i),
                ts_doc_text: String::new(),
                recency_score: 1.0,
                churn_score: 0.5,
                metadata: None,
            };
            store_arc.insert_chunk(&chunk).await.unwrap();
        }

        // Verify: 8 total chunks, 5 embeddings (the old ones)
        let progress_before_second = get_encoding_progress(store_arc.clone(), None)
            .await
            .unwrap();
        assert_eq!(progress_before_second.total_chunks, 8);
        assert_eq!(progress_before_second.total_embeddings, 5);
        assert_eq!(progress_before_second.chunks_remaining, 3);

        // Step 3: Run pipeline with "openai" / 1536 (different provider & dimension)
        let service2 = create_fast_service(1536, "openai");
        let config2 = PipelineConfig {
            batch_size: 10,
            incremental: true,
            dry_run: false,
            sample_size: None,
            batch_delay_ms: 0,
            max_cost_usd: None,
        };
        let pipeline2 = EmbeddingPipeline::new(service2, config2);
        let stats2 = pipeline2.run(&store_arc).await.unwrap();

        // Only the 3 new chunks should be processed (incremental mode)
        assert_eq!(stats2.total_chunks, 3);
        assert_eq!(stats2.provider, "openai");
        assert_eq!(stats2.dimension, 1536);

        // Step 4: Verify final state
        let final_progress = get_encoding_progress(store_arc.clone(), None)
            .await
            .unwrap();
        assert_eq!(final_progress.total_chunks, 8);
        assert_eq!(final_progress.total_embeddings, 8);
        assert!((final_progress.percentage - 100.0).abs() < f64::EPSILON);
        assert_eq!(final_progress.chunks_remaining, 0);

        // Verify: old embeddings remain in the database
        let old_embedding_count: i64 = store_arc
            .run(|conn| {
                let count: i64 = conn.query_row(
                    "SELECT COUNT(*) FROM code_embeddings WHERE blob_sha LIKE 'blob_test-repo_%'",
                    [],
                    |row| row.get(0),
                )?;
                Ok(count)
            })
            .await
            .unwrap();
        assert_eq!(
            old_embedding_count, 5,
            "Old embeddings should remain in the database"
        );

        // Verify: new embeddings were created
        let new_embedding_count: i64 = store_arc
            .run(|conn| {
                let count: i64 = conn.query_row(
                    "SELECT COUNT(*) FROM code_embeddings WHERE blob_sha LIKE 'blob_new_%'",
                    [],
                    |row| row.get(0),
                )?;
                Ok(count)
            })
            .await
            .unwrap();
        assert_eq!(new_embedding_count, 3, "New embeddings should be created");

        // Verify: the second encoding run recorded the new provider and dimension
        let (provider2, dimension2): (Option<String>, Option<i32>) = store_arc
            .run(|conn| {
                let row: (Option<String>, Option<i32>) = conn.query_row(
                    "SELECT provider, dimension FROM encoding_runs ORDER BY id DESC LIMIT 1",
                    [],
                    |row| Ok((row.get(0)?, row.get(1)?)),
                )?;
                Ok(row)
            })
            .await
            .unwrap();
        assert_eq!(provider2, Some("openai".to_string()));
        assert_eq!(dimension2, Some(1536));

        // Verify: we have exactly 2 encoding runs (one per pipeline invocation)
        let run_count: i64 = store_arc
            .run(|conn| {
                let count: i64 =
                    conn.query_row("SELECT COUNT(*) FROM encoding_runs", [], |row| row.get(0))?;
                Ok(count)
            })
            .await
            .unwrap();
        assert_eq!(run_count, 2, "Should have two completed encoding runs");
    }

    // ========================================================================
    // Test 4: Progress percentage increases and ETA decreases during encoding
    //
    // Uses a slow mock provider and progress callback to capture intermediate
    // progress snapshots, then verifies monotonic progress increase.
    // ========================================================================
    #[tokio::test]
    async fn test_progress_increases_and_eta_decreases() {
        let store = setup_shared_test_store().await;

        // Create 10 test chunks
        setup_test_chunks(&store, "test-repo", 10).await;

        // Use slow provider so we can observe progress changes
        let service = create_slow_service(20, 1536, "ollama");
        let config = PipelineConfig {
            batch_size: 2,
            incremental: true,
            dry_run: false,
            sample_size: None,
            batch_delay_ms: 0,
            max_cost_usd: None,
        };
        let pipeline = EmbeddingPipeline::new(service, config);

        // Use a progress callback to capture snapshots
        let snapshots = Arc::new(std::sync::Mutex::new(Vec::<(usize, usize)>::new()));
        let snapshots_clone = snapshots.clone();

        let callback = move |completed: usize, total: usize| {
            snapshots_clone.lock().unwrap().push((completed, total));
        };

        let stats = pipeline
            .run_with_progress(&store, Some(&callback))
            .await
            .unwrap();
        assert_eq!(stats.total_chunks, 10);

        // Verify progress snapshots are monotonically increasing
        let captured = snapshots.lock().unwrap().clone();
        assert!(
            !captured.is_empty(),
            "Should have captured at least one progress snapshot"
        );

        let mut prev_completed = 0;
        for (completed, total) in &captured {
            assert_eq!(*total, 10, "Total should always be 10");
            assert!(
                *completed >= prev_completed,
                "Progress should never decrease: {} < {}",
                completed,
                prev_completed
            );
            assert!(*completed <= *total, "Completed should not exceed total");
            prev_completed = *completed;
        }

        // Final snapshot should have all chunks completed
        let (final_completed, _) = captured.last().unwrap();
        assert_eq!(
            *final_completed, 10,
            "Final progress should show all chunks completed"
        );

        // Verify encoding run was marked completed with valid throughput
        store
            .run(move |conn| {
                let (status, cps): (String, Option<f64>) = conn.query_row(
                    "SELECT status, chunks_per_second FROM encoding_runs ORDER BY id DESC LIMIT 1",
                    [],
                    |row| Ok((row.get(0)?, row.get(1)?)),
                )?;
                assert_eq!(status, "completed");
                assert!(cps.is_some());
                assert!(cps.unwrap() > 0.0, "Throughput should be positive");
                Ok(())
            })
            .await
            .unwrap();
    }

    // ========================================================================
    // Test 5: Stale run cleanup during pipeline restart (thorough variant)
    //
    // This extends the ENCPROG.2002 test by verifying that:
    // - Multiple stale runs from different providers are cleaned up
    // - A new run is created successfully after cleanup
    // - The new run tracks the correct provider/dimension
    // ========================================================================
    #[tokio::test]
    async fn test_stale_run_cleanup_multi_provider() {
        let store = setup_test_store().await;

        // Create multiple stale runs with different providers
        let stale1 = store
            .create_encoding_run(500, Some("ollama"), Some(768))
            .await
            .unwrap();
        let stale2 = store
            .create_encoding_run(300, Some("openai"), Some(1536))
            .await
            .unwrap();

        // Verify both are active
        let active = store.get_active_encoding_run().await.unwrap();
        assert!(active.is_some(), "Should have an active run");

        // Add test chunks so the pipeline has work
        setup_test_chunks(&store, "test-repo", 3).await;

        // Run a new pipeline - should clean up stale runs first
        let service = create_fast_service(1024, "google");
        let config = PipelineConfig {
            batch_size: 10,
            incremental: true,
            dry_run: false,
            sample_size: None,
            batch_delay_ms: 0,
            max_cost_usd: None,
        };
        let pipeline = EmbeddingPipeline::new(service, config);
        let stats = pipeline.run(&store).await.unwrap();
        assert_eq!(stats.total_chunks, 3);
        assert_eq!(stats.provider, "google");

        // Verify: both stale runs are marked as failed
        store
            .run(move |conn| {
                let status1: String = conn.query_row(
                    "SELECT status FROM encoding_runs WHERE id = ?1",
                    params![stale1],
                    |row| row.get(0),
                )?;
                assert_eq!(status1, "failed", "First stale run should be marked failed");

                let status2: String = conn.query_row(
                    "SELECT status FROM encoding_runs WHERE id = ?1",
                    params![stale2],
                    |row| row.get(0),
                )?;
                assert_eq!(status2, "failed", "Second stale run should be marked failed");

                // The new run (third) should be completed
                let (status3, provider3, dimension3): (String, Option<String>, Option<i32>) =
                    conn.query_row(
                        "SELECT status, provider, dimension FROM encoding_runs ORDER BY id DESC LIMIT 1",
                        [],
                        |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),
                    )?;
                assert_eq!(status3, "completed");
                assert_eq!(provider3, Some("google".to_string()));
                assert_eq!(dimension3, Some(1024));

                // Total runs should be 3
                let count: i64 = conn.query_row(
                    "SELECT COUNT(*) FROM encoding_runs",
                    [],
                    |row| row.get(0),
                )?;
                assert_eq!(count, 3);

                Ok(())
            })
            .await
            .unwrap();
    }

    // ========================================================================
    // Test 6: Error does not prevent future runs
    //
    // This extends ENCPROG.2002's error test by verifying that after a failed
    // run, a subsequent run with a working provider succeeds.
    // ========================================================================
    #[tokio::test]
    async fn test_error_does_not_prevent_future_runs() {
        let store = setup_test_store().await;
        setup_test_chunks(&store, "test-repo", 3).await;

        // First run: use a failing provider
        let failing_provider = Box::new(FailingMockProvider {
            dimension: 1536,
            name: "failing",
        });
        let service1 = create_service_with_provider(failing_provider);
        let config1 = PipelineConfig {
            batch_size: 2,
            incremental: true,
            dry_run: false,
            sample_size: None,
            batch_delay_ms: 0,
            max_cost_usd: None,
        };
        let pipeline1 = EmbeddingPipeline::new(service1, config1);
        let result1 = pipeline1.run(&store).await;
        assert!(result1.is_err(), "First run should fail");

        // Verify the failed run is in the database
        let failed_run_count: i64 = store
            .run(|conn| {
                let count: i64 = conn.query_row(
                    "SELECT COUNT(*) FROM encoding_runs WHERE status = 'failed'",
                    [],
                    |row| row.get(0),
                )?;
                Ok(count)
            })
            .await
            .unwrap();
        assert_eq!(failed_run_count, 1);

        // Second run: use a working provider
        let service2 = create_fast_service(1536, "openai");
        let config2 = PipelineConfig {
            batch_size: 10,
            incremental: true,
            dry_run: false,
            sample_size: None,
            batch_delay_ms: 0,
            max_cost_usd: None,
        };
        let pipeline2 = EmbeddingPipeline::new(service2, config2);
        let stats2 = pipeline2.run(&store).await.unwrap();

        // Second run should succeed and process all chunks
        assert_eq!(stats2.total_chunks, 3);

        // Verify final state
        let final_progress = get_encoding_progress(Arc::new(store), None).await.unwrap();
        assert_eq!(final_progress.total_chunks, 3);
        assert_eq!(final_progress.total_embeddings, 3);
        assert!((final_progress.percentage - 100.0).abs() < f64::EPSILON);
    }

    /// Mock provider that always fails (for error handling tests).
    struct FailingMockProvider {
        dimension: usize,
        name: &'static str,
    }

    #[async_trait]
    impl EmbeddingProvider for FailingMockProvider {
        async fn embed(&self, _text: String) -> Result<Vec<f32>, EmbeddingError> {
            Err(EmbeddingError::Other(
                "simulated embedding failure".to_string(),
            ))
        }

        async fn embed_batch(&self, _texts: Vec<String>) -> Result<Vec<Vec<f32>>, EmbeddingError> {
            Err(EmbeddingError::Other(
                "simulated batch embedding failure".to_string(),
            ))
        }

        fn dimension(&self) -> usize {
            self.dimension
        }

        fn provider_name(&self) -> &'static str {
            self.name
        }

        fn metrics(&self) -> Option<ProviderMetrics> {
            None
        }
    }

    // ========================================================================
    // Test 7: Pre-existing embeddings counted in progress
    //
    // Verifies that embeddings inserted outside the pipeline (e.g., from a
    // previous run or manual insertion) are counted correctly by the progress
    // query.
    // ========================================================================
    #[tokio::test]
    async fn test_preexisting_embeddings_counted_in_progress() {
        let store = setup_test_store().await;
        let store_arc = Arc::new(store);

        // Create 10 chunks
        setup_test_chunks(&store_arc, "test-repo", 10).await;

        // Manually insert embeddings for 4 of the 10 chunks (simulating a previous run)
        let blob_shas: Vec<String> = (0..4).map(|i| format!("blob_test-repo_{}", i)).collect();
        insert_embeddings_with_params(&store_arc, blob_shas, 1024, "ollama").await;

        // Verify progress reflects the pre-existing embeddings
        let progress = get_encoding_progress(store_arc.clone(), None)
            .await
            .unwrap();
        assert_eq!(progress.total_chunks, 10);
        assert_eq!(progress.total_embeddings, 4);
        assert!((progress.percentage - 40.0).abs() < f64::EPSILON);
        assert_eq!(progress.chunks_remaining, 6);

        // Run pipeline - should only process the 6 remaining chunks
        let service = create_fast_service(1536, "openai");
        let config = PipelineConfig {
            batch_size: 10,
            incremental: true,
            dry_run: false,
            sample_size: None,
            batch_delay_ms: 0,
            max_cost_usd: None,
        };
        let pipeline = EmbeddingPipeline::new(service, config);
        let stats = pipeline.run(&store_arc).await.unwrap();
        assert_eq!(
            stats.total_chunks, 6,
            "Should only process chunks without embeddings"
        );

        // Final progress: all 10 chunks should now have embeddings
        let final_progress = get_encoding_progress(store_arc.clone(), None)
            .await
            .unwrap();
        assert_eq!(final_progress.total_chunks, 10);
        assert_eq!(final_progress.total_embeddings, 10);
        assert!((final_progress.percentage - 100.0).abs() < f64::EPSILON);
    }
}

/// Performance benchmark tests for encoding progress queries with large datasets.
///
/// These tests validate that progress queries complete in <500ms even with 100K chunks,
/// confirming the "typical repository" performance assumption from the design plan.
///
/// Run with: cargo test --release -p maproom -- --ignored --nocapture benchmark_large_repository
#[cfg(test)]
mod benchmark_tests {
    use super::*;
    use crate::db::sqlite::SqliteStore;
    use rusqlite::params;
    use std::sync::Arc;
    use std::time::Instant;

    const NUM_REPOS: usize = 10;
    const CHUNKS_PER_REPO: usize = 10_000;
    const TOTAL_CHUNKS: usize = NUM_REPOS * CHUNKS_PER_REPO; // 100,000
    const TOTAL_EMBEDDINGS: usize = TOTAL_CHUNKS / 2; // 50,000 (50% coverage)
    const QUERY_THRESHOLD_MS: u128 = 500;

    /// Helper to create a test store with migrations applied.
    async fn setup_test_store() -> Arc<SqliteStore> {
        Arc::new(SqliteStore::connect(":memory:").await.unwrap())
    }

    /// Bulk-insert test data: 10 repos, 100K chunks, 50K embeddings.
    ///
    /// Uses direct SQL batch inserts inside a transaction for speed.
    /// Returns the time taken for setup.
    async fn setup_large_test_db(store: &Arc<SqliteStore>) -> std::time::Duration {
        let start = Instant::now();

        store
            .run(move |conn| {
                let tx = conn.transaction()?;

                // 1. Create 10 repos and worktrees
                for repo_idx in 0..NUM_REPOS {
                    let repo_name = format!("bench-repo-{}", repo_idx);
                    let repo_path = format!("/bench/path/{}", repo_idx);
                    tx.execute(
                        "INSERT INTO repos (name, root_path) VALUES (?1, ?2)",
                        params![repo_name, repo_path],
                    )?;
                    let repo_id: i64 =
                        tx.query_row("SELECT last_insert_rowid()", [], |row| row.get(0))?;

                    tx.execute(
                        "INSERT INTO worktrees (repo_id, name, abs_path) VALUES (?1, ?2, ?3)",
                        params![repo_id, "main", repo_path],
                    )?;
                    let worktree_id: i64 =
                        tx.query_row("SELECT last_insert_rowid()", [], |row| row.get(0))?;

                    tx.execute(
                        "INSERT INTO commits (repo_id, sha) VALUES (?1, ?2)",
                        params![repo_id, format!("commit_{}", repo_idx)],
                    )?;
                    let commit_id: i64 =
                        tx.query_row("SELECT last_insert_rowid()", [], |row| row.get(0))?;

                    tx.execute(
                        "INSERT INTO files (repo_id, worktree_id, commit_id, relpath, language, content_hash, size_bytes)
                         VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
                        params![repo_id, worktree_id, commit_id, "bench.rs", "rust", format!("hash_{}", repo_idx), 1000],
                    )?;
                    let file_id: i64 =
                        tx.query_row("SELECT last_insert_rowid()", [], |row| row.get(0))?;

                    // 2. Bulk-insert chunks for this repo (CHUNKS_PER_REPO each)
                    {
                        let mut chunk_stmt = tx.prepare(
                            "INSERT INTO chunks (file_id, blob_sha, symbol_name, kind, start_line, end_line, preview, ts_doc_text, recency_score, churn_score, worktree_ids)
                             VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11)",
                        )?;

                        let mut cw_stmt = tx.prepare(
                            "INSERT INTO chunk_worktrees (chunk_id, worktree_id) VALUES (?1, ?2)",
                        )?;

                        for chunk_idx in 0..CHUNKS_PER_REPO {
                            let global_idx = repo_idx * CHUNKS_PER_REPO + chunk_idx;
                            let blob_sha = format!("blob_{:08x}", global_idx);
                            let sym = format!("fn_{}", chunk_idx);
                            let line_start = (chunk_idx * 10 + 1) as i32;
                            let line_end = (chunk_idx * 10 + 10) as i32;
                            let preview = format!("fn fn_{}() {{}}", chunk_idx);
                            let wt_json = format!("[{}]", worktree_id);

                            chunk_stmt.execute(params![
                                file_id, blob_sha, sym, "function",
                                line_start, line_end, preview, "",
                                1.0_f64, 0.5_f64, wt_json,
                            ])?;
                            let chunk_id: i64 =
                                tx.query_row("SELECT last_insert_rowid()", [], |row| row.get(0))?;

                            cw_stmt.execute(params![chunk_id, worktree_id])?;
                        }
                    }

                    // 3. Bulk-insert embeddings for 50% of chunks in this repo
                    {
                        let mut emb_stmt = tx.prepare(
                            "INSERT INTO code_embeddings (blob_sha, embedding, embedding_dim, model_version)
                             VALUES (?1, ?2, ?3, ?4)",
                        )?;

                        let dummy_embedding = vec![0u8; 64]; // Small dummy blob
                        for chunk_idx in 0..CHUNKS_PER_REPO {
                            if chunk_idx % 2 == 0 {
                                let global_idx = repo_idx * CHUNKS_PER_REPO + chunk_idx;
                                let blob_sha = format!("blob_{:08x}", global_idx);
                                emb_stmt.execute(params![
                                    blob_sha,
                                    dummy_embedding,
                                    768,
                                    "bench-model",
                                ])?;
                            }
                        }
                    }
                }

                tx.commit()?;
                Ok(())
            })
            .await
            .unwrap();

        start.elapsed()
    }

    /// Performance benchmark: validates encoding progress queries complete in <500ms
    /// with 100K chunks distributed across 10 repos.
    ///
    /// Run with: cargo test --release -p maproom -- --ignored --nocapture benchmark_large_repository
    #[tokio::test]
    #[ignore]
    async fn benchmark_large_repository() {
        let store = setup_test_store().await;

        // ---- Database Setup ----
        let setup_duration = setup_large_test_db(&store).await;

        println!();
        println!("Benchmark: 100K chunks performance test");
        println!("----------------------------------------");
        println!("Database setup:        {}ms", setup_duration.as_millis());

        // ---- Warm-up query (not measured) ----
        let _ = get_encoding_progress(store.clone(), None).await.unwrap();

        // ---- Global progress query ----
        let start = Instant::now();
        let global_result = get_encoding_progress(store.clone(), None).await.unwrap();
        let global_duration = start.elapsed();
        println!("Global progress query: {}ms", global_duration.as_millis());

        // Sanity-check the data
        assert_eq!(
            global_result.total_chunks, TOTAL_CHUNKS as i64,
            "Expected {} total chunks, got {}",
            TOTAL_CHUNKS, global_result.total_chunks
        );
        assert_eq!(
            global_result.total_embeddings, TOTAL_EMBEDDINGS as i64,
            "Expected {} total embeddings, got {}",
            TOTAL_EMBEDDINGS, global_result.total_embeddings
        );
        assert!(
            (global_result.percentage - 50.0).abs() < 0.1,
            "Expected ~50% coverage, got {}%",
            global_result.percentage
        );

        // ---- Repo-filtered query ----
        let start = Instant::now();
        let repo_result = get_encoding_progress(store.clone(), Some("bench-repo-0".to_string()))
            .await
            .unwrap();
        let repo_duration = start.elapsed();
        println!("Repo filtered query:   {}ms", repo_duration.as_millis());

        assert_eq!(
            repo_result.total_chunks, CHUNKS_PER_REPO as i64,
            "Expected {} chunks for single repo, got {}",
            CHUNKS_PER_REPO, repo_result.total_chunks
        );

        // ---- Query with active encoding run ----
        store
            .create_encoding_run(TOTAL_CHUNKS as i64, Some("bench-provider"), Some(768))
            .await
            .unwrap();

        let start = Instant::now();
        let run_result = get_encoding_progress(store.clone(), None).await.unwrap();
        let run_duration = start.elapsed();
        println!("With active run:       {}ms", run_duration.as_millis());

        assert!(
            run_result.active_run.is_some(),
            "Expected active run to be present"
        );

        // ---- Results ----
        println!("----------------------------------------");

        let all_pass = global_duration.as_millis() < QUERY_THRESHOLD_MS
            && repo_duration.as_millis() < QUERY_THRESHOLD_MS
            && run_duration.as_millis() < QUERY_THRESHOLD_MS;

        if all_pass {
            println!("\u{2713} All queries < {}ms threshold", QUERY_THRESHOLD_MS);
        } else {
            println!(
                "\u{2717} FAILED: some queries exceeded {}ms threshold",
                QUERY_THRESHOLD_MS
            );
        }
        println!();

        assert!(
            global_duration.as_millis() < QUERY_THRESHOLD_MS,
            "Global progress query took {}ms, exceeds {}ms threshold",
            global_duration.as_millis(),
            QUERY_THRESHOLD_MS
        );
        assert!(
            repo_duration.as_millis() < QUERY_THRESHOLD_MS,
            "Repo filtered query took {}ms, exceeds {}ms threshold",
            repo_duration.as_millis(),
            QUERY_THRESHOLD_MS
        );
        assert!(
            run_duration.as_millis() < QUERY_THRESHOLD_MS,
            "Query with active run took {}ms, exceeds {}ms threshold",
            run_duration.as_millis(),
            QUERY_THRESHOLD_MS
        );
    }
}