destructive_command_guard 0.4.3

A Claude Code hook that blocks destructive commands before they execute
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
//! `SQLite` schema definitions for command history.
//!
//! This module defines the database schema, types, and core operations for
//! the history system. The schema is designed for:
//!
//! - Efficient writes during hook execution (< 1ms target)
//! - Flexible queries for analytics and debugging
//! - Full-text search on command content
//! - Graceful schema migrations

use chrono::{DateTime, Duration, Utc};
use fsqlite::Connection;
use fsqlite_error::FrankenError;
use fsqlite_types::value::SqliteValue;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::collections::HashMap;
use std::env;
use std::fmt::Write as FmtWrite;
use std::path::{Path, PathBuf};

// ============================================================================
// SqliteValue Conversion Helpers
// ============================================================================

/// Extract a `String` from a `SqliteValue`.
fn sv_to_string(v: &SqliteValue) -> String {
    match v {
        SqliteValue::Text(s) => s.to_string(),
        SqliteValue::Integer(i) => i.to_string(),
        SqliteValue::Float(f) => f.to_string(),
        SqliteValue::Null => String::new(),
        SqliteValue::Blob(_) => String::new(),
    }
}

/// Extract an `i64` from a `SqliteValue`.
fn sv_to_i64(v: &SqliteValue) -> i64 {
    match v {
        SqliteValue::Integer(i) => *i,
        SqliteValue::Float(f) => *f as i64,
        SqliteValue::Text(s) => s.parse().unwrap_or(0),
        _ => 0,
    }
}

/// Extract an `f64` from a `SqliteValue`.
#[allow(dead_code)]
fn sv_to_f64(v: &SqliteValue) -> f64 {
    match v {
        SqliteValue::Float(f) => *f,
        SqliteValue::Integer(i) => *i as f64,
        SqliteValue::Text(s) => s.parse().unwrap_or(0.0),
        _ => 0.0,
    }
}

/// Extract an `f32` from a `SqliteValue`.
fn sv_to_f32(v: &SqliteValue) -> f32 {
    match v {
        SqliteValue::Float(f) => *f as f32,
        SqliteValue::Integer(i) => *i as f32,
        SqliteValue::Text(s) => s.parse().unwrap_or(0.0),
        _ => 0.0,
    }
}

/// Extract an `i32` from a `SqliteValue`.
fn sv_to_i32(v: &SqliteValue) -> i32 {
    match v {
        SqliteValue::Integer(i) => i32::try_from(*i).unwrap_or(0),
        SqliteValue::Float(f) => *f as i32,
        SqliteValue::Text(s) => s.parse().unwrap_or(0),
        _ => 0,
    }
}

/// Extract an `Option<String>` from a `SqliteValue`.
fn sv_to_opt_string(v: &SqliteValue) -> Option<String> {
    match v {
        SqliteValue::Text(s) => Some(s.to_string()),
        SqliteValue::Null => None,
        SqliteValue::Integer(i) => Some(i.to_string()),
        _ => None,
    }
}

fn text_sv(value: impl Into<String>) -> SqliteValue {
    SqliteValue::from(value.into())
}

/// Convert an `Option<String>` to a `SqliteValue`.
fn opt_string_to_sv(v: Option<&String>) -> SqliteValue {
    match v {
        Some(s) => text_sv(s.clone()),
        None => SqliteValue::Null,
    }
}

/// Convert an `Option<i32>` to a `SqliteValue`.
fn opt_i32_to_sv(v: Option<&i32>) -> SqliteValue {
    match v {
        Some(i) => SqliteValue::Integer(i64::from(*i)),
        None => SqliteValue::Null,
    }
}

/// Convert an `Option<i64>` to a `SqliteValue`.
fn opt_i64_to_sv(v: Option<&i64>) -> SqliteValue {
    match v {
        Some(i) => SqliteValue::Integer(*i),
        None => SqliteValue::Null,
    }
}

/// Inline bind parameters into SQL for use with `conn.query()`.
///
/// Workaround: fsqlite's `query_with_params()` only returns the first matching
/// row instead of all rows. This helper substitutes `?1`, `?2`, ... placeholders
/// with the actual values so we can use the non-parameterized `query()` method.
fn inline_params(sql: &str, params: &[SqliteValue]) -> String {
    let mut result = sql.to_string();
    // Replace in reverse order so ?10 is replaced before ?1
    for (i, param) in params.iter().enumerate().rev() {
        let placeholder = format!("?{}", i + 1);
        let value = match param {
            SqliteValue::Text(s) => format!("'{}'", s.replace('\'', "''")),
            SqliteValue::Integer(i) => i.to_string(),
            SqliteValue::Float(f) => f.to_string(),
            SqliteValue::Null => "NULL".to_string(),
            SqliteValue::Blob(_) => "X''".to_string(),
        };
        result = result.replace(&placeholder, &value);
    }
    result
}

/// Current schema version for migrations.
pub const CURRENT_SCHEMA_VERSION: u32 = 6;

/// Default database filename.
pub const DEFAULT_DB_FILENAME: &str = "history.db";

/// History-specific error type.
#[derive(Debug)]
pub enum HistoryError {
    /// FrankenSQLite error.
    Sqlite(FrankenError),
    /// I/O error.
    Io(std::io::Error),
    /// Schema version mismatch (expected, found).
    SchemaMismatch { expected: u32, found: u32 },
    /// Database is disabled.
    Disabled,
    /// Database integrity check failed.
    IntegrityCheckFailed(String),
    /// Backup operation failed.
    BackupFailed(String),
}

impl std::fmt::Display for HistoryError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Sqlite(e) => write!(f, "SQLite error: {e}"),
            Self::Io(e) => write!(f, "I/O error: {e}"),
            Self::SchemaMismatch { expected, found } => {
                write!(f, "Schema mismatch: expected v{expected}, found v{found}")
            }
            Self::Disabled => write!(f, "History is disabled"),
            Self::IntegrityCheckFailed(msg) => write!(f, "Integrity check failed: {msg}"),
            Self::BackupFailed(msg) => write!(f, "Backup failed: {msg}"),
        }
    }
}

impl std::error::Error for HistoryError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Sqlite(e) => Some(e),
            Self::Io(e) => Some(e),
            _ => None,
        }
    }
}

impl From<FrankenError> for HistoryError {
    fn from(e: FrankenError) -> Self {
        Self::Sqlite(e)
    }
}

impl From<std::io::Error> for HistoryError {
    fn from(e: std::io::Error) -> Self {
        Self::Io(e)
    }
}

/// Command evaluation outcome.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Outcome {
    /// Command was allowed to execute.
    Allow,
    /// Command was blocked from execution.
    Deny,
    /// Command triggered a warning but was allowed.
    Warn,
    /// Command was allowed via bypass (allow-once).
    Bypass,
}

impl Outcome {
    /// Convert to database string representation.
    #[must_use]
    pub const fn as_str(&self) -> &'static str {
        match self {
            Self::Allow => "allow",
            Self::Deny => "deny",
            Self::Warn => "warn",
            Self::Bypass => "bypass",
        }
    }

    fn parse_inner(s: &str) -> Option<Self> {
        match s.to_lowercase().as_str() {
            "allow" => Some(Self::Allow),
            "deny" => Some(Self::Deny),
            "warn" => Some(Self::Warn),
            "bypass" => Some(Self::Bypass),
            _ => None,
        }
    }

    /// Parse from database string representation.
    #[must_use]
    pub fn parse(s: &str) -> Option<Self> {
        Self::parse_inner(s)
    }
}

impl std::str::FromStr for Outcome {
    type Err = ();

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::parse_inner(s).ok_or(())
    }
}

/// A single command entry for the history database.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CommandEntry {
    /// Timestamp when the command was evaluated (ISO 8601).
    pub timestamp: DateTime<Utc>,
    /// Agent type that issued the command (e.g., "`claude_code`", "codex").
    pub agent_type: String,
    /// Working directory where the command was executed.
    pub working_dir: String,
    /// The actual command string.
    pub command: String,
    /// Evaluation outcome.
    pub outcome: Outcome,
    /// Pack ID that matched (if any).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub pack_id: Option<String>,
    /// Pattern name that matched (if any).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub pattern_name: Option<String>,
    /// Stable rule identifier: `pack_id:pattern_name`
    /// Present only for denied commands that matched a pattern.
    /// Format: "core.git:reset-hard", "core.filesystem:rm-rf-root"
    #[serde(skip_serializing_if = "Option::is_none")]
    pub rule_id: Option<String>,
    /// Evaluation duration in microseconds.
    #[serde(default)]
    pub eval_duration_us: u64,
    /// Optional session ID to group commands.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub session_id: Option<String>,
    /// Exit code if the command was executed.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub exit_code: Option<i32>,
    /// Parent command ID for subshell tracking.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub parent_command_id: Option<i64>,
    /// Hostname for multi-machine setups.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub hostname: Option<String>,
    /// Allowlist layer that matched (if command was allowed by allowlist).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub allowlist_layer: Option<String>,
    /// Bypass code used (if command was bypassed).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub bypass_code: Option<String>,
}

impl Default for CommandEntry {
    fn default() -> Self {
        Self {
            timestamp: Utc::now(),
            agent_type: String::new(),
            working_dir: String::new(),
            command: String::new(),
            outcome: Outcome::Allow,
            pack_id: None,
            pattern_name: None,
            rule_id: None,
            eval_duration_us: 0,
            session_id: None,
            exit_code: None,
            parent_command_id: None,
            hostname: None,
            allowlist_layer: None,
            bypass_code: None,
        }
    }
}

impl CommandEntry {
    /// Compute and return the `rule_id` from `pack_id` and `pattern_name`.
    /// Returns `Some("pack_id:pattern_name")` if both are present, else `None`.
    #[must_use]
    pub fn compute_rule_id(&self) -> Option<String> {
        match (&self.pack_id, &self.pattern_name) {
            (Some(pack), Some(pattern)) => Some(format!("{pack}:{pattern}")),
            _ => None,
        }
    }

    /// Get the `rule_id`, using the stored value or computing it from parts.
    #[must_use]
    pub fn get_rule_id(&self) -> Option<String> {
        self.rule_id.clone().or_else(|| self.compute_rule_id())
    }

    /// Ensure `rule_id` is set from `pack_id` and `pattern_name` if not already set.
    /// Returns true if `rule_id` was set or already present.
    pub fn ensure_rule_id(&mut self) -> bool {
        if self.rule_id.is_some() {
            return true;
        }
        self.rule_id = self.compute_rule_id();
        self.rule_id.is_some()
    }
}

/// Aggregate outcome counts for history stats.
#[derive(Debug, Clone, Default, Serialize)]
pub struct OutcomeStats {
    pub allowed: u64,
    pub denied: u64,
    pub warned: u64,
    pub bypassed: u64,
}

/// Performance percentiles for history stats.
#[derive(Debug, Clone, Default, Serialize)]
pub struct PerformanceStats {
    pub p50_us: u64,
    pub p95_us: u64,
    pub p99_us: u64,
    pub max_us: u64,
}

/// Top pattern count summary.
#[derive(Debug, Clone, Serialize)]
pub struct PatternStat {
    pub name: String,
    pub count: u64,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub pack_id: Option<String>,
}

/// Top project summary.
#[derive(Debug, Clone, Serialize)]
pub struct ProjectStat {
    pub path: String,
    pub command_count: u64,
}

/// Agent breakdown summary.
#[derive(Debug, Clone, Serialize)]
pub struct AgentStat {
    pub name: String,
    pub count: u64,
}

/// Trend comparison for history stats.
#[derive(Debug, Clone, Serialize)]
pub struct StatsTrends {
    pub commands_change: f64,
    pub block_rate_change: f64,
    pub top_pattern_change: Vec<(String, i32)>,
}

/// Result of a database health check.
#[derive(Debug, Clone, Serialize)]
pub struct CheckResult {
    /// `SQLite` integrity check result (should be "ok").
    pub integrity_check: String,
    /// Whether the integrity check passed.
    pub integrity_ok: bool,
    /// Foreign key check result count (0 = no violations).
    pub foreign_key_violations: usize,
    /// Number of commands in main table.
    pub commands_count: u64,
    /// Number of entries in FTS index.
    pub fts_count: u64,
    /// Whether FTS index is in sync with main table.
    pub fts_in_sync: bool,
    /// Current journal mode.
    pub journal_mode: String,
    /// Database file size in bytes.
    pub file_size_bytes: u64,
    /// WAL file size in bytes (0 if not using WAL).
    pub wal_size_bytes: u64,
    /// Current schema version.
    pub schema_version: u32,
    /// Page size in bytes.
    pub page_size: u32,
    /// Total page count.
    pub page_count: u64,
    /// Free list page count.
    pub freelist_count: u64,
}

/// Result of a database backup operation.
#[derive(Debug, Clone, Serialize)]
pub struct BackupResult {
    /// Path to the backup file.
    pub backup_path: String,
    /// Size of the backup file in bytes.
    pub backup_size_bytes: u64,
    /// Whether the backup was compressed.
    pub compressed: bool,
    /// Time taken to create backup in milliseconds.
    pub duration_ms: u64,
    /// Whether backup integrity was verified.
    pub verified: bool,
}

/// Aggregated history stats for a time window.
#[derive(Debug, Clone, Serialize)]
pub struct HistoryStats {
    pub period_days: u64,
    pub total_commands: u64,
    pub outcomes: OutcomeStats,
    pub block_rate: f64,
    pub top_patterns: Vec<PatternStat>,
    pub top_projects: Vec<ProjectStat>,
    pub agents: Vec<AgentStat>,
    pub performance: PerformanceStats,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub trends: Option<StatsTrends>,
}

// ============================================================================
// Suggestion Analysis Types
// ============================================================================

/// Command that was blocked frequently in a time window.
#[derive(Debug, Clone, Serialize)]
pub struct FrequentBlock {
    /// The blocked command.
    pub command: String,
    /// Number of times the command was blocked.
    pub block_count: u64,
    /// Most recent timestamp when the command was blocked.
    pub last_seen: DateTime<Utc>,
}

/// Command blocks clustered by working directory.
#[derive(Debug, Clone, Serialize)]
pub struct PathCluster {
    /// The blocked command.
    pub command: String,
    /// Working directory where the command was blocked.
    pub working_dir: String,
    /// Number of times the command was blocked in this directory.
    pub block_count: u64,
}

/// Command that was manually bypassed (allow-once) and may be a suggestion candidate.
#[derive(Debug, Clone, Serialize)]
pub struct SuggestionCandidate {
    /// The command that was bypassed.
    pub command: String,
    /// Number of times the command was bypassed.
    pub bypass_count: u64,
    /// Most recent timestamp when the command was bypassed.
    pub last_seen: DateTime<Utc>,
}

/// Helper for history analysis queries used by suggestion heuristics.
pub struct HistoryAnalyzer<'a> {
    conn: &'a Connection,
}

impl<'a> HistoryAnalyzer<'a> {
    /// Create a new analyzer for the provided history database.
    #[must_use]
    pub fn new(db: &'a HistoryDb) -> Self {
        Self { conn: &db.conn }
    }

    /// Return commands blocked at least `min_count` times in the last `days` days.
    ///
    /// # Errors
    ///
    /// Returns an error if the query fails.
    pub fn get_frequent_blocks(
        &self,
        days: u32,
        min_count: u32,
    ) -> Result<Vec<FrequentBlock>, HistoryError> {
        let days_i64 = i64::from(days);
        let since = Utc::now() - Duration::days(days_i64);
        let since_ts = format_timestamp(since);
        let min_count_i64 = i64::from(min_count);

        let rows = self.conn.query(&inline_params(
            "SELECT command, COUNT(*) as block_count, MAX(timestamp) as last_seen
             FROM commands
             WHERE outcome = 'deny' AND timestamp >= ?1
             GROUP BY command
             HAVING COUNT(*) >= ?2
             ORDER BY block_count DESC, command ASC",
            &[text_sv(since_ts), SqliteValue::Integer(min_count_i64)],
        ))?;

        let mut blocks = Vec::new();
        for row in &rows {
            let vals = row.values();
            let command = sv_to_string(&vals[0]);
            let block_count = sv_to_i64(&vals[1]);
            let last_seen_str = sv_to_string(&vals[2]);
            let last_seen = DateTime::parse_from_rfc3339(&last_seen_str)
                .map_or_else(|_| Utc::now(), |dt| dt.with_timezone(&Utc));
            blocks.push(FrequentBlock {
                command,
                block_count: u64::try_from(block_count).unwrap_or(0),
                last_seen,
            });
        }

        Ok(blocks)
    }

    /// Return command + working directory clusters blocked at least `min_count` times.
    ///
    /// # Errors
    ///
    /// Returns an error if the query fails.
    pub fn get_path_clusters(&self, min_count: u32) -> Result<Vec<PathCluster>, HistoryError> {
        let min_count_i64 = i64::from(min_count);

        let rows = self.conn.query(&inline_params(
            "SELECT command, working_dir, COUNT(*) as block_count
             FROM commands
             WHERE outcome = 'deny'
             GROUP BY command, working_dir
             HAVING COUNT(*) >= ?1
             ORDER BY block_count DESC, command ASC, working_dir ASC",
            &[SqliteValue::Integer(min_count_i64)],
        ))?;

        let mut clusters = Vec::new();
        for row in &rows {
            let vals = row.values();
            let command = sv_to_string(&vals[0]);
            let working_dir = sv_to_string(&vals[1]);
            let block_count = sv_to_i64(&vals[2]);
            clusters.push(PathCluster {
                command,
                working_dir,
                block_count: u64::try_from(block_count).unwrap_or(0),
            });
        }

        Ok(clusters)
    }

    /// Return commands that were manually bypassed (allow-once).
    ///
    /// This approximates "manual allows" using the `bypass` outcome.
    ///
    /// # Errors
    ///
    /// Returns an error if the query fails.
    pub fn get_suggestion_candidates(&self) -> Result<Vec<SuggestionCandidate>, HistoryError> {
        let rows = self.conn.query(
            "SELECT command, COUNT(*) as bypass_count, MAX(timestamp) as last_seen
             FROM commands
             WHERE outcome = 'bypass'
             GROUP BY command
             ORDER BY bypass_count DESC, command ASC",
        )?;

        let mut candidates = Vec::new();
        for row in &rows {
            let vals = row.values();
            let command = sv_to_string(&vals[0]);
            let bypass_count = sv_to_i64(&vals[1]);
            let last_seen_str = sv_to_string(&vals[2]);
            let last_seen = DateTime::parse_from_rfc3339(&last_seen_str)
                .map_or_else(|_| Utc::now(), |dt| dt.with_timezone(&Utc));
            candidates.push(SuggestionCandidate {
                command,
                bypass_count: u64::try_from(bypass_count).unwrap_or(0),
                last_seen,
            });
        }

        Ok(candidates)
    }
}

#[derive(Debug, Clone)]
struct StatsSnapshot {
    total_commands: u64,
    outcomes: OutcomeStats,
    block_rate: f64,
    top_patterns: Vec<PatternStat>,
    top_projects: Vec<ProjectStat>,
    agents: Vec<AgentStat>,
    performance: PerformanceStats,
}

fn format_timestamp(dt: DateTime<Utc>) -> String {
    dt.format("%Y-%m-%dT%H:%M:%S%.3fZ").to_string()
}

fn percentile_from_sorted(values: &[u64], numerator: usize, denominator: usize) -> u64 {
    if values.is_empty() || denominator == 0 {
        return 0;
    }

    let max_index = values.len() - 1;
    let numerator = numerator.min(denominator);
    let idx = (max_index * numerator + (denominator / 2)) / denominator;
    values[idx.min(max_index)]
}

#[allow(clippy::cast_precision_loss)]
fn ratio(numerator: u64, denominator: u64) -> f64 {
    if denominator == 0 {
        return 0.0;
    }
    numerator as f64 / denominator as f64
}

#[allow(clippy::cast_precision_loss)]
fn percent_change(current: u64, previous: u64) -> f64 {
    if previous == 0 {
        return if current == 0 { 0.0 } else { 100.0 };
    }
    ((current as f64 - previous as f64) / previous as f64) * 100.0
}

fn build_trends(current: &StatsSnapshot, previous: &StatsSnapshot) -> StatsTrends {
    let prev_patterns: HashMap<&str, i32> = previous
        .top_patterns
        .iter()
        .enumerate()
        .map(|(idx, stat)| {
            let rank = i32::try_from(idx + 1).unwrap_or(i32::MAX);
            (stat.name.as_str(), rank)
        })
        .collect();

    let top_pattern_change = current
        .top_patterns
        .iter()
        .enumerate()
        .map(|(idx, stat)| {
            let current_rank = i32::try_from(idx + 1).unwrap_or(i32::MAX);
            let prev_rank = prev_patterns
                .get(stat.name.as_str())
                .copied()
                .unwrap_or(current_rank);
            (stat.name.clone(), prev_rank - current_rank)
        })
        .collect::<Vec<_>>();

    StatsTrends {
        commands_change: percent_change(current.total_commands, previous.total_commands),
        block_rate_change: (current.block_rate - previous.block_rate) * 100.0,
        top_pattern_change,
    }
}

impl CommandEntry {
    /// Compute a SHA256 hash of the command for deduplication/grouping.
    #[must_use]
    pub fn command_hash(&self) -> String {
        let mut hasher = Sha256::new();
        hasher.update(self.command.as_bytes());
        let digest = hasher.finalize();
        let mut hex = String::with_capacity(digest.len() * 2);
        for byte in digest {
            let _ = write!(hex, "{byte:02x}");
        }
        hex
    }
}

/// History database handle.
pub struct HistoryDb {
    conn: Connection,
    path: Option<PathBuf>,
}

impl HistoryDb {
    /// Open or create the history database at the default path.
    ///
    /// The default path is `~/.config/dcg/history.db` unless overridden
    /// by the `DCG_HISTORY_DB` environment variable.
    ///
    /// # Errors
    ///
    /// Returns an error if the database cannot be opened or initialized.
    pub fn open(path: Option<PathBuf>) -> Result<Self, HistoryError> {
        // Check if history is disabled
        if env::var(super::ENV_HISTORY_DISABLED)
            .map(|v| v == "1" || v.to_lowercase() == "true")
            .unwrap_or(false)
        {
            return Err(HistoryError::Disabled);
        }

        let db_path = path.unwrap_or_else(Self::default_path);

        // Ensure parent directory exists
        if let Some(parent) = db_path.parent() {
            std::fs::create_dir_all(parent)?;
        }

        let path_str = db_path.to_string_lossy().to_string();
        let conn = Connection::open(&path_str)?;
        let db = Self {
            conn,
            path: Some(db_path),
        };
        db.initialize_schema()?;
        Ok(db)
    }

    /// Open an in-memory database for testing.
    ///
    /// # Errors
    ///
    /// Returns an error if the database cannot be initialized.
    pub fn open_in_memory() -> Result<Self, HistoryError> {
        let conn = Connection::open(":memory:")?;
        let db = Self { conn, path: None };
        db.initialize_schema()?;
        Ok(db)
    }

    /// Get the default database path.
    #[must_use]
    pub fn default_path() -> PathBuf {
        if let Ok(path) = env::var(super::ENV_HISTORY_DB_PATH) {
            return PathBuf::from(path);
        }

        // Check XDG-style path first (~/.config/dcg/), then platform-native
        let xdg_base = dirs::home_dir().map(|h| h.join(".config"));
        let xdg_path = xdg_base
            .as_ref()
            .map(|b| b.join("dcg").join(DEFAULT_DB_FILENAME));
        if let Some(ref path) = xdg_path {
            if path.exists()
                || xdg_base
                    .as_ref()
                    .map(|b| b.join("dcg").exists())
                    .unwrap_or(false)
            {
                return path.clone();
            }
        }

        // Fall back to platform-native
        let base = dirs::config_dir()
            .unwrap_or_else(|| dirs::home_dir().unwrap_or_default().join(".config"));
        base.join("dcg").join(DEFAULT_DB_FILENAME)
    }

    /// Get the database file path (None for in-memory).
    #[must_use]
    pub fn path(&self) -> Option<&Path> {
        self.path.as_deref()
    }

    /// Get the current schema version.
    ///
    /// # Errors
    ///
    /// Returns an error if the schema version cannot be read.
    pub fn get_schema_version(&self) -> Result<u32, HistoryError> {
        let row = self
            .conn
            .query_row("SELECT version FROM schema_version ORDER BY version DESC LIMIT 1")?;
        let version = sv_to_i64(&row.values()[0]);
        Ok(u32::try_from(version).unwrap_or(0))
    }

    /// Attempt to open the history database, returning None on failure.
    ///
    /// This is intended for fail-open paths (history should never block the hook).
    #[must_use]
    pub fn try_open(path: Option<PathBuf>) -> Option<Self> {
        Self::open(path).ok()
    }

    /// Get the database file size in bytes.
    ///
    /// Returns 0 for in-memory databases.
    ///
    /// # Errors
    ///
    /// Returns an error if the file metadata cannot be read.
    pub fn file_size(&self) -> Result<u64, HistoryError> {
        match &self.path {
            Some(p) => Ok(std::fs::metadata(p)?.len()),
            None => Ok(0),
        }
    }

    /// Count total commands in the database.
    ///
    /// # Errors
    ///
    /// Returns an error if the query fails.
    pub fn count_commands(&self) -> Result<u64, HistoryError> {
        let row = self.conn.query_row("SELECT COUNT(*) FROM commands")?;
        let count = sv_to_i64(&row.values()[0]);
        Ok(u64::try_from(count).unwrap_or(0))
    }

    /// Prune history entries older than the specified number of days.
    ///
    /// When `dry_run` is true, no rows are deleted.
    ///
    /// # Errors
    ///
    /// Returns an error if any query fails.
    pub fn prune_older_than_days(
        &self,
        older_than_days: u64,
        dry_run: bool,
    ) -> Result<u64, HistoryError> {
        let days_i64 = i64::try_from(older_than_days).unwrap_or(i64::MAX);
        let cutoff = Utc::now() - Duration::days(days_i64);
        let cutoff_ts = format_timestamp(cutoff);

        let row = self.conn.query_row_with_params(
            "SELECT COUNT(*) FROM commands WHERE timestamp < ?1",
            &[text_sv(cutoff_ts.clone())],
        )?;
        let count = sv_to_i64(&row.values()[0]);

        if !dry_run {
            self.conn.execute_with_params(
                "DELETE FROM commands WHERE timestamp < ?1",
                &[text_sv(cutoff_ts)],
            )?;
            // Rebuild FTS index after deletion since fsqlite FTS5 doesn't support
            // individual row deletion via 'delete' control command triggers
            self.rebuild_fts()?;
        }

        Ok(u64::try_from(count).unwrap_or(0))
    }

    /// Compute history stats for the last `period_days` days.
    ///
    /// # Errors
    ///
    /// Returns an error if any underlying query fails.
    pub fn compute_stats(&self, period_days: u64) -> Result<HistoryStats, HistoryError> {
        let now = Utc::now();
        let period_days_i64 = i64::try_from(period_days).unwrap_or(i64::MAX);
        let since = now - Duration::days(period_days_i64);
        let snapshot = self.compute_stats_range(since, now)?;
        Ok(HistoryStats {
            period_days,
            total_commands: snapshot.total_commands,
            outcomes: snapshot.outcomes,
            block_rate: snapshot.block_rate,
            top_patterns: snapshot.top_patterns,
            top_projects: snapshot.top_projects,
            agents: snapshot.agents,
            performance: snapshot.performance,
            trends: None,
        })
    }

    /// Compute history stats with trend comparison against the previous period.
    ///
    /// # Errors
    ///
    /// Returns an error if any underlying query fails.
    pub fn compute_stats_with_trends(
        &self,
        period_days: u64,
    ) -> Result<HistoryStats, HistoryError> {
        let now = Utc::now();
        let period_days_i64 = i64::try_from(period_days).unwrap_or(i64::MAX);
        let since = now - Duration::days(period_days_i64);
        let prev_start = since - Duration::days(period_days_i64);

        let current = self.compute_stats_range(since, now)?;
        let previous = self.compute_stats_range(prev_start, since)?;

        let trends = build_trends(&current, &previous);

        Ok(HistoryStats {
            period_days,
            total_commands: current.total_commands,
            outcomes: current.outcomes,
            block_rate: current.block_rate,
            top_patterns: current.top_patterns,
            top_projects: current.top_projects,
            agents: current.agents,
            performance: current.performance,
            trends: Some(trends),
        })
    }

    #[allow(clippy::too_many_lines)]
    fn compute_stats_range(
        &self,
        start: DateTime<Utc>,
        end: DateTime<Utc>,
    ) -> Result<StatsSnapshot, HistoryError> {
        let start_ts = format_timestamp(start);
        let end_ts = format_timestamp(end);
        let ts_params = &[text_sv(start_ts.clone()), text_sv(end_ts.clone())];

        let total_row = self.conn.query_row_with_params(
            "SELECT COUNT(*) FROM commands WHERE timestamp >= ?1 AND timestamp < ?2",
            ts_params,
        )?;
        let total_commands = u64::try_from(sv_to_i64(&total_row.values()[0])).unwrap_or(0);

        let mut outcomes = OutcomeStats::default();
        let outcome_rows = self.conn.query(&inline_params(
            "SELECT outcome, COUNT(*) FROM commands
             WHERE timestamp >= ?1 AND timestamp < ?2
             GROUP BY outcome",
            ts_params,
        ))?;
        for row in &outcome_rows {
            let vals = row.values();
            let outcome = sv_to_string(&vals[0]);
            let count = u64::try_from(sv_to_i64(&vals[1])).unwrap_or(0);
            match Outcome::parse(&outcome) {
                Some(Outcome::Allow) => outcomes.allowed = count,
                Some(Outcome::Deny) => outcomes.denied = count,
                Some(Outcome::Warn) => outcomes.warned = count,
                Some(Outcome::Bypass) => outcomes.bypassed = count,
                None => {}
            }
        }

        let block_rate = ratio(outcomes.denied, total_commands);

        let mut top_patterns = Vec::new();
        let pattern_rows = self.conn.query(&inline_params(
            "SELECT pattern_name, pack_id, COUNT(*) FROM commands
             WHERE timestamp >= ?1 AND timestamp < ?2 AND pattern_name IS NOT NULL
             GROUP BY pattern_name, pack_id
             ORDER BY COUNT(*) DESC, pattern_name ASC
             LIMIT 10",
            ts_params,
        ))?;
        for row in &pattern_rows {
            let vals = row.values();
            let name = sv_to_string(&vals[0]);
            let pack_id = sv_to_opt_string(&vals[1]);
            let count = sv_to_i64(&vals[2]);
            top_patterns.push(PatternStat {
                name,
                count: u64::try_from(count).unwrap_or(0),
                pack_id,
            });
        }

        let mut top_projects = Vec::new();
        let project_rows = self.conn.query(&inline_params(
            "SELECT working_dir, COUNT(*) FROM commands
             WHERE timestamp >= ?1 AND timestamp < ?2
             GROUP BY working_dir
             ORDER BY COUNT(*) DESC, working_dir ASC
             LIMIT 10",
            ts_params,
        ))?;
        for row in &project_rows {
            let vals = row.values();
            let path = sv_to_string(&vals[0]);
            let count = sv_to_i64(&vals[1]);
            top_projects.push(ProjectStat {
                path,
                command_count: u64::try_from(count).unwrap_or(0),
            });
        }

        let mut agents = Vec::new();
        let agent_rows = self.conn.query(&inline_params(
            "SELECT agent_type, COUNT(*) FROM commands
             WHERE timestamp >= ?1 AND timestamp < ?2
             GROUP BY agent_type
             ORDER BY COUNT(*) DESC, agent_type ASC",
            ts_params,
        ))?;
        for row in &agent_rows {
            let vals = row.values();
            let name = sv_to_string(&vals[0]);
            let count = sv_to_i64(&vals[1]);
            agents.push(AgentStat {
                name,
                count: u64::try_from(count).unwrap_or(0),
            });
        }

        let mut durations = Vec::new();
        let dur_rows = self.conn.query(&inline_params(
            "SELECT eval_duration_us FROM commands
             WHERE timestamp >= ?1 AND timestamp < ?2 AND eval_duration_us > 0
             ORDER BY eval_duration_us ASC",
            ts_params,
        ))?;
        for row in &dur_rows {
            let value = sv_to_i64(&row.values()[0]);
            if let Ok(value) = u64::try_from(value) {
                durations.push(value);
            }
        }

        let performance = if durations.is_empty() {
            PerformanceStats::default()
        } else {
            let max_us = *durations.last().unwrap_or(&0);
            PerformanceStats {
                p50_us: percentile_from_sorted(&durations, 50, 100),
                p95_us: percentile_from_sorted(&durations, 95, 100),
                p99_us: percentile_from_sorted(&durations, 99, 100),
                max_us,
            }
        };

        Ok(StatsSnapshot {
            total_commands,
            outcomes,
            block_rate,
            top_patterns,
            top_projects,
            agents,
            performance,
        })
    }

    /// Log a command entry to the database.
    ///
    /// # Errors
    ///
    /// Returns an error if the insert fails.
    pub fn log_command(&self, entry: &CommandEntry) -> Result<i64, HistoryError> {
        let command_hash = entry.command_hash();
        let timestamp = entry.timestamp.format("%Y-%m-%dT%H:%M:%S%.3fZ").to_string();

        let eval_duration_us = i64::try_from(entry.eval_duration_us).unwrap_or(i64::MAX);

        // Compute rule_id if not already set but pack_id and pattern_name are present
        let rule_id = entry.rule_id.clone().or_else(|| entry.compute_rule_id());

        self.conn.execute_with_params(
            r"INSERT INTO commands (
                timestamp, agent_type, working_dir, command, command_hash,
                outcome, pack_id, pattern_name, rule_id, eval_duration_us,
                session_id, exit_code, parent_command_id, hostname,
                allowlist_layer, bypass_code
            ) VALUES (
                ?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16
            )",
            &[
                text_sv(timestamp),
                text_sv(entry.agent_type.clone()),
                text_sv(entry.working_dir.clone()),
                text_sv(entry.command.clone()),
                text_sv(command_hash),
                text_sv(entry.outcome.as_str()),
                opt_string_to_sv(entry.pack_id.as_ref()),
                opt_string_to_sv(entry.pattern_name.as_ref()),
                opt_string_to_sv(rule_id.as_ref()),
                SqliteValue::Integer(eval_duration_us),
                opt_string_to_sv(entry.session_id.as_ref()),
                opt_i32_to_sv(entry.exit_code.as_ref()),
                opt_i64_to_sv(entry.parent_command_id.as_ref()),
                opt_string_to_sv(entry.hostname.as_ref()),
                opt_string_to_sv(entry.allowlist_layer.as_ref()),
                opt_string_to_sv(entry.bypass_code.as_ref()),
            ],
        )?;

        // FrankenSQLite: last_insert_rowid() is a stub, use max(id) instead
        let row = self.conn.query_row("SELECT max(id) FROM commands")?;
        Ok(sv_to_i64(&row.values()[0]))
    }

    /// Run VACUUM to reclaim space after deletions.
    ///
    /// # Errors
    ///
    /// Returns an error if the VACUUM fails.
    pub fn vacuum(&self) -> Result<(), HistoryError> {
        self.conn.execute("VACUUM")?;
        Ok(())
    }

    /// Initialize the database schema.
    fn initialize_schema(&self) -> Result<(), HistoryError> {
        // Enable WAL mode for better concurrent performance
        self.conn.execute("PRAGMA journal_mode=WAL;")?;

        // Set busy timeout for better concurrent access (5 seconds default)
        self.conn.execute("PRAGMA busy_timeout=5000;")?;

        // Configure WAL checkpoint behavior
        self.conn.execute("PRAGMA wal_autocheckpoint=1000;")?;

        // Create schema version table (includes all columns up to v3)
        self.conn.execute(
            r"CREATE TABLE IF NOT EXISTS schema_version (
                version INTEGER PRIMARY KEY,
                applied_at TEXT NOT NULL DEFAULT (datetime('now')),
                description TEXT NOT NULL DEFAULT 'Initial schema',
                last_prune_at TEXT
            )",
        )?;

        // Check if we need to initialize
        let needs_init = self
            .conn
            .query_row("SELECT COUNT(*) = 0 FROM schema_version")
            .map(|row| sv_to_i64(&row.values()[0]) != 0)
            .unwrap_or(true);

        if needs_init {
            self.create_v1_schema()?;
        } else {
            // Run migrations if needed
            let version = self.get_schema_version()?;
            if version < CURRENT_SCHEMA_VERSION {
                self.run_migrations(version)?;
            }
        }

        Ok(())
    }

    /// Create the v1 schema (initial version).
    #[allow(clippy::too_many_lines)]
    fn create_v1_schema(&self) -> Result<(), HistoryError> {
        // Main commands table
        self.conn.execute(
            r"CREATE TABLE IF NOT EXISTS commands (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                timestamp TEXT NOT NULL,
                agent_type TEXT NOT NULL,
                working_dir TEXT NOT NULL,
                command TEXT NOT NULL,
                command_hash TEXT NOT NULL,
                outcome TEXT NOT NULL CHECK (outcome IN ('allow', 'deny', 'warn', 'bypass')),
                pack_id TEXT,
                pattern_name TEXT,
                rule_id TEXT,
                eval_duration_us INTEGER DEFAULT 0,
                session_id TEXT,
                exit_code INTEGER,
                parent_command_id INTEGER REFERENCES commands(id),
                hostname TEXT,
                allowlist_layer TEXT,
                bypass_code TEXT
            )",
        )?;

        // Create indexes for common query patterns (split from execute_batch)
        self.conn
            .execute("CREATE INDEX IF NOT EXISTS idx_commands_timestamp ON commands(timestamp)")?;
        self.conn
            .execute("CREATE INDEX IF NOT EXISTS idx_commands_outcome ON commands(outcome)")?;
        self.conn.execute(
            "CREATE INDEX IF NOT EXISTS idx_commands_working_dir ON commands(working_dir)",
        )?;
        self.conn
            .execute("CREATE INDEX IF NOT EXISTS idx_commands_pack_id ON commands(pack_id)")?;
        self.conn.execute("CREATE INDEX IF NOT EXISTS idx_commands_rule_id ON commands(rule_id) WHERE rule_id IS NOT NULL")?;
        self.conn.execute(
            "CREATE INDEX IF NOT EXISTS idx_commands_agent_type ON commands(agent_type)",
        )?;
        self.conn.execute(
            "CREATE INDEX IF NOT EXISTS idx_commands_session_id ON commands(session_id)",
        )?;
        self.conn.execute(
            "CREATE INDEX IF NOT EXISTS idx_commands_command_hash ON commands(command_hash)",
        )?;
        self.conn.execute("CREATE INDEX IF NOT EXISTS idx_commands_outcome_timestamp ON commands(outcome, timestamp)")?;
        self.conn.execute(
            "CREATE INDEX IF NOT EXISTS idx_commands_pack_outcome ON commands(pack_id, outcome)",
        )?;

        // Create FTS5 virtual table for full-text search
        self.conn.execute(
            r"CREATE VIRTUAL TABLE IF NOT EXISTS commands_fts USING fts5(
                command,
                content='commands',
                content_rowid='id'
            )",
        )?;

        // Create trigger to keep FTS in sync on INSERT.
        // Note: fsqlite's FTS5 does not support the 'delete' control command via
        // INSERT INTO fts(fts, rowid, col) VALUES('delete', ...), so we omit
        // DELETE/UPDATE triggers. Instead, prune_older_than_days rebuilds FTS after deletion.
        self.conn.execute(
            r"CREATE TRIGGER IF NOT EXISTS commands_fts_insert AFTER INSERT ON commands BEGIN
                INSERT INTO commands_fts(rowid, command) VALUES (new.id, new.command);
            END",
        )?;

        // Create stats_cache table for real-time statistics (v3 feature)
        self.conn.execute(
            r"CREATE TABLE IF NOT EXISTS stats_cache (
                key TEXT PRIMARY KEY,
                value INTEGER NOT NULL,
                updated_at TEXT NOT NULL
            )",
        )?;

        // Create suggestion_audit table for tracking accepted/modified/rejected suggestions (v5 feature)
        self.conn.execute(
            r"CREATE TABLE IF NOT EXISTS suggestion_audit (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                timestamp TEXT NOT NULL,
                action TEXT NOT NULL CHECK (action IN ('accepted', 'modified', 'rejected')),
                pattern TEXT NOT NULL,
                final_pattern TEXT,
                risk_level TEXT NOT NULL,
                risk_score REAL NOT NULL,
                confidence_tier TEXT NOT NULL,
                confidence_points INTEGER NOT NULL,
                cluster_frequency INTEGER NOT NULL,
                unique_variants INTEGER NOT NULL,
                sample_commands TEXT NOT NULL,
                rule_id TEXT,
                session_id TEXT,
                working_dir TEXT
            )",
        )?;

        // Create indexes for suggestion_audit
        self.conn.execute("CREATE INDEX IF NOT EXISTS idx_suggestion_audit_timestamp ON suggestion_audit(timestamp)")?;
        self.conn.execute(
            "CREATE INDEX IF NOT EXISTS idx_suggestion_audit_action ON suggestion_audit(action)",
        )?;
        self.conn.execute("CREATE INDEX IF NOT EXISTS idx_suggestion_audit_session_id ON suggestion_audit(session_id)")?;

        // Create interactive_allowlist_audit table for interactive allowlist actions (v6 feature)
        self.conn.execute(
            r"CREATE TABLE IF NOT EXISTS interactive_allowlist_audit (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                timestamp TEXT NOT NULL,
                command TEXT NOT NULL,
                pattern_added TEXT NOT NULL,
                option_type TEXT NOT NULL CHECK (option_type IN ('exact', 'temporary', 'path_specific')),
                option_detail TEXT,
                config_file TEXT NOT NULL,
                cwd TEXT,
                user TEXT
            )",
        )?;

        // Create indexes for interactive_allowlist_audit
        self.conn.execute("CREATE INDEX IF NOT EXISTS idx_interactive_allowlist_audit_timestamp ON interactive_allowlist_audit(timestamp)")?;
        self.conn.execute("CREATE INDEX IF NOT EXISTS idx_interactive_allowlist_audit_option_type ON interactive_allowlist_audit(option_type)")?;

        // Record schema version.
        // Use INSERT OR REPLACE so that reopening a file-backed database whose
        // pager already contains the schema_version row does not fail with a
        // PRIMARY KEY constraint error (fsqlite may replay `create_v1_schema`
        // when the schema_version table appears empty in the in-memory catalog
        // but its B-tree pages are already populated on disk).
        self.conn.execute_with_params(
            "INSERT OR REPLACE INTO schema_version (version, description, last_prune_at) VALUES (?1, ?2, NULL)",
            &[
                SqliteValue::Integer(i64::from(CURRENT_SCHEMA_VERSION)),
                text_sv("Initial schema"),
            ],
        )?;

        Ok(())
    }

    /// Run migrations from a given version to current.
    fn run_migrations(&self, from_version: u32) -> Result<(), HistoryError> {
        // Apply migrations in order.
        if from_version < 2 {
            self.migrate_v1_to_v2()?;
        }
        if from_version < 3 {
            self.migrate_v2_to_v3()?;
        }
        if from_version < 4 {
            self.migrate_v3_to_v4()?;
        }
        if from_version < 5 {
            self.migrate_v4_to_v5()?;
        }
        if from_version < 6 {
            self.migrate_v5_to_v6()?;
        }

        // Ensure we're at the expected version
        let current = self.get_schema_version()?;
        if current != CURRENT_SCHEMA_VERSION {
            return Err(HistoryError::SchemaMismatch {
                expected: CURRENT_SCHEMA_VERSION,
                found: current,
            });
        }

        Ok(())
    }

    fn schema_version_has_description(&self) -> Result<bool, HistoryError> {
        let rows = self.conn.query("PRAGMA table_info(schema_version)")?;
        Ok(rows
            .iter()
            .any(|row| sv_to_string(&row.values()[1]) == "description"))
    }

    fn migrate_v1_to_v2(&self) -> Result<(), HistoryError> {
        if !self.schema_version_has_description()? {
            self.conn.execute(
                "ALTER TABLE schema_version ADD COLUMN description TEXT NOT NULL DEFAULT 'Initial schema'",
            )?;
        }

        self.conn.execute_with_params(
            "INSERT OR REPLACE INTO schema_version (version, description) VALUES (?1, ?2)",
            &[
                SqliteValue::Integer(2),
                text_sv("Add schema version descriptions"),
            ],
        )?;
        Ok(())
    }

    fn migrate_v2_to_v3(&self) -> Result<(), HistoryError> {
        // Add stats_cache table for real-time statistics
        self.conn.execute(
            r"CREATE TABLE IF NOT EXISTS stats_cache (
                key TEXT PRIMARY KEY,
                value INTEGER NOT NULL,
                updated_at TEXT NOT NULL
            )",
        )?;

        // Add last_prune_at column to schema_version for auto-prune tracking
        // Check if column exists first
        let rows = self.conn.query("PRAGMA table_info(schema_version)")?;
        let has_last_prune = rows
            .iter()
            .any(|row| sv_to_string(&row.values()[1]) == "last_prune_at");

        if !has_last_prune {
            self.conn
                .execute("ALTER TABLE schema_version ADD COLUMN last_prune_at TEXT")?;
        }

        // Record migration
        self.conn.execute_with_params(
            "INSERT OR REPLACE INTO schema_version (version, description) VALUES (?1, ?2)",
            &[
                SqliteValue::Integer(3),
                text_sv("Add stats cache and auto-prune tracking"),
            ],
        )?;

        Ok(())
    }

    fn migrate_v3_to_v4(&self) -> Result<(), HistoryError> {
        // Add rule_id column for stable pattern identification
        // Check if column exists first
        let rows = self.conn.query("PRAGMA table_info(commands)")?;
        let has_rule_id = rows
            .iter()
            .any(|row| sv_to_string(&row.values()[1]) == "rule_id");

        if !has_rule_id {
            self.conn
                .execute("ALTER TABLE commands ADD COLUMN rule_id TEXT")?;
        }

        // Backfill rule_id from existing pack_id and pattern_name
        self.conn.execute(
            r"UPDATE commands
              SET rule_id = pack_id || ':' || pattern_name
              WHERE rule_id IS NULL
                AND pack_id IS NOT NULL
                AND pattern_name IS NOT NULL",
        )?;

        // Create index for rule_id queries (partial index for non-NULL values)
        self.conn.execute(
            r"CREATE INDEX IF NOT EXISTS idx_commands_rule_id
              ON commands(rule_id) WHERE rule_id IS NOT NULL",
        )?;

        // Record migration
        self.conn.execute_with_params(
            "INSERT OR REPLACE INTO schema_version (version, description) VALUES (?1, ?2)",
            &[
                SqliteValue::Integer(4),
                text_sv("Add rule_id column and index"),
            ],
        )?;

        Ok(())
    }

    fn migrate_v4_to_v5(&self) -> Result<(), HistoryError> {
        // Add suggestion_audit table for tracking accepted/modified/rejected suggestions
        self.conn.execute(
            r"CREATE TABLE IF NOT EXISTS suggestion_audit (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                timestamp TEXT NOT NULL,
                action TEXT NOT NULL CHECK (action IN ('accepted', 'modified', 'rejected')),
                pattern TEXT NOT NULL,
                final_pattern TEXT,
                risk_level TEXT NOT NULL,
                risk_score REAL NOT NULL,
                confidence_tier TEXT NOT NULL,
                confidence_points INTEGER NOT NULL,
                cluster_frequency INTEGER NOT NULL,
                unique_variants INTEGER NOT NULL,
                sample_commands TEXT NOT NULL,
                rule_id TEXT,
                session_id TEXT,
                working_dir TEXT
            )",
        )?;

        // Create indexes for common query patterns
        self.conn.execute("CREATE INDEX IF NOT EXISTS idx_suggestion_audit_timestamp ON suggestion_audit(timestamp)")?;
        self.conn.execute(
            "CREATE INDEX IF NOT EXISTS idx_suggestion_audit_action ON suggestion_audit(action)",
        )?;
        self.conn.execute("CREATE INDEX IF NOT EXISTS idx_suggestion_audit_session_id ON suggestion_audit(session_id)")?;

        // Record migration
        self.conn.execute_with_params(
            "INSERT OR REPLACE INTO schema_version (version, description) VALUES (?1, ?2)",
            &[
                SqliteValue::Integer(5),
                text_sv("Add suggestion_audit table for tracking suggestion actions"),
            ],
        )?;

        Ok(())
    }

    fn migrate_v5_to_v6(&self) -> Result<(), HistoryError> {
        // Add interactive_allowlist_audit table for tracking interactive allowlist operations
        self.conn.execute(
            r"CREATE TABLE IF NOT EXISTS interactive_allowlist_audit (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                timestamp TEXT NOT NULL,
                command TEXT NOT NULL,
                pattern_added TEXT NOT NULL,
                option_type TEXT NOT NULL CHECK (option_type IN ('exact', 'temporary', 'path_specific')),
                option_detail TEXT,
                config_file TEXT NOT NULL,
                cwd TEXT,
                user TEXT
            )",
        )?;

        // Create indexes for common query patterns
        self.conn.execute("CREATE INDEX IF NOT EXISTS idx_interactive_allowlist_audit_timestamp ON interactive_allowlist_audit(timestamp)")?;
        self.conn.execute("CREATE INDEX IF NOT EXISTS idx_interactive_allowlist_audit_option_type ON interactive_allowlist_audit(option_type)")?;

        // Record migration
        self.conn.execute_with_params(
            "INSERT OR REPLACE INTO schema_version (version, description) VALUES (?1, ?2)",
            &[
                SqliteValue::Integer(6),
                text_sv("Add interactive_allowlist_audit table for interactive allowlist actions"),
            ],
        )?;

        Ok(())
    }

    // ========================================================================
    // Batch Operations
    // ========================================================================

    /// Log multiple command entries in a single transaction (batched insert).
    ///
    /// Uses `BEGIN IMMEDIATE` for reliable single-writer batching.
    ///
    /// # Errors
    ///
    /// Returns an error if the transaction fails.
    pub fn log_commands_batch(&self, entries: &[CommandEntry]) -> Result<(), HistoryError> {
        if entries.is_empty() {
            return Ok(());
        }

        // Use BEGIN IMMEDIATE for reliable single-writer batching.
        // BEGIN CONCURRENT is available in fsqlite for multi-writer MVCC scenarios,
        // but the HistoryWriter uses a single connection so IMMEDIATE is sufficient.
        self.conn.execute("BEGIN IMMEDIATE;")?;

        let result = (|| -> Result<(), HistoryError> {
            for entry in entries {
                let command_hash = entry.command_hash();
                let timestamp = entry.timestamp.format("%Y-%m-%dT%H:%M:%S%.3fZ").to_string();
                let eval_duration_us = i64::try_from(entry.eval_duration_us).unwrap_or(i64::MAX);

                // Use inline_params + execute to avoid execute_with_params
                // nesting auto-transaction inside our explicit BEGIN IMMEDIATE.
                let sql = inline_params(
                    r"INSERT INTO commands (
                        timestamp, agent_type, working_dir, command, command_hash,
                        outcome, pack_id, pattern_name, eval_duration_us,
                        session_id, exit_code, parent_command_id, hostname,
                        allowlist_layer, bypass_code, rule_id
                    ) VALUES (
                        ?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16
                    )",
                    &[
                        text_sv(timestamp),
                        text_sv(entry.agent_type.clone()),
                        text_sv(entry.working_dir.clone()),
                        text_sv(entry.command.clone()),
                        text_sv(command_hash),
                        text_sv(entry.outcome.as_str()),
                        opt_string_to_sv(entry.pack_id.as_ref()),
                        opt_string_to_sv(entry.pattern_name.as_ref()),
                        SqliteValue::Integer(eval_duration_us),
                        opt_string_to_sv(entry.session_id.as_ref()),
                        opt_i32_to_sv(entry.exit_code.as_ref()),
                        opt_i64_to_sv(entry.parent_command_id.as_ref()),
                        opt_string_to_sv(entry.hostname.as_ref()),
                        opt_string_to_sv(entry.allowlist_layer.as_ref()),
                        opt_string_to_sv(entry.bypass_code.as_ref()),
                        opt_string_to_sv(entry.get_rule_id().as_ref()),
                    ],
                );
                self.conn.execute(&sql)?;
            }
            Ok(())
        })();

        match result {
            Ok(()) => {
                self.conn.execute("COMMIT;")?;
                Ok(())
            }
            Err(e) => {
                let _ = self.conn.execute("ROLLBACK;");
                Err(e)
            }
        }
    }

    // ========================================================================
    // WAL and Checkpoint Operations
    // ========================================================================

    /// Manually checkpoint the WAL file.
    ///
    /// This moves committed transactions from WAL to the main database file.
    /// Uses PASSIVE mode to avoid blocking readers.
    ///
    /// # Errors
    ///
    /// Returns an error if the checkpoint fails.
    pub fn checkpoint(&self) -> Result<(), HistoryError> {
        self.conn.execute("PRAGMA wal_checkpoint(PASSIVE);")?;
        Ok(())
    }

    /// Checkpoint with TRUNCATE mode (resets WAL file).
    ///
    /// This is more aggressive and may block briefly, but reclaims disk space.
    ///
    /// # Errors
    ///
    /// Returns an error if the checkpoint fails.
    pub fn checkpoint_truncate(&self) -> Result<(), HistoryError> {
        self.conn.execute("PRAGMA wal_checkpoint(TRUNCATE);")?;
        Ok(())
    }

    // ========================================================================
    // Auto-Prune Support
    // ========================================================================

    /// Check if automatic pruning should run based on the last prune timestamp.
    ///
    /// Returns true if no prune has been recorded or if the last prune was
    /// more than 24 hours ago.
    ///
    /// # Errors
    ///
    /// Returns an error if the query fails.
    pub fn should_auto_prune(&self) -> Result<bool, HistoryError> {
        let result = self.conn.query_row(
            "SELECT last_prune_at FROM schema_version WHERE last_prune_at IS NOT NULL ORDER BY version DESC LIMIT 1",
        );

        match result {
            Ok(row) => {
                let timestamp_str = sv_to_string(&row.values()[0]);
                if timestamp_str.is_empty() {
                    return Ok(true);
                }
                chrono::DateTime::parse_from_rfc3339(&timestamp_str).map_or(
                    Ok(true), // Invalid timestamp, assume prune needed
                    |last_prune| {
                        let hours_since_prune =
                            (Utc::now() - last_prune.with_timezone(&Utc)).num_hours();
                        Ok(hours_since_prune >= 24)
                    },
                )
            }
            Err(_) => Ok(true), // No rows found, prune needed
        }
    }

    /// Record the current timestamp as the last prune time.
    ///
    /// # Errors
    ///
    /// Returns an error if the update fails.
    pub fn record_prune_timestamp(&self) -> Result<(), HistoryError> {
        let now = format_timestamp(Utc::now());
        self.conn.execute_with_params(
            "UPDATE schema_version SET last_prune_at = ?1 WHERE version = (SELECT MAX(version) FROM schema_version)",
            &[text_sv(now)],
        )?;
        Ok(())
    }

    // ========================================================================
    // Statistics Cache
    // ========================================================================

    /// Get a cached statistic value.
    ///
    /// Returns None if the key doesn't exist or is stale (older than `max_age_secs`).
    ///
    /// # Errors
    ///
    /// Returns an error if the query fails.
    pub fn get_cached_stat(
        &self,
        key: &str,
        max_age_secs: i64,
    ) -> Result<Option<i64>, HistoryError> {
        let result = self.conn.query_row_with_params(
            "SELECT value, updated_at FROM stats_cache WHERE key = ?1",
            &[text_sv(key)],
        );

        match result {
            Ok(row) => {
                let vals = row.values();
                let value = sv_to_i64(&vals[0]);
                let updated_at = sv_to_string(&vals[1]);
                if let Ok(updated) = chrono::DateTime::parse_from_rfc3339(&updated_at) {
                    let age_secs = (Utc::now() - updated.with_timezone(&Utc)).num_seconds();
                    if age_secs <= max_age_secs {
                        return Ok(Some(value));
                    }
                }
                Ok(None) // Stale or invalid timestamp
            }
            Err(_) => Ok(None),
        }
    }

    /// Update a cached statistic value.
    ///
    /// # Errors
    ///
    /// Returns an error if the upsert fails.
    pub fn update_cached_stat(&self, key: &str, value: i64) -> Result<(), HistoryError> {
        let now = format_timestamp(Utc::now());
        self.conn.execute_with_params(
            "INSERT INTO stats_cache (key, value, updated_at) VALUES (?1, ?2, ?3)
             ON CONFLICT(key) DO UPDATE SET value = ?2, updated_at = ?3",
            &[text_sv(key), SqliteValue::Integer(value), text_sv(now)],
        )?;
        Ok(())
    }

    /// Increment a cached statistic value atomically.
    ///
    /// Creates the key with value 1 if it doesn't exist.
    ///
    /// # Errors
    ///
    /// Returns an error if the operation fails.
    pub fn increment_cached_stat(&self, key: &str) -> Result<(), HistoryError> {
        let now = format_timestamp(Utc::now());
        self.conn.execute_with_params(
            "INSERT INTO stats_cache (key, value, updated_at) VALUES (?1, 1, ?2)
             ON CONFLICT(key) DO UPDATE SET value = value + 1, updated_at = ?2",
            &[text_sv(key), text_sv(now)],
        )?;
        Ok(())
    }

    // ========================================================================
    // Health Check
    // ========================================================================

    /// Perform a comprehensive database health check.
    ///
    /// Checks integrity, FTS sync, and reports statistics.
    ///
    /// # Errors
    ///
    /// Returns an error if any check query fails.
    pub fn check_health(&self) -> Result<CheckResult, HistoryError> {
        // Integrity check
        let integrity_row = self.conn.query_row("PRAGMA integrity_check")?;
        let integrity_check = sv_to_string(&integrity_row.values()[0]);
        let integrity_ok = integrity_check == "ok";

        // Foreign key check
        let fk_rows = self.conn.query("PRAGMA foreign_key_check")?;
        let foreign_key_violations = fk_rows.len();

        // Commands count
        let cmd_row = self.conn.query_row("SELECT COUNT(*) FROM commands")?;
        let commands_count = u64::try_from(sv_to_i64(&cmd_row.values()[0])).unwrap_or(0);

        // FrankenSQLite's FTS5 fallback does not reliably collapse COUNT(*)
        // over virtual tables to a single aggregate row, so count by scanning.
        let fts_count = u64::try_from(self.conn.query("SELECT rowid FROM commands_fts")?.len())
            .unwrap_or(u64::MAX);

        // Journal mode
        let jm_row = self.conn.query_row("PRAGMA journal_mode")?;
        let journal_mode = sv_to_string(&jm_row.values()[0]);

        // File sizes
        let file_size_bytes = self.file_size().unwrap_or(0);
        let wal_size_bytes = self.path.as_ref().map_or(0, |p| {
            // SQLite WAL files are named by appending "-wal" to the database path
            let wal_path = PathBuf::from(format!("{}-wal", p.display()));
            std::fs::metadata(&wal_path).map(|m| m.len()).unwrap_or(0)
        });

        // Schema version
        let schema_version = self.get_schema_version().unwrap_or(0);

        // Page info
        let ps_row = self.conn.query_row("PRAGMA page_size")?;
        let page_size = sv_to_i64(&ps_row.values()[0]);
        let pc_row = self.conn.query_row("PRAGMA page_count")?;
        let page_count = sv_to_i64(&pc_row.values()[0]);
        let fl_row = self.conn.query_row("PRAGMA freelist_count")?;
        let freelist_count = sv_to_i64(&fl_row.values()[0]);

        Ok(CheckResult {
            integrity_check,
            integrity_ok,
            foreign_key_violations,
            commands_count,
            fts_count,
            fts_in_sync: commands_count == fts_count,
            journal_mode,
            file_size_bytes,
            wal_size_bytes,
            schema_version,
            page_size: u32::try_from(page_size).unwrap_or(0),
            page_count: u64::try_from(page_count).unwrap_or(0),
            freelist_count: u64::try_from(freelist_count).unwrap_or(0),
        })
    }

    /// Rebuild the FTS (Full-Text Search) index from scratch.
    ///
    /// This is useful for recovering from FTS corruption or when the FTS
    /// index has become out of sync with the main commands table.
    ///
    /// # Returns
    ///
    /// Returns the number of commands re-indexed.
    ///
    /// # Errors
    ///
    /// Returns an error if the rebuild fails.
    pub fn rebuild_fts(&self) -> Result<u64, HistoryError> {
        // FrankenSQLite currently rejects recreating a live VTAB with the same
        // name while the DROP is still staged inside a transaction. Clear and
        // repopulate the existing FTS table instead of dropping/recreating it.
        self.conn
            .execute("DROP TRIGGER IF EXISTS commands_fts_insert")?;
        self.conn
            .execute("DROP TRIGGER IF EXISTS commands_fts_delete")?;
        self.conn
            .execute("DROP TRIGGER IF EXISTS commands_fts_update")?;

        self.conn.execute("DELETE FROM commands_fts")?;

        // fsqlite FTS5 does not support the control-column rebuild syntax, so
        // repopulate the index row-by-row.
        let rows = self.conn.query("SELECT id, command FROM commands")?;
        for row in &rows {
            let vals = row.values();
            self.conn.execute_with_params(
                "INSERT INTO commands_fts(rowid, command) VALUES (?1, ?2)",
                &[vals[0].clone(), vals[1].clone()],
            )?;
        }

        self.conn.execute(
            r"CREATE TRIGGER commands_fts_insert AFTER INSERT ON commands BEGIN
                INSERT INTO commands_fts(rowid, command) VALUES (new.id, new.command);
            END",
        )?;

        Ok(u64::try_from(self.conn.query("SELECT rowid FROM commands_fts")?.len()).unwrap_or(0))
    }

    /// Check and optionally repair database health issues.
    ///
    /// Performs `check_health` and attempts to fix recoverable issues:
    /// - FTS out of sync: rebuilds the FTS index
    ///
    /// # Returns
    ///
    /// Returns a tuple of (original health check, repairs made).
    ///
    /// # Errors
    ///
    /// Returns an error if health check or repairs fail.
    pub fn repair(&self) -> Result<(CheckResult, Vec<String>), HistoryError> {
        let health = self.check_health()?;
        let mut repairs = Vec::new();

        // Repair FTS if out of sync
        if !health.fts_in_sync {
            let reindexed = self.rebuild_fts()?;
            repairs.push(format!(
                "Rebuilt FTS index ({reindexed} commands re-indexed)"
            ));
        }

        Ok((health, repairs))
    }

    // ========================================================================
    // Backup
    // ========================================================================

    /// Create a backup of the database to the specified path.
    ///
    /// Uses `VACUUM INTO` for a consistent backup. Optionally compresses
    /// the output with gzip.
    ///
    /// # Errors
    ///
    /// Returns an error if the backup fails.
    pub fn backup(&self, output_path: &Path, compress: bool) -> Result<BackupResult, HistoryError> {
        use std::time::Instant;

        let start = Instant::now();

        // Checkpoint first to minimize WAL size
        self.checkpoint()?;

        if compress {
            // For compression, we need to vacuum to a temp file first
            let temp_path = output_path.with_extension("db.tmp");

            // VACUUM INTO creates a clean copy
            self.conn.execute_with_params(
                "VACUUM INTO ?1",
                &[text_sv(temp_path.to_string_lossy().to_string())],
            )?;

            // Compress the temp file to the final path
            let temp_file = std::fs::File::open(&temp_path)?;
            let final_file = std::fs::File::create(output_path)?;
            let mut encoder =
                flate2::write::GzEncoder::new(final_file, flate2::Compression::default());
            std::io::copy(&mut std::io::BufReader::new(temp_file), &mut encoder)?;
            encoder.finish()?;

            // Clean up temp file
            let _ = std::fs::remove_file(&temp_path);
        } else {
            // Direct VACUUM INTO
            self.conn.execute_with_params(
                "VACUUM INTO ?1",
                &[text_sv(output_path.to_string_lossy().to_string())],
            )?;
        }

        let backup_size_bytes = std::fs::metadata(output_path)?.len();
        #[allow(clippy::cast_possible_truncation)]
        let duration_ms = start.elapsed().as_millis() as u64;

        // Verify backup integrity (quick check)
        let verified = if compress {
            // Skip verification for compressed backups (would need to decompress)
            false
        } else {
            // Verify uncompressed backups via FrankenSQLite
            let path_str = output_path.to_string_lossy().to_string();
            Connection::open(&path_str)
                .and_then(|conn| conn.query_row("PRAGMA integrity_check"))
                .map(|row| sv_to_string(&row.values()[0]) == "ok")
                .unwrap_or(false)
        };

        Ok(BackupResult {
            backup_path: output_path.to_string_lossy().to_string(),
            backup_size_bytes,
            compressed: compress,
            duration_ms,
            verified,
        })
    }

    /// Access the underlying connection for advanced queries.
    ///
    /// This is primarily for testing and advanced use cases.
    #[must_use]
    pub const fn connection(&self) -> &Connection {
        &self.conn
    }

    /// Query commands for export with optional filtering.
    ///
    /// # Errors
    ///
    /// Returns an error if the query fails.
    pub fn query_commands_for_export(
        &self,
        options: &ExportOptions,
    ) -> Result<Vec<CommandEntry>, HistoryError> {
        let mut sql = String::from(
            "SELECT timestamp, agent_type, working_dir, command, outcome,
                    pack_id, pattern_name, rule_id, eval_duration_us, session_id,
                    exit_code, parent_command_id, hostname, allowlist_layer, bypass_code
             FROM commands WHERE 1=1",
        );
        let mut params: Vec<SqliteValue> = Vec::new();
        let mut param_idx = 1;

        if let Some(outcome) = &options.outcome_filter {
            write!(sql, " AND outcome = ?{param_idx}").unwrap();
            params.push(text_sv(outcome.as_str()));
            param_idx += 1;
        }

        if let Some(since) = &options.since {
            write!(sql, " AND timestamp >= ?{param_idx}").unwrap();
            params.push(text_sv(format_timestamp(*since)));
            param_idx += 1;
        }

        if let Some(until) = &options.until {
            write!(sql, " AND timestamp < ?{param_idx}").unwrap();
            params.push(text_sv(format_timestamp(*until)));
            param_idx += 1;
        }

        sql.push_str(" ORDER BY timestamp DESC");

        if let Some(limit) = options.limit {
            write!(sql, " LIMIT ?{param_idx}").unwrap();
            params.push(SqliteValue::Integer(
                i64::try_from(limit).unwrap_or(i64::MAX),
            ));
        }

        let rows = self.conn.query(&inline_params(&sql, &params))?;

        let mut entries = Vec::new();
        for row in &rows {
            let vals = row.values();
            let timestamp_str = sv_to_string(&vals[0]);
            let timestamp = DateTime::parse_from_rfc3339(&timestamp_str)
                .map_or_else(|_| Utc::now(), |dt| dt.with_timezone(&Utc));

            let outcome_str = sv_to_string(&vals[4]);
            let outcome = Outcome::parse(&outcome_str).unwrap_or(Outcome::Allow);

            let eval_duration_us = sv_to_i64(&vals[8]);

            entries.push(CommandEntry {
                timestamp,
                agent_type: sv_to_string(&vals[1]),
                working_dir: sv_to_string(&vals[2]),
                command: sv_to_string(&vals[3]),
                outcome,
                pack_id: sv_to_opt_string(&vals[5]),
                pattern_name: sv_to_opt_string(&vals[6]),
                rule_id: sv_to_opt_string(&vals[7]),
                eval_duration_us: u64::try_from(eval_duration_us).unwrap_or(0),
                session_id: sv_to_opt_string(&vals[9]),
                exit_code: match &vals[10] {
                    SqliteValue::Integer(i) => Some(i32::try_from(*i).unwrap_or(0)),
                    SqliteValue::Null => None,
                    _ => None,
                },
                parent_command_id: match &vals[11] {
                    SqliteValue::Integer(i) => Some(*i),
                    SqliteValue::Null => None,
                    _ => None,
                },
                hostname: sv_to_opt_string(&vals[12]),
                allowlist_layer: sv_to_opt_string(&vals[13]),
                bypass_code: sv_to_opt_string(&vals[14]),
            });
        }
        Ok(entries)
    }

    /// Export commands to JSON format.
    ///
    /// Returns a JSON object with metadata and commands array.
    ///
    /// # Errors
    ///
    /// Returns an error if the query or serialization fails.
    pub fn export_json<W: std::io::Write>(
        &self,
        writer: &mut W,
        options: &ExportOptions,
    ) -> Result<usize, HistoryError> {
        let entries = self.query_commands_for_export(options)?;
        let count = entries.len();

        let export = ExportedData {
            exported_at: Utc::now(),
            total_records: count,
            filters: ExportFilters {
                outcome: options.outcome_filter.map(|o| o.as_str().to_string()),
                since: options.since,
                until: options.until,
            },
            commands: entries,
        };

        serde_json::to_writer_pretty(writer, &export)
            .map_err(|e| HistoryError::Io(std::io::Error::other(e)))?;

        Ok(count)
    }

    /// Export commands to JSONL (JSON Lines) format for streaming.
    ///
    /// Each line is a valid JSON object representing one command.
    ///
    /// # Errors
    ///
    /// Returns an error if the query or serialization fails.
    pub fn export_jsonl<W: std::io::Write>(
        &self,
        writer: &mut W,
        options: &ExportOptions,
    ) -> Result<usize, HistoryError> {
        let entries = self.query_commands_for_export(options)?;
        let count = entries.len();

        for entry in &entries {
            serde_json::to_writer(&mut *writer, entry)
                .map_err(|e| HistoryError::Io(std::io::Error::other(e)))?;
            writeln!(writer)?;
        }

        Ok(count)
    }

    /// Export commands to CSV format.
    ///
    /// Includes a header row followed by data rows.
    ///
    /// # Errors
    ///
    /// Returns an error if the query or write fails.
    pub fn export_csv<W: std::io::Write>(
        &self,
        writer: &mut W,
        options: &ExportOptions,
    ) -> Result<usize, HistoryError> {
        let entries = self.query_commands_for_export(options)?;
        let count = entries.len();

        // Write header
        writeln!(
            writer,
            "timestamp,agent_type,working_dir,command,outcome,pack_id,pattern_name,eval_duration_us"
        )?;

        // Write data rows
        for entry in &entries {
            writeln!(
                writer,
                "{},{},{},{},{},{},{},{}",
                csv_escape(&format_timestamp(entry.timestamp)),
                csv_escape(&entry.agent_type),
                csv_escape(&entry.working_dir),
                csv_escape(&entry.command),
                entry.outcome.as_str(),
                entry.pack_id.as_deref().unwrap_or(""),
                entry.pattern_name.as_deref().unwrap_or(""),
                entry.eval_duration_us,
            )?;
        }

        Ok(count)
    }

    // ========================================================================
    // Pack Effectiveness Analysis Methods
    // ========================================================================

    /// Analyze pack effectiveness for the specified period.
    ///
    /// This analyzes patterns to identify:
    /// - High-value patterns (high volume, low bypass rate)
    /// - Potentially overly aggressive patterns (high bypass rate)
    /// - Inactive packs that never triggered
    /// - Potential coverage gaps
    ///
    /// # Arguments
    ///
    /// * `period_days` - Number of days to analyze
    /// * `enabled_packs` - List of currently enabled pack IDs
    ///
    /// # Errors
    ///
    /// Returns an error if any database query fails.
    pub fn analyze_pack_effectiveness(
        &self,
        period_days: u64,
        enabled_packs: &[&str],
    ) -> Result<PackEffectivenessAnalysis, HistoryError> {
        let now = Utc::now();
        let period_days_i64 = i64::try_from(period_days).unwrap_or(i64::MAX);
        let since = now - Duration::days(period_days_i64);
        let since_ts = format_timestamp(since);
        let end_ts = format_timestamp(now);

        // Get total commands for context
        let total_row = self.conn.query_row_with_params(
            "SELECT COUNT(*) FROM commands WHERE timestamp >= ?1 AND timestamp < ?2",
            &[text_sv(since_ts.clone()), text_sv(end_ts.clone())],
        )?;
        let total_commands = u64::try_from(sv_to_i64(&total_row.values()[0])).unwrap_or(0);

        // Query pattern effectiveness (denied + bypassed counts)
        let pattern_stats = self.query_pattern_effectiveness(&since_ts, &end_ts)?;

        // Categorize patterns by bypass rate
        let (high_value, aggressive) = Self::categorize_patterns(&pattern_stats);

        // Find inactive packs
        let active_packs = self.query_active_packs(&since_ts, &end_ts)?;
        let inactive_packs: Vec<String> = enabled_packs
            .iter()
            .filter(|pack| !active_packs.contains(&pack.to_string()))
            .map(std::string::ToString::to_string)
            .collect();

        // Find potential coverage gaps
        let potential_gaps = self.find_coverage_gaps(&since_ts, &end_ts)?;

        // Generate recommendations
        let recommendations = Self::generate_recommendations(
            &high_value,
            &aggressive,
            &inactive_packs,
            &potential_gaps,
        );

        Ok(PackEffectivenessAnalysis {
            period_days,
            analyzed_at: now,
            total_commands,
            high_value_patterns: high_value,
            potentially_aggressive: aggressive,
            inactive_packs,
            potential_gaps,
            recommendations,
        })
    }

    /// Query pattern effectiveness statistics.
    fn query_pattern_effectiveness(
        &self,
        since_ts: &str,
        end_ts: &str,
    ) -> Result<Vec<PatternEffectiveness>, HistoryError> {
        let mut patterns = Vec::new();
        let ts_params = &[text_sv(since_ts.to_string()), text_sv(end_ts.to_string())];

        // Get deny counts per pattern
        let mut deny_counts: HashMap<(String, Option<String>), u64> = HashMap::new();
        let deny_rows = self.conn.query(&inline_params(
            "SELECT pattern_name, pack_id, COUNT(*) FROM commands
             WHERE timestamp >= ?1 AND timestamp < ?2
             AND outcome = 'deny' AND pattern_name IS NOT NULL
             GROUP BY pattern_name, pack_id",
            ts_params,
        ))?;
        for row in &deny_rows {
            let vals = row.values();
            let pattern = sv_to_string(&vals[0]);
            let pack_id = sv_to_opt_string(&vals[1]);
            let count = sv_to_i64(&vals[2]);
            deny_counts.insert((pattern, pack_id), u64::try_from(count).unwrap_or(0));
        }

        // Get bypass counts per pattern
        let mut bypass_counts: HashMap<(String, Option<String>), u64> = HashMap::new();
        let bypass_rows = self.conn.query(&inline_params(
            "SELECT pattern_name, pack_id, COUNT(*) FROM commands
             WHERE timestamp >= ?1 AND timestamp < ?2
             AND outcome = 'bypass' AND pattern_name IS NOT NULL
             GROUP BY pattern_name, pack_id",
            ts_params,
        ))?;
        for row in &bypass_rows {
            let vals = row.values();
            let pattern = sv_to_string(&vals[0]);
            let pack_id = sv_to_opt_string(&vals[1]);
            let count = sv_to_i64(&vals[2]);
            bypass_counts.insert((pattern, pack_id), u64::try_from(count).unwrap_or(0));
        }

        // Merge into PatternEffectiveness structs
        let mut all_patterns: HashMap<(String, Option<String>), (u64, u64)> = HashMap::new();
        for (key, count) in deny_counts {
            all_patterns.entry(key).or_insert((0, 0)).0 = count;
        }
        for (key, count) in bypass_counts {
            all_patterns.entry(key).or_insert((0, 0)).1 = count;
        }

        for ((pattern, pack_id), (denied, bypassed)) in all_patterns {
            let total = denied + bypassed;
            #[allow(clippy::cast_precision_loss)]
            let bypass_rate = if total > 0 {
                (bypassed as f64 / total as f64) * 100.0
            } else {
                0.0
            };

            patterns.push(PatternEffectiveness {
                pattern,
                pack_id,
                total_triggers: total,
                denied_count: denied,
                bypassed_count: bypassed,
                bypass_rate,
            });
        }

        // Sort by total triggers descending
        patterns.sort_by_key(|p| std::cmp::Reverse(p.total_triggers));

        Ok(patterns)
    }

    /// Categorize patterns into high-value and potentially aggressive.
    fn categorize_patterns(
        patterns: &[PatternEffectiveness],
    ) -> (Vec<PatternEffectiveness>, Vec<PatternEffectiveness>) {
        // Thresholds
        const HIGH_BYPASS_THRESHOLD: f64 = 20.0; // 20% bypass rate = potentially aggressive
        const MIN_TRIGGERS_FOR_AGGRESSIVE: u64 = 5; // Need enough data to judge
        const MIN_TRIGGERS_FOR_HIGH_VALUE: u64 = 10; // High volume threshold
        const LOW_BYPASS_THRESHOLD: f64 = 5.0; // Low bypass rate for high-value

        let mut high_value = Vec::new();
        let mut aggressive = Vec::new();

        for p in patterns {
            // High value: high volume + low bypass rate
            if p.total_triggers >= MIN_TRIGGERS_FOR_HIGH_VALUE
                && p.bypass_rate <= LOW_BYPASS_THRESHOLD
            {
                high_value.push(p.clone());
            }

            // Potentially aggressive: high bypass rate
            if p.total_triggers >= MIN_TRIGGERS_FOR_AGGRESSIVE
                && p.bypass_rate >= HIGH_BYPASS_THRESHOLD
            {
                aggressive.push(p.clone());
            }
        }

        // Sort high-value by volume descending
        high_value.sort_by_key(|p| std::cmp::Reverse(p.total_triggers));
        // Sort aggressive by bypass rate descending
        aggressive.sort_by(|a, b| {
            b.bypass_rate
                .partial_cmp(&a.bypass_rate)
                .unwrap_or(std::cmp::Ordering::Equal)
        });

        (high_value, aggressive)
    }

    /// Query active packs (packs that triggered at least once).
    fn query_active_packs(
        &self,
        since_ts: &str,
        end_ts: &str,
    ) -> Result<Vec<String>, HistoryError> {
        let rows = self.conn.query(&inline_params(
            "SELECT DISTINCT pack_id FROM commands
             WHERE timestamp >= ?1 AND timestamp < ?2
             AND pack_id IS NOT NULL",
            &[text_sv(since_ts.to_string()), text_sv(end_ts.to_string())],
        ))?;
        let mut packs = Vec::new();
        for row in &rows {
            packs.push(sv_to_string(&row.values()[0]));
        }
        Ok(packs)
    }

    /// Find potential coverage gaps (dangerous commands that were allowed).
    fn find_coverage_gaps(
        &self,
        since_ts: &str,
        end_ts: &str,
    ) -> Result<Vec<PotentialGap>, HistoryError> {
        let mut gaps = Vec::new();

        // Heuristic patterns for potentially dangerous allowed commands
        let dangerous_patterns = [
            ("--force", "Force flag used"),
            ("--hard", "Hard reset/operation"),
            ("-rf", "Recursive force delete"),
            ("prune", "Prune operation"),
            ("DROP", "SQL DROP statement"),
            ("DELETE FROM", "SQL DELETE statement"),
            ("TRUNCATE", "SQL TRUNCATE statement"),
            ("rm -r", "Recursive remove"),
            ("chmod 777", "World-writable permissions"),
        ];

        let rows = self.conn.query(&inline_params(
            "SELECT command, timestamp, working_dir FROM commands
             WHERE timestamp >= ?1 AND timestamp < ?2
             AND outcome = 'allow'
             ORDER BY timestamp DESC
             LIMIT 1000",
            &[text_sv(since_ts.to_string()), text_sv(end_ts.to_string())],
        ))?;

        for row in &rows {
            let vals = row.values();
            let command = sv_to_string(&vals[0]);
            let timestamp_str = sv_to_string(&vals[1]);
            let working_dir = sv_to_opt_string(&vals[2]);
            let command_lower = command.to_lowercase();

            for (pattern, reason) in &dangerous_patterns {
                if command_lower.contains(&pattern.to_lowercase()) {
                    // Parse timestamp
                    let timestamp = chrono::DateTime::parse_from_rfc3339(&timestamp_str)
                        .map_or_else(|_| Utc::now(), |dt| dt.with_timezone(&Utc));

                    gaps.push(PotentialGap {
                        command: command.clone(),
                        reason: reason.to_string(),
                        timestamp,
                        working_dir: working_dir.clone(),
                    });
                    break; // Only report each command once
                }
            }
        }

        // Limit to top 20 gaps
        gaps.truncate(20);
        Ok(gaps)
    }

    /// Generate recommendations based on analysis.
    fn generate_recommendations(
        high_value: &[PatternEffectiveness],
        aggressive: &[PatternEffectiveness],
        inactive_packs: &[String],
        gaps: &[PotentialGap],
    ) -> Vec<PackRecommendation> {
        let mut recommendations = Vec::new();

        // Recommend relaxing aggressive patterns
        for p in aggressive.iter().take(3) {
            recommendations.push(PackRecommendation {
                recommendation_type: RecommendationType::RelaxPattern,
                description: format!(
                    "Pattern '{}' has a {:.1}% bypass rate ({} of {} triggers bypassed). \
                     Consider adding an allowlist entry or refining the pattern.",
                    p.pattern, p.bypass_rate, p.bypassed_count, p.total_triggers
                ),
                suggested_action: Some(format!(
                    "dcg allow {}:{} --reason \"High bypass rate\"",
                    p.pack_id.as_deref().unwrap_or("unknown"),
                    p.pattern
                )),
                config_change: None,
                related_pattern: Some(p.pattern.clone()),
                priority: 8,
            });
        }

        // Recommend disabling inactive packs
        for pack in inactive_packs.iter().take(3) {
            recommendations.push(PackRecommendation {
                recommendation_type: RecommendationType::DisablePack,
                description: format!(
                    "Pack '{pack}' is enabled but has not triggered any rules. \
                     Consider disabling it to reduce overhead."
                ),
                suggested_action: None,
                config_change: Some(format!(
                    "[packs.{}]\nenabled = false",
                    pack.replace('.', "_")
                )),
                related_pattern: Some(pack.clone()),
                priority: 3,
            });
        }

        // Recommend adding coverage for gaps
        if !gaps.is_empty() {
            let gap_count = gaps.len();
            let example = &gaps[0];
            recommendations.push(PackRecommendation {
                recommendation_type: RecommendationType::AddPattern,
                description: format!(
                    "Found {} potentially dangerous commands that were allowed. \
                     Example: '{}' ({})",
                    gap_count,
                    truncate_string(&example.command, 50),
                    example.reason
                ),
                suggested_action: Some("Review allowed commands with `dcg history export --outcome allow` and consider adding patterns".to_string()),
                config_change: None,
                related_pattern: None,
                priority: 7,
            });
        }

        // Praise high-value patterns
        if !high_value.is_empty() {
            let total_blocked: u64 = high_value.iter().map(|p| p.denied_count).sum();
            recommendations.push(PackRecommendation {
                recommendation_type: RecommendationType::Tuning,
                description: format!(
                    "{} high-value patterns blocked {} potentially destructive commands with minimal false positives.",
                    high_value.len(),
                    total_blocked
                ),
                suggested_action: None,
                config_change: None,
                related_pattern: None,
                priority: 1,
            });
        }

        // Sort by priority descending
        recommendations.sort_by_key(|r| std::cmp::Reverse(r.priority));
        recommendations
    }

    // ========================================================================
    // Rule-Level Metrics Queries
    // ========================================================================

    /// Get aggregated metrics for all rules.
    ///
    /// Returns per-rule statistics including hit counts, override rates, and trends.
    ///
    /// # Arguments
    ///
    /// * `since` - Optional start time (defaults to all time)
    /// * `limit` - Maximum number of rules to return (defaults to 100)
    ///
    /// # Errors
    ///
    /// Returns an error if the query fails.
    pub fn get_rule_metrics(
        &self,
        since: Option<DateTime<Utc>>,
        limit: usize,
    ) -> Result<Vec<RuleMetrics>, HistoryError> {
        let since_ts = since.map_or_else(
            || "1970-01-01T00:00:00Z".to_string(),
            |dt| dt.format("%Y-%m-%dT%H:%M:%S%.3fZ").to_string(),
        );

        // Query for main aggregates
        let limit_i64 = i64::try_from(limit).unwrap_or(100);
        // fsqlite does not support SUM(CASE WHEN ...) with GROUP BY.
        // Use two separate queries and merge bypass counts in Rust.
        let rows = self.conn.query(&inline_params(
            r"SELECT
                rule_id,
                COUNT(*) as total_hits,
                MIN(timestamp) as first_seen,
                MAX(timestamp) as last_seen,
                COUNT(DISTINCT command_hash) as unique_commands
             FROM commands
             WHERE rule_id IS NOT NULL
               AND timestamp >= ?1
             GROUP BY rule_id
             ORDER BY total_hits DESC
             LIMIT ?2",
            &[text_sv(since_ts.clone()), SqliteValue::Integer(limit_i64)],
        ))?;
        // Bypass counts per rule
        let bypass_rows = self.conn.query(&inline_params(
            "SELECT rule_id, COUNT(*) FROM commands WHERE rule_id IS NOT NULL AND outcome = 'bypass' AND timestamp >= ?1 GROUP BY rule_id",
            &[text_sv(since_ts)],
        ))?;
        let bypass_map: HashMap<String, i64> = bypass_rows
            .iter()
            .map(|r| (sv_to_string(&r.values()[0]), sv_to_i64(&r.values()[1])))
            .collect();

        let mut metrics = Vec::new();
        for row in &rows {
            let vals = row.values();
            let rule_id = sv_to_string(&vals[0]);
            let total_hits = sv_to_i64(&vals[1]);
            let first_seen_str = sv_to_string(&vals[2]);
            let last_seen_str = sv_to_string(&vals[3]);
            let unique_commands = sv_to_i64(&vals[4]);

            let total_hits = u64::try_from(total_hits).unwrap_or(0);
            let overrides_i64 = bypass_map.get(&rule_id).copied().unwrap_or(0);
            let overrides = u64::try_from(overrides_i64).unwrap_or(0);
            let unique_commands = u64::try_from(unique_commands).unwrap_or(0);

            #[allow(clippy::cast_precision_loss)]
            let override_rate = if total_hits > 0 {
                (overrides as f64 / total_hits as f64) * 100.0
            } else {
                0.0
            };

            let first_seen = chrono::DateTime::parse_from_rfc3339(&first_seen_str)
                .map_or_else(|_| Utc::now(), |dt| dt.with_timezone(&Utc));
            let last_seen = chrono::DateTime::parse_from_rfc3339(&last_seen_str)
                .map_or_else(|_| Utc::now(), |dt| dt.with_timezone(&Utc));

            // Calculate trend with week-over-week comparison
            let (trend, previous_period_hits, change_percentage, is_anomaly) =
                self.calculate_rule_trend(&rule_id, total_hits);

            metrics.push(RuleMetrics {
                rule_id,
                total_hits,
                allowlist_overrides: overrides,
                override_rate,
                first_seen,
                last_seen,
                unique_commands,
                trend,
                is_noisy: override_rate >= RuleMetrics::NOISY_THRESHOLD,
                previous_period_hits,
                change_percentage,
                is_anomaly,
            });
        }

        Ok(metrics)
    }

    /// Get metrics for a specific rule.
    ///
    /// # Errors
    ///
    /// Returns an error if the query fails.
    pub fn get_rule_metrics_for_rule(
        &self,
        rule_id: &str,
    ) -> Result<Option<RuleMetrics>, HistoryError> {
        // fsqlite does not support SUM(CASE WHEN ...) or scalar subqueries
        // mixed with aggregates. Use two separate queries.
        let params = &[text_sv(rule_id.to_string())];
        let result = self.conn.query_row(&inline_params(
            r"SELECT
                COUNT(*) as total_hits,
                MIN(timestamp) as first_seen,
                MAX(timestamp) as last_seen,
                COUNT(DISTINCT command_hash) as unique_commands
             FROM commands
             WHERE rule_id = ?1",
            params,
        ));

        match result {
            Ok(row) => {
                let vals = row.values();
                let total_hits_i64 = sv_to_i64(&vals[0]);

                if total_hits_i64 == 0 {
                    return Ok(None);
                }

                let total_hits = u64::try_from(total_hits_i64).unwrap_or(0);
                // Separate query for bypass count
                let bypass_count = self
                    .conn
                    .query_row(&inline_params(
                        "SELECT COUNT(*) FROM commands WHERE rule_id = ?1 AND outcome = 'bypass'",
                        params,
                    ))
                    .map(|r| sv_to_i64(&r.values()[0]))
                    .unwrap_or(0);
                let overrides = u64::try_from(bypass_count).unwrap_or(0);
                let unique_commands = u64::try_from(sv_to_i64(&vals[3])).unwrap_or(0);

                let first_seen_opt = sv_to_opt_string(&vals[1]);
                let last_seen_opt = sv_to_opt_string(&vals[2]);

                #[allow(clippy::cast_precision_loss)]
                let override_rate = if total_hits > 0 {
                    (overrides as f64 / total_hits as f64) * 100.0
                } else {
                    0.0
                };

                let first_seen = first_seen_opt
                    .and_then(|s| chrono::DateTime::parse_from_rfc3339(&s).ok())
                    .map_or_else(Utc::now, |dt| dt.with_timezone(&Utc));
                let last_seen = last_seen_opt
                    .and_then(|s| chrono::DateTime::parse_from_rfc3339(&s).ok())
                    .map_or_else(Utc::now, |dt| dt.with_timezone(&Utc));

                let (trend, previous_period_hits, change_percentage, is_anomaly) =
                    self.calculate_rule_trend(rule_id, total_hits);

                Ok(Some(RuleMetrics {
                    rule_id: rule_id.to_string(),
                    total_hits,
                    allowlist_overrides: overrides,
                    override_rate,
                    first_seen,
                    last_seen,
                    unique_commands,
                    trend,
                    is_noisy: override_rate >= RuleMetrics::NOISY_THRESHOLD,
                    previous_period_hits,
                    change_percentage,
                    is_anomaly,
                }))
            }
            Err(FrankenError::QueryReturnedNoRows) => Ok(None),
            Err(e) => Err(HistoryError::Sqlite(e)),
        }
    }

    /// Get the noisiest rules (highest override rate).
    ///
    /// # Arguments
    ///
    /// * `limit` - Maximum number of rules to return
    ///
    /// # Errors
    ///
    /// Returns an error if the query fails.
    pub fn get_noisiest_rules(&self, limit: usize) -> Result<Vec<RuleMetrics>, HistoryError> {
        let min_hits = i64::try_from(RuleMetrics::MIN_HITS_FOR_TREND).unwrap_or(5);

        // fsqlite does not support SUM(CASE WHEN ...) with GROUP BY.
        // Use two queries and merge bypass counts in Rust, then sort.
        let rows = self.conn.query(&inline_params(
            r"SELECT
                rule_id,
                COUNT(*) as total_hits,
                MIN(timestamp) as first_seen,
                MAX(timestamp) as last_seen,
                COUNT(DISTINCT command_hash) as unique_commands
             FROM commands
             WHERE rule_id IS NOT NULL
             GROUP BY rule_id
             HAVING total_hits >= ?1",
            &[SqliteValue::Integer(min_hits)],
        ))?;
        let bypass_rows = self.conn.query(
            "SELECT rule_id, COUNT(*) FROM commands WHERE rule_id IS NOT NULL AND outcome = 'bypass' GROUP BY rule_id",
        )?;
        let bypass_map: HashMap<String, i64> = bypass_rows
            .iter()
            .map(|r| (sv_to_string(&r.values()[0]), sv_to_i64(&r.values()[1])))
            .collect();

        let mut metrics = Vec::new();
        for row in &rows {
            let vals = row.values();
            let rule_id = sv_to_string(&vals[0]);
            let total_hits = sv_to_i64(&vals[1]);
            let first_seen_str = sv_to_string(&vals[2]);
            let last_seen_str = sv_to_string(&vals[3]);
            let unique_commands = sv_to_i64(&vals[4]);

            let total_hits = u64::try_from(total_hits).unwrap_or(0);
            let overrides_i64 = bypass_map.get(&rule_id).copied().unwrap_or(0);
            let overrides = u64::try_from(overrides_i64).unwrap_or(0);
            let unique_commands = u64::try_from(unique_commands).unwrap_or(0);

            #[allow(clippy::cast_precision_loss)]
            let override_rate = if total_hits > 0 {
                (overrides as f64 / total_hits as f64) * 100.0
            } else {
                0.0
            };

            let first_seen = chrono::DateTime::parse_from_rfc3339(&first_seen_str)
                .map_or_else(|_| Utc::now(), |dt| dt.with_timezone(&Utc));
            let last_seen = chrono::DateTime::parse_from_rfc3339(&last_seen_str)
                .map_or_else(|_| Utc::now(), |dt| dt.with_timezone(&Utc));

            let (trend, previous_period_hits, change_percentage, is_anomaly) =
                self.calculate_rule_trend(&rule_id, total_hits);

            metrics.push(RuleMetrics {
                rule_id,
                total_hits,
                allowlist_overrides: overrides,
                override_rate,
                first_seen,
                last_seen,
                unique_commands,
                trend,
                is_noisy: override_rate >= RuleMetrics::NOISY_THRESHOLD,
                previous_period_hits,
                change_percentage,
                is_anomaly,
            });
        }

        // Sort by override rate descending and apply limit (done in Rust since
        // the SQL no longer handles the bypass-rate-based ordering)
        metrics.sort_by(|a, b| {
            b.override_rate
                .partial_cmp(&a.override_rate)
                .unwrap_or(std::cmp::Ordering::Equal)
        });
        metrics.truncate(limit);

        Ok(metrics)
    }

    /// Calculate trend by comparing recent vs previous period.
    ///
    /// Returns (trend, `previous_period_hits`, `change_percentage`, `is_anomaly`).
    fn calculate_rule_trend(&self, rule_id: &str, total_hits: u64) -> (RuleTrend, u64, f64, bool) {
        if total_hits < RuleMetrics::MIN_HITS_FOR_TREND {
            return (RuleTrend::Stable, 0, 0.0, false);
        }

        let now = Utc::now();
        let one_week_ago = now - chrono::Duration::days(7);
        let two_weeks_ago = now - chrono::Duration::days(14);

        let recent_ts = one_week_ago.format("%Y-%m-%dT%H:%M:%S%.3fZ").to_string();
        let previous_ts = two_weeks_ago.format("%Y-%m-%dT%H:%M:%S%.3fZ").to_string();
        let now_ts = now.format("%Y-%m-%dT%H:%M:%S%.3fZ").to_string();

        // Count recent period
        let recent_count: i64 = self.conn.query_row_with_params(
            "SELECT COUNT(*) FROM commands WHERE rule_id = ?1 AND timestamp >= ?2 AND timestamp < ?3",
            &[
                text_sv(rule_id.to_string()),
                text_sv(recent_ts.clone()),
                text_sv(now_ts),
            ],
        ).map(|row| sv_to_i64(&row.values()[0])).unwrap_or(0);

        // Count previous period
        let previous_count: i64 = self.conn.query_row_with_params(
            "SELECT COUNT(*) FROM commands WHERE rule_id = ?1 AND timestamp >= ?2 AND timestamp < ?3",
            &[
                text_sv(rule_id.to_string()),
                text_sv(previous_ts),
                text_sv(recent_ts),
            ],
        ).map(|row| sv_to_i64(&row.values()[0])).unwrap_or(0);

        let previous_hits = u64::try_from(previous_count).unwrap_or(0);

        if previous_count == 0 {
            // No previous data - can't determine trend percentage, but can be anomaly if new
            let is_anomaly = recent_count > 10; // Treat new rules with many hits as anomalous
            return (RuleTrend::Stable, 0, 0.0, is_anomaly);
        }

        #[allow(clippy::cast_precision_loss)]
        let change_percentage =
            ((recent_count as f64 - previous_count as f64) / previous_count as f64) * 100.0;
        let is_anomaly = change_percentage >= RuleMetrics::ANOMALY_THRESHOLD;

        let trend = if change_percentage > (RuleMetrics::TREND_THRESHOLD * 100.0) {
            RuleTrend::Increasing
        } else if change_percentage < -(RuleMetrics::TREND_THRESHOLD * 100.0) {
            RuleTrend::Decreasing
        } else {
            RuleTrend::Stable
        };

        (trend, previous_hits, change_percentage, is_anomaly)
    }

    // ========================================================================
    // Suggestion Audit Logging
    // ========================================================================

    /// Log a suggestion audit entry to the database.
    ///
    /// Records when a user accepts, modifies, or rejects a suggested allowlist pattern.
    /// This provides traceability for how the allowlist evolved over time.
    ///
    /// # Errors
    ///
    /// Returns an error if the insert fails.
    pub fn log_suggestion_audit(&self, entry: &SuggestionAuditEntry) -> Result<i64, HistoryError> {
        let timestamp = entry.timestamp.format("%Y-%m-%dT%H:%M:%S%.3fZ").to_string();
        let cluster_frequency = i64::try_from(entry.cluster_frequency).unwrap_or(i64::MAX);
        let unique_variants = i64::try_from(entry.unique_variants).unwrap_or(i64::MAX);

        self.conn.execute_with_params(
            r"INSERT INTO suggestion_audit (
                timestamp, action, pattern, final_pattern, risk_level, risk_score,
                confidence_tier, confidence_points, cluster_frequency, unique_variants,
                sample_commands, rule_id, session_id, working_dir
            ) VALUES (
                ?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14
            )",
            &[
                text_sv(timestamp),
                text_sv(entry.action.as_str()),
                text_sv(entry.pattern.clone()),
                opt_string_to_sv(entry.final_pattern.as_ref()),
                text_sv(entry.risk_level.clone()),
                SqliteValue::Float(f64::from(entry.risk_score)),
                text_sv(entry.confidence_tier.clone()),
                SqliteValue::Integer(i64::from(entry.confidence_points)),
                SqliteValue::Integer(cluster_frequency),
                SqliteValue::Integer(unique_variants),
                text_sv(entry.sample_commands.clone()),
                opt_string_to_sv(entry.rule_id.as_ref()),
                opt_string_to_sv(entry.session_id.as_ref()),
                opt_string_to_sv(entry.working_dir.as_ref()),
            ],
        )?;

        let row = self
            .conn
            .query_row("SELECT max(id) FROM suggestion_audit")?;
        Ok(sv_to_i64(&row.values()[0]))
    }

    /// Count suggestion audit entries in the database.
    ///
    /// # Errors
    ///
    /// Returns an error if the query fails.
    pub fn count_suggestion_audits(&self) -> Result<u64, HistoryError> {
        let count: i64 = self
            .conn
            .query_row("SELECT COUNT(*) FROM suggestion_audit")
            .map(|row| sv_to_i64(&row.values()[0]))
            .map_err(HistoryError::Sqlite)?;
        Ok(u64::try_from(count).unwrap_or(0))
    }

    /// Query recent suggestion audit entries.
    ///
    /// # Arguments
    ///
    /// * `limit` - Maximum number of entries to return
    /// * `action_filter` - Optional filter by action type
    ///
    /// # Errors
    ///
    /// Returns an error if the query fails.
    pub fn query_suggestion_audits(
        &self,
        limit: usize,
        action_filter: Option<SuggestionAction>,
    ) -> Result<Vec<SuggestionAuditEntry>, HistoryError> {
        let mut sql = String::from(
            "SELECT timestamp, action, pattern, final_pattern, risk_level, risk_score,
                    confidence_tier, confidence_points, cluster_frequency, unique_variants,
                    sample_commands, rule_id, session_id, working_dir
             FROM suggestion_audit",
        );

        let mut params: Vec<SqliteValue> = Vec::new();
        let mut param_idx = 1;

        if let Some(action) = action_filter {
            write!(sql, " WHERE action = ?{param_idx}").unwrap();
            params.push(text_sv(action.as_str()));
            param_idx += 1;
        }

        write!(sql, " ORDER BY timestamp DESC LIMIT ?{param_idx}").unwrap();
        params.push(SqliteValue::Integer(
            i64::try_from(limit).unwrap_or(i64::MAX),
        ));

        let rows = self.conn.query(&inline_params(&sql, &params))?;

        let mut entries = Vec::new();
        for row in &rows {
            let vals = row.values();
            let timestamp_str = sv_to_string(&vals[0]);
            let timestamp = DateTime::parse_from_rfc3339(&timestamp_str)
                .map_or_else(|_| Utc::now(), |dt| dt.with_timezone(&Utc));

            let action_str = sv_to_string(&vals[1]);
            let action = SuggestionAction::parse(&action_str).unwrap_or(SuggestionAction::Accepted);

            let cluster_frequency = sv_to_i64(&vals[8]);
            let unique_variants = sv_to_i64(&vals[9]);

            entries.push(SuggestionAuditEntry {
                timestamp,
                action,
                pattern: sv_to_string(&vals[2]),
                final_pattern: sv_to_opt_string(&vals[3]),
                risk_level: sv_to_string(&vals[4]),
                risk_score: sv_to_f32(&vals[5]),
                confidence_tier: sv_to_string(&vals[6]),
                confidence_points: sv_to_i32(&vals[7]),
                cluster_frequency: usize::try_from(cluster_frequency).unwrap_or(0),
                unique_variants: usize::try_from(unique_variants).unwrap_or(0),
                sample_commands: sv_to_string(&vals[10]),
                rule_id: sv_to_opt_string(&vals[11]),
                session_id: sv_to_opt_string(&vals[12]),
                working_dir: sv_to_opt_string(&vals[13]),
            });
        }
        Ok(entries)
    }

    // ========================================================================
    // Interactive Allowlist Audit Logging
    // ========================================================================

    /// Log an interactive allowlist audit entry to the database.
    ///
    /// Records when a user adds an interactive allowlist entry from CLI flows.
    ///
    /// # Errors
    ///
    /// Returns an error if the insert fails.
    pub fn log_interactive_allowlist_audit(
        &self,
        entry: &InteractiveAllowlistAuditEntry,
    ) -> Result<i64, HistoryError> {
        let timestamp = entry.timestamp.format("%Y-%m-%dT%H:%M:%S%.3fZ").to_string();

        self.conn.execute_with_params(
            r"INSERT INTO interactive_allowlist_audit (
                timestamp, command, pattern_added, option_type, option_detail,
                config_file, cwd, user
            ) VALUES (
                ?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8
            )",
            &[
                text_sv(timestamp),
                text_sv(entry.command.clone()),
                text_sv(entry.pattern_added.clone()),
                text_sv(entry.option_type.as_str()),
                opt_string_to_sv(entry.option_detail.as_ref()),
                text_sv(entry.config_file.clone()),
                opt_string_to_sv(entry.cwd.as_ref()),
                opt_string_to_sv(entry.user.as_ref()),
            ],
        )?;

        let row = self
            .conn
            .query_row("SELECT max(id) FROM interactive_allowlist_audit")?;
        Ok(sv_to_i64(&row.values()[0]))
    }

    /// Count interactive allowlist audit entries in the database.
    ///
    /// # Errors
    ///
    /// Returns an error if the query fails.
    pub fn count_interactive_allowlist_audits(&self) -> Result<u64, HistoryError> {
        let count: i64 = self
            .conn
            .query_row("SELECT COUNT(*) FROM interactive_allowlist_audit")
            .map(|row| sv_to_i64(&row.values()[0]))
            .map_err(HistoryError::Sqlite)?;
        Ok(u64::try_from(count).unwrap_or(0))
    }

    /// Query recent interactive allowlist audit entries.
    ///
    /// # Arguments
    ///
    /// * `limit` - Maximum number of entries to return
    /// * `option_type_filter` - Optional filter by option type
    ///
    /// # Errors
    ///
    /// Returns an error if the query fails.
    pub fn query_interactive_allowlist_audits(
        &self,
        limit: usize,
        option_type_filter: Option<InteractiveAllowlistOptionType>,
    ) -> Result<Vec<InteractiveAllowlistAuditEntry>, HistoryError> {
        let mut sql = String::from(
            "SELECT timestamp, command, pattern_added, option_type, option_detail,
                    config_file, cwd, user
             FROM interactive_allowlist_audit",
        );

        let mut params: Vec<SqliteValue> = Vec::new();
        let mut param_idx = 1;

        if let Some(option_type) = option_type_filter {
            write!(sql, " WHERE option_type = ?{param_idx}").unwrap();
            params.push(text_sv(option_type.as_str()));
            param_idx += 1;
        }

        write!(sql, " ORDER BY timestamp DESC LIMIT ?{param_idx}").unwrap();
        params.push(SqliteValue::Integer(
            i64::try_from(limit).unwrap_or(i64::MAX),
        ));

        let rows = self.conn.query(&inline_params(&sql, &params))?;

        let mut entries = Vec::new();
        for row in &rows {
            let vals = row.values();
            let timestamp_str = sv_to_string(&vals[0]);
            let timestamp = DateTime::parse_from_rfc3339(&timestamp_str)
                .map_or_else(|_| Utc::now(), |dt| dt.with_timezone(&Utc));

            let option_type = InteractiveAllowlistOptionType::parse(&sv_to_string(&vals[3]))
                .unwrap_or(InteractiveAllowlistOptionType::Exact);

            entries.push(InteractiveAllowlistAuditEntry {
                timestamp,
                command: sv_to_string(&vals[1]),
                pattern_added: sv_to_string(&vals[2]),
                option_type,
                option_detail: sv_to_opt_string(&vals[4]),
                config_file: sv_to_string(&vals[5]),
                cwd: sv_to_opt_string(&vals[6]),
                user: sv_to_opt_string(&vals[7]),
            });
        }

        Ok(entries)
    }
}

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

/// Options for export operations.
#[derive(Debug, Clone, Default)]
pub struct ExportOptions {
    /// Filter by outcome (allow, deny, warn, bypass).
    pub outcome_filter: Option<Outcome>,
    /// Include only commands since this timestamp.
    pub since: Option<DateTime<Utc>>,
    /// Include only commands until this timestamp.
    pub until: Option<DateTime<Utc>>,
    /// Maximum number of records to export.
    pub limit: Option<usize>,
}

/// Exported data container with metadata.
#[derive(Debug, Serialize)]
pub struct ExportedData {
    /// When the export was generated.
    pub exported_at: DateTime<Utc>,
    /// Total number of records exported.
    pub total_records: usize,
    /// Filters applied to the export.
    pub filters: ExportFilters,
    /// The exported commands.
    pub commands: Vec<CommandEntry>,
}

/// Filters applied during export.
#[derive(Debug, Serialize)]
pub struct ExportFilters {
    /// Outcome filter if any.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub outcome: Option<String>,
    /// Since timestamp if any.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub since: Option<DateTime<Utc>>,
    /// Until timestamp if any.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub until: Option<DateTime<Utc>>,
}

// ============================================================================
// Pack Effectiveness Analysis Types
// ============================================================================

/// Pattern effectiveness statistics with bypass analysis.
#[derive(Debug, Clone, Serialize)]
pub struct PatternEffectiveness {
    /// Pattern name.
    pub pattern: String,
    /// Pack ID the pattern belongs to.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub pack_id: Option<String>,
    /// Total times this pattern triggered (deny + bypass).
    pub total_triggers: u64,
    /// Times the pattern blocked a command (deny).
    pub denied_count: u64,
    /// Times the pattern was bypassed (allow-once).
    pub bypassed_count: u64,
    /// Bypass rate as a percentage (0.0-100.0).
    pub bypass_rate: f64,
}

/// A potential coverage gap where dangerous commands were allowed.
#[derive(Debug, Clone, Serialize)]
pub struct PotentialGap {
    /// The command that was allowed but may be dangerous.
    pub command: String,
    /// Why this command may be a gap (heuristic match).
    pub reason: String,
    /// When this command was executed.
    pub timestamp: DateTime<Utc>,
    /// Working directory where command was executed.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub working_dir: Option<String>,
}

/// Type of recommendation for pack configuration.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum RecommendationType {
    /// Consider relaxing an overly aggressive pattern.
    RelaxPattern,
    /// Consider enabling a currently disabled pack.
    EnablePack,
    /// Consider disabling an unused pack.
    DisablePack,
    /// Add a new pattern to cover a gap.
    AddPattern,
    /// General tuning suggestion.
    Tuning,
}

/// An actionable recommendation for improving pack configuration.
#[derive(Debug, Clone, Serialize)]
pub struct PackRecommendation {
    /// Type of recommendation.
    #[serde(rename = "type")]
    pub recommendation_type: RecommendationType,
    /// Human-readable description.
    pub description: String,
    /// Suggested action to take.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub suggested_action: Option<String>,
    /// Suggested config change (TOML snippet).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub config_change: Option<String>,
    /// Pattern or pack this relates to.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub related_pattern: Option<String>,
    /// Priority score (higher = more important).
    pub priority: u8,
}

/// Complete pack effectiveness analysis result.
#[derive(Debug, Clone, Serialize)]
pub struct PackEffectivenessAnalysis {
    /// Analysis period in days.
    pub period_days: u64,
    /// When this analysis was generated.
    pub analyzed_at: DateTime<Utc>,
    /// Total commands analyzed.
    pub total_commands: u64,
    /// High-value patterns (high volume, low bypass rate).
    pub high_value_patterns: Vec<PatternEffectiveness>,
    /// Potentially overly aggressive patterns (high bypass rate).
    pub potentially_aggressive: Vec<PatternEffectiveness>,
    /// Enabled packs that never triggered.
    pub inactive_packs: Vec<String>,
    /// Potential coverage gaps (dangerous commands that were allowed).
    pub potential_gaps: Vec<PotentialGap>,
    /// Generated recommendations.
    pub recommendations: Vec<PackRecommendation>,
}

// ============================================================================
// Rule-Level Metrics Types
// ============================================================================

/// Trend direction for rule activity.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum RuleTrend {
    /// Rule triggers are increasing compared to previous period.
    Increasing,
    /// Rule triggers are stable.
    Stable,
    /// Rule triggers are decreasing.
    Decreasing,
}

impl std::fmt::Display for RuleTrend {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Increasing => write!(f, "↑ increasing"),
            Self::Stable => write!(f, "→ stable"),
            Self::Decreasing => write!(f, "↓ decreasing"),
        }
    }
}

/// Per-rule aggregated metrics.
#[derive(Debug, Clone, Serialize)]
pub struct RuleMetrics {
    /// Stable rule identifier (`pack_id:pattern_name`).
    pub rule_id: String,
    /// Total times this rule triggered (deny + bypass + warn).
    pub total_hits: u64,
    /// Times the rule resulted in allowlist override (bypass).
    pub allowlist_overrides: u64,
    /// Override rate as a percentage (0.0-100.0).
    pub override_rate: f64,
    /// When this rule was first triggered.
    pub first_seen: DateTime<Utc>,
    /// When this rule was last triggered.
    pub last_seen: DateTime<Utc>,
    /// Number of unique commands that triggered this rule.
    pub unique_commands: u64,
    /// Trend direction based on recent vs previous period.
    pub trend: RuleTrend,
    /// Whether this rule is considered noisy (high override rate).
    pub is_noisy: bool,
    /// Hits in the previous period (for week-over-week comparison).
    pub previous_period_hits: u64,
    /// Percentage change from previous period (-100.0 to +infinity).
    pub change_percentage: f64,
    /// Whether this rule shows an anomalous spike (> 200% increase).
    pub is_anomaly: bool,
}

impl RuleMetrics {
    /// Threshold for considering a rule noisy.
    pub const NOISY_THRESHOLD: f64 = 30.0;
    /// Minimum hits required to calculate trend.
    pub const MIN_HITS_FOR_TREND: u64 = 5;
    /// Threshold change for increasing/decreasing trend (30% change).
    pub const TREND_THRESHOLD: f64 = 0.3;
    /// Threshold for anomaly detection (200% increase).
    pub const ANOMALY_THRESHOLD: f64 = 200.0;
}

// ============================================================================
// Suggestion Audit Logging Types
// ============================================================================

/// User action taken on a suggestion.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SuggestionAction {
    /// User accepted the suggestion as-is.
    Accepted,
    /// User modified the suggestion before accepting.
    Modified,
    /// User rejected the suggestion.
    Rejected,
}

impl SuggestionAction {
    /// Convert to database string representation.
    #[must_use]
    pub const fn as_str(&self) -> &'static str {
        match self {
            Self::Accepted => "accepted",
            Self::Modified => "modified",
            Self::Rejected => "rejected",
        }
    }

    /// Parse from database string representation.
    #[must_use]
    pub fn parse(s: &str) -> Option<Self> {
        match s.to_lowercase().as_str() {
            "accepted" => Some(Self::Accepted),
            "modified" => Some(Self::Modified),
            "rejected" => Some(Self::Rejected),
            _ => None,
        }
    }
}

impl std::str::FromStr for SuggestionAction {
    type Err = ();

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::parse(s).ok_or(())
    }
}

impl std::fmt::Display for SuggestionAction {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

/// An audit entry for a suggestion action.
///
/// Records when a user accepts, modifies, or rejects a suggested allowlist pattern.
/// This provides traceability for how the allowlist evolved over time.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SuggestionAuditEntry {
    /// Timestamp when the action was taken (ISO 8601).
    pub timestamp: DateTime<Utc>,
    /// The action taken by the user.
    pub action: SuggestionAction,
    /// The suggested regex pattern.
    pub pattern: String,
    /// The final pattern (may differ from suggestion if modified).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub final_pattern: Option<String>,
    /// Risk level of the suggestion (low, medium, high).
    pub risk_level: String,
    /// Numeric risk score from 0.0 (safest) to 1.0 (most dangerous).
    pub risk_score: f32,
    /// Confidence tier (high, medium, low).
    pub confidence_tier: String,
    /// Confidence score points.
    pub confidence_points: i32,
    /// How many times commands matching this pattern were blocked.
    pub cluster_frequency: usize,
    /// Number of unique command variants in the source cluster.
    pub unique_variants: usize,
    /// Sample commands from the cluster (JSON array, limited to 5).
    pub sample_commands: String,
    /// Rule ID if the pattern corresponds to a specific rule.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub rule_id: Option<String>,
    /// Session ID to correlate with command history.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub session_id: Option<String>,
    /// Working directory where the suggestion was generated.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub working_dir: Option<String>,
}

impl Default for SuggestionAuditEntry {
    fn default() -> Self {
        Self {
            timestamp: Utc::now(),
            action: SuggestionAction::Accepted,
            pattern: String::new(),
            final_pattern: None,
            risk_level: "low".to_string(),
            risk_score: 0.0,
            confidence_tier: "medium".to_string(),
            confidence_points: 0,
            cluster_frequency: 0,
            unique_variants: 0,
            sample_commands: "[]".to_string(),
            rule_id: None,
            session_id: None,
            working_dir: None,
        }
    }
}

/// Type of interactive allowlist option selected by the user.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum InteractiveAllowlistOptionType {
    /// Exact command was allowlisted without temporary expiry/path scoping.
    Exact,
    /// Command/rule was allowlisted temporarily with expiration.
    Temporary,
    /// Command/rule was allowlisted with path-specific scope.
    PathSpecific,
}

impl InteractiveAllowlistOptionType {
    /// Convert to database string representation.
    #[must_use]
    pub const fn as_str(&self) -> &'static str {
        match self {
            Self::Exact => "exact",
            Self::Temporary => "temporary",
            Self::PathSpecific => "path_specific",
        }
    }

    /// Parse from database/CLI string representation.
    #[must_use]
    pub fn parse(s: &str) -> Option<Self> {
        match s.to_ascii_lowercase().as_str() {
            "exact" => Some(Self::Exact),
            "temporary" | "temp" => Some(Self::Temporary),
            "path_specific" | "path-specific" | "path" => Some(Self::PathSpecific),
            _ => None,
        }
    }
}

impl std::str::FromStr for InteractiveAllowlistOptionType {
    type Err = ();

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::parse(s).ok_or(())
    }
}

impl std::fmt::Display for InteractiveAllowlistOptionType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

/// Audit entry for an interactive allowlist action.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct InteractiveAllowlistAuditEntry {
    /// Timestamp when the interactive allowlist action occurred.
    pub timestamp: DateTime<Utc>,
    /// Original command that was being evaluated.
    pub command: String,
    /// Pattern added to allowlist (rule ID or exact command).
    pub pattern_added: String,
    /// Option type selected by the user (exact/temporary/path-specific).
    pub option_type: InteractiveAllowlistOptionType,
    /// Optional detail string (e.g., target/layer/expiry/paths metadata).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub option_detail: Option<String>,
    /// Config file path that was modified.
    pub config_file: String,
    /// Current working directory where action was taken.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cwd: Option<String>,
    /// Username associated with the action.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub user: Option<String>,
}

impl Default for InteractiveAllowlistAuditEntry {
    fn default() -> Self {
        Self {
            timestamp: Utc::now(),
            command: String::new(),
            pattern_added: String::new(),
            option_type: InteractiveAllowlistOptionType::Exact,
            option_detail: None,
            config_file: String::new(),
            cwd: None,
            user: None,
        }
    }
}

/// Escape a string for CSV output.
fn csv_escape(s: &str) -> String {
    if s.contains(',') || s.contains('"') || s.contains('\n') || s.contains('\r') {
        format!("\"{}\"", s.replace('"', "\"\""))
    } else {
        s.to_string()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use chrono::Duration;

    type OptionalFields = (
        Option<String>,
        Option<String>,
        Option<String>,
        Option<String>,
        Option<String>,
    );

    fn reset_schema_version_to_v1(db: &HistoryDb) {
        db.conn.execute("DROP TABLE schema_version").unwrap();
        db.conn
            .execute(
                r"CREATE TABLE schema_version (
                    version INTEGER PRIMARY KEY,
                    applied_at TEXT NOT NULL DEFAULT (datetime('now'))
                )",
            )
            .unwrap();
        db.conn
            .execute("INSERT INTO schema_version (version) VALUES (1)")
            .unwrap();
    }

    fn test_entry() -> CommandEntry {
        CommandEntry {
            timestamp: Utc::now(),
            agent_type: "claude_code".to_string(),
            working_dir: "/test/project".to_string(),
            command: "git status".to_string(),
            outcome: Outcome::Allow,
            ..Default::default()
        }
    }

    #[allow(clippy::too_many_arguments)]
    fn insert_entry(
        db: &HistoryDb,
        idx: usize,
        timestamp: DateTime<Utc>,
        outcome: Outcome,
        pattern_name: Option<&str>,
        pack_id: Option<&str>,
        agent_type: &str,
        working_dir: &str,
        eval_duration_us: u64,
    ) {
        let entry = CommandEntry {
            timestamp,
            agent_type: agent_type.to_string(),
            working_dir: working_dir.to_string(),
            command: format!("cmd-{idx}"),
            outcome,
            pack_id: pack_id.map(str::to_string),
            pattern_name: pattern_name.map(str::to_string),
            eval_duration_us,
            ..Default::default()
        };
        db.log_command(&entry).unwrap();
    }

    fn insert_command(
        db: &HistoryDb,
        command: &str,
        outcome: Outcome,
        working_dir: &str,
        timestamp: DateTime<Utc>,
    ) {
        let entry = CommandEntry {
            timestamp,
            agent_type: "claude_code".to_string(),
            working_dir: working_dir.to_string(),
            command: command.to_string(),
            outcome,
            ..Default::default()
        };
        db.log_command(&entry).unwrap();
    }

    fn create_test_db_with_outcomes(allow: usize, deny: usize, warn: usize) -> HistoryDb {
        let db = HistoryDb::open_in_memory().unwrap();
        let now = Utc::now() - Duration::days(1);
        let mut idx = 0;
        for _ in 0..allow {
            insert_entry(
                &db,
                idx,
                now,
                Outcome::Allow,
                None,
                None,
                "claude_code",
                "/project/a",
                100,
            );
            idx += 1;
        }
        for _ in 0..deny {
            insert_entry(
                &db,
                idx,
                now,
                Outcome::Deny,
                Some("reset-hard"),
                Some("core.git"),
                "claude_code",
                "/project/a",
                120,
            );
            idx += 1;
        }
        for _ in 0..warn {
            insert_entry(
                &db,
                idx,
                now,
                Outcome::Warn,
                Some("force-push"),
                Some("core.git"),
                "claude_code",
                "/project/a",
                140,
            );
            idx += 1;
        }
        db
    }

    fn create_test_db_with_patterns(patterns: &[(&str, usize)]) -> HistoryDb {
        let db = HistoryDb::open_in_memory().unwrap();
        let now = Utc::now() - Duration::days(1);
        let mut idx = 0;
        for (name, count) in patterns {
            for _ in 0..*count {
                insert_entry(
                    &db,
                    idx,
                    now,
                    Outcome::Deny,
                    Some(name),
                    Some("core.git"),
                    "claude_code",
                    "/project/a",
                    100,
                );
                idx += 1;
            }
        }
        db
    }

    fn create_test_db_with_durations(durations: &[u64]) -> HistoryDb {
        let db = HistoryDb::open_in_memory().unwrap();
        let now = Utc::now() - Duration::days(1);
        for (idx, duration) in durations.iter().enumerate() {
            insert_entry(
                &db,
                idx,
                now,
                Outcome::Allow,
                None,
                None,
                "claude_code",
                "/project/a",
                *duration,
            );
        }
        db
    }

    fn create_test_db_with_projects(projects: &[(&str, usize)]) -> HistoryDb {
        let db = HistoryDb::open_in_memory().unwrap();
        let now = Utc::now() - Duration::days(1);
        let mut idx = 0;
        for (path, count) in projects {
            for _ in 0..*count {
                insert_entry(
                    &db,
                    idx,
                    now,
                    Outcome::Allow,
                    None,
                    None,
                    "claude_code",
                    path,
                    100,
                );
                idx += 1;
            }
        }
        db
    }

    fn create_test_db_with_agents(agents: &[(&str, usize)]) -> HistoryDb {
        let db = HistoryDb::open_in_memory().unwrap();
        let now = Utc::now() - Duration::days(1);
        let mut idx = 0;
        for (agent, count) in agents {
            for _ in 0..*count {
                insert_entry(
                    &db,
                    idx,
                    now,
                    Outcome::Allow,
                    None,
                    None,
                    agent,
                    "/project/a",
                    100,
                );
                idx += 1;
            }
        }
        db
    }

    fn create_test_db_with_trend_data() -> HistoryDb {
        let db = HistoryDb::open_in_memory().unwrap();
        let now = Utc::now();
        let mut idx = 0;
        // Current period (last 30 days)
        for _ in 0..50 {
            insert_entry(
                &db,
                idx,
                now - Duration::days(5),
                Outcome::Allow,
                None,
                None,
                "claude_code",
                "/project/a",
                100,
            );
            idx += 1;
        }
        // Previous period (30-60 days ago)
        for _ in 0..25 {
            insert_entry(
                &db,
                idx,
                now - Duration::days(40),
                Outcome::Allow,
                None,
                None,
                "claude_code",
                "/project/a",
                100,
            );
            idx += 1;
        }
        db
    }

    #[test]
    fn test_schema_creation() {
        let db = HistoryDb::open_in_memory().unwrap();

        // Verify all expected tables exist
        let rows = db
            .conn
            .query("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name")
            .unwrap();
        let tables: Vec<String> = rows
            .iter()
            .map(|row| sv_to_string(&row.values()[0]))
            .collect();

        assert!(tables.contains(&"commands".to_string()));
        assert!(tables.contains(&"schema_version".to_string()));
    }

    #[test]
    fn test_commands_table_columns() {
        let db = HistoryDb::open_in_memory().unwrap();

        // Verify columns exist by selecting them (fsqlite PRAGMA table_info
        // may return empty results for in-memory databases).
        let row = db.conn.query_row(
            "SELECT id, timestamp, agent_type, working_dir, command, command_hash,
                        outcome, eval_duration_us, session_id, exit_code,
                        parent_command_id, hostname
                 FROM commands LIMIT 0",
        );
        // The query should parse successfully even with no data (LIMIT 0).
        // If any column didn't exist, this would fail with "no such column".
        assert!(
            row.is_ok() || matches!(row, Err(FrankenError::QueryReturnedNoRows)),
            "all expected columns should exist in commands table"
        );
    }

    #[test]
    fn test_indexes_created() {
        let db = HistoryDb::open_in_memory().unwrap();

        let rows = db
            .conn
            .query("SELECT name FROM sqlite_master WHERE type='index' AND name LIKE 'idx_%'")
            .unwrap();
        let indexes: Vec<String> = rows
            .iter()
            .map(|row| sv_to_string(&row.values()[0]))
            .collect();

        // Performance-critical indexes
        assert!(indexes.iter().any(|i| i.contains("timestamp")));
        assert!(indexes.iter().any(|i| i.contains("outcome")));
        assert!(indexes.iter().any(|i| i.contains("working_dir")));
        assert!(indexes.iter().any(|i| i.contains("pack_id")));
        assert!(indexes.iter().any(|i| i.contains("agent_type")));
    }

    #[test]
    fn test_fts_table_created() {
        let db = HistoryDb::open_in_memory().unwrap();

        // FTS5 virtual table for full-text search
        let result = db
            .conn
            .query_row("SELECT 1 FROM sqlite_master WHERE type='table' AND name='commands_fts'");
        assert!(result.is_ok());
    }

    #[test]
    fn test_insert_and_query() {
        let db = HistoryDb::open_in_memory().unwrap();

        let entry = test_entry();
        db.log_command(&entry).unwrap();

        let count: i64 = db
            .conn
            .query_row("SELECT COUNT(*) FROM commands")
            .map(|row| sv_to_i64(&row.values()[0]))
            .unwrap();

        assert_eq!(count, 1);
    }

    #[test]
    fn test_log_command_computes_rule_id_from_pack_and_pattern() {
        let db = HistoryDb::open_in_memory().unwrap();

        let entry = CommandEntry {
            timestamp: Utc::now(),
            agent_type: "claude_code".to_string(),
            working_dir: "/test/project".to_string(),
            command: "git reset --hard".to_string(),
            outcome: Outcome::Deny,
            pack_id: Some("core.git".to_string()),
            pattern_name: Some("reset-hard".to_string()),
            rule_id: None,
            ..Default::default()
        };

        db.log_command(&entry).unwrap();

        let stored: Option<String> = db
            .conn
            .query_row("SELECT rule_id FROM commands LIMIT 1")
            .map(|row| sv_to_opt_string(&row.values()[0]))
            .unwrap();
        assert_eq!(stored, Some("core.git:reset-hard".to_string()));
    }

    #[test]
    fn test_log_command_preserves_explicit_rule_id() {
        let db = HistoryDb::open_in_memory().unwrap();

        let entry = CommandEntry {
            timestamp: Utc::now(),
            agent_type: "claude_code".to_string(),
            working_dir: "/test/project".to_string(),
            command: "git reset --hard".to_string(),
            outcome: Outcome::Deny,
            pack_id: Some("core.git".to_string()),
            pattern_name: Some("reset-hard".to_string()),
            rule_id: Some("override.rule-id".to_string()),
            ..Default::default()
        };

        db.log_command(&entry).unwrap();

        let stored: Option<String> = db
            .conn
            .query_row("SELECT rule_id FROM commands LIMIT 1")
            .map(|row| sv_to_opt_string(&row.values()[0]))
            .unwrap();
        assert_eq!(stored, Some("override.rule-id".to_string()));
    }

    #[test]
    fn test_log_command_records_rule_id_for_allowlist_override() {
        let db = HistoryDb::open_in_memory().unwrap();

        let entry = CommandEntry {
            timestamp: Utc::now(),
            agent_type: "claude_code".to_string(),
            working_dir: "/test/project".to_string(),
            command: "git reset --hard".to_string(),
            outcome: Outcome::Allow,
            pack_id: Some("core.git".to_string()),
            pattern_name: Some("reset-hard".to_string()),
            allowlist_layer: Some("user".to_string()),
            ..Default::default()
        };

        db.log_command(&entry).unwrap();

        let stored: Option<String> = db
            .conn
            .query_row("SELECT rule_id FROM commands LIMIT 1")
            .map(|row| sv_to_opt_string(&row.values()[0]))
            .unwrap();
        assert_eq!(stored, Some("core.git:reset-hard".to_string()));
    }

    #[test]
    fn test_stats_outcome_distribution() {
        let db = create_test_db_with_outcomes(70, 20, 10);

        let stats = db.compute_stats(30).unwrap();

        assert_eq!(stats.total_commands, 100);
        assert_eq!(stats.outcomes.allowed, 70);
        assert_eq!(stats.outcomes.denied, 20);
        assert_eq!(stats.outcomes.warned, 10);
    }

    #[test]
    fn test_stats_top_patterns() {
        let db =
            create_test_db_with_patterns(&[("reset-hard", 50), ("force-push", 30), ("rm-rf", 20)]);

        let stats = db.compute_stats(30).unwrap();

        assert_eq!(stats.top_patterns[0].name, "reset-hard");
        assert_eq!(stats.top_patterns[0].count, 50);
    }

    #[test]
    fn test_stats_performance_percentiles() {
        let db = create_test_db_with_durations(&[100, 200, 300, 400, 500, 1000, 2000, 5000, 10000]);

        let stats = db.compute_stats(30).unwrap();

        assert!(stats.performance.p50_us <= stats.performance.p95_us);
        assert!(stats.performance.p95_us <= stats.performance.p99_us);
    }

    #[test]
    fn test_stats_project_breakdown() {
        let db = create_test_db_with_projects(&[
            ("/project/a", 50),
            ("/project/b", 30),
            ("/project/c", 20),
        ]);

        let stats = db.compute_stats(30).unwrap();

        assert_eq!(stats.top_projects[0].path, "/project/a");
        assert_eq!(stats.top_projects[0].command_count, 50);
    }

    #[test]
    fn test_stats_agent_distribution() {
        let db = create_test_db_with_agents(&[("claude_code", 60), ("codex", 30), ("gemini", 10)]);

        let stats = db.compute_stats(30).unwrap();

        assert_eq!(stats.agents[0].name, "claude_code");
        assert_eq!(stats.agents[0].count, 60);
    }

    #[test]
    fn test_stats_with_trends() {
        let db = create_test_db_with_trend_data();

        let stats = db.compute_stats_with_trends(30).unwrap();

        assert!(stats.trends.is_some());
        let trends = stats.trends.unwrap();
        assert!(!trends.commands_change.is_nan());
    }

    #[test]
    fn test_stats_empty_db() {
        let db = HistoryDb::open_in_memory().unwrap();

        let stats = db.compute_stats(30).unwrap();

        assert_eq!(stats.total_commands, 0);
        assert_eq!(stats.outcomes.allowed, 0);
    }

    #[test]
    fn test_stats_json_output() {
        let db = create_test_db_with_outcomes(50, 30, 20);

        let stats = db.compute_stats(30).unwrap();
        let json = serde_json::to_string(&stats).unwrap();

        let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();
        assert!(parsed["total_commands"].is_number());
    }

    #[test]
    fn test_timestamp_format() {
        let db = HistoryDb::open_in_memory().unwrap();

        let entry = test_entry();
        db.log_command(&entry).unwrap();

        let stored: String = db
            .conn
            .query_row("SELECT timestamp FROM commands LIMIT 1")
            .map(|row| sv_to_string(&row.values()[0]))
            .unwrap();

        // ISO 8601 format with T separator
        assert!(stored.contains('T'));
        assert!(stored.ends_with('Z'));
    }

    #[test]
    fn test_schema_version() {
        let db = HistoryDb::open_in_memory().unwrap();
        let version = db.get_schema_version().unwrap();
        assert_eq!(version, CURRENT_SCHEMA_VERSION);
    }

    #[test]
    fn test_database_creation() {
        let temp_dir = tempfile::tempdir().unwrap();
        let db_path = temp_dir.path().join("test.db");

        assert!(!db_path.exists());
        let _db = HistoryDb::open(Some(db_path.clone())).unwrap();
        assert!(db_path.exists());
    }

    #[test]
    fn test_parent_directory_created() {
        let temp_dir = tempfile::tempdir().unwrap();
        let db_path = temp_dir.path().join("nested/deep/test.db");

        let _db = HistoryDb::open(Some(db_path.clone())).unwrap();
        assert!(db_path.exists());
    }

    #[test]
    fn test_wal_mode_enabled() {
        let temp_dir = tempfile::tempdir().unwrap();
        let db_path = temp_dir.path().join("wal.db");
        let db = HistoryDb::open(Some(db_path)).unwrap();

        let mode: String = db
            .conn
            .query_row("PRAGMA journal_mode")
            .map(|row| sv_to_string(&row.values()[0]))
            .unwrap();

        assert_eq!(mode.to_lowercase(), "wal");
    }

    #[test]
    fn test_try_open_corruption_returns_none() {
        let temp_dir = tempfile::tempdir().unwrap();
        let db_path = temp_dir.path().join("corrupt.db");

        std::fs::write(&db_path, b"not a valid sqlite db").unwrap();
        let result = HistoryDb::try_open(Some(db_path));
        assert!(result.is_none());
    }

    #[test]
    #[cfg(unix)]
    fn test_try_open_permission_denied_returns_none() {
        use std::os::unix::fs::PermissionsExt;

        let temp_dir = tempfile::tempdir().unwrap();
        let dir_path = temp_dir.path().join("readonly");
        std::fs::create_dir(&dir_path).unwrap();

        std::fs::set_permissions(&dir_path, std::fs::Permissions::from_mode(0o444)).unwrap();

        let db_path = dir_path.join("test.db");
        let result = HistoryDb::try_open(Some(db_path));
        assert!(result.is_none());

        // Restore permissions so temp_dir cleanup can succeed
        std::fs::set_permissions(&dir_path, std::fs::Permissions::from_mode(0o755)).unwrap();
    }

    #[test]
    fn test_migration_adds_schema_version_description() {
        let db = HistoryDb::open_in_memory().unwrap();
        reset_schema_version_to_v1(&db);

        db.run_migrations(1).unwrap();

        let version = db.get_schema_version().unwrap();
        assert_eq!(version, CURRENT_SCHEMA_VERSION);

        let description_count: i64 = db
            .conn
            .query_row("SELECT COUNT(*) FROM schema_version WHERE description IS NOT NULL")
            .map(|row| sv_to_i64(&row.values()[0]))
            .unwrap();
        assert!(description_count > 0);
    }

    #[test]
    fn test_command_hash_deterministic() {
        let entry1 = CommandEntry {
            command: "git status".to_string(),
            ..Default::default()
        };
        let entry2 = CommandEntry {
            command: "git status".to_string(),
            ..Default::default()
        };

        assert_eq!(entry1.command_hash(), entry2.command_hash());
        assert_eq!(entry1.command_hash().len(), 64); // SHA256 = 64 hex chars
    }

    #[test]
    fn test_outcome_roundtrip() {
        for outcome in [
            Outcome::Allow,
            Outcome::Deny,
            Outcome::Warn,
            Outcome::Bypass,
        ] {
            let s = outcome.as_str();
            let parsed = Outcome::parse(s).unwrap();
            assert_eq!(outcome, parsed);
        }
    }

    #[test]
    fn test_fts_search() {
        let db = HistoryDb::open_in_memory().unwrap();

        // Insert a few commands
        db.log_command(&CommandEntry {
            command: "git push origin main".to_string(),
            ..Default::default()
        })
        .unwrap();
        db.log_command(&CommandEntry {
            command: "npm install lodash".to_string(),
            ..Default::default()
        })
        .unwrap();
        db.log_command(&CommandEntry {
            command: "git pull origin feature".to_string(),
            ..Default::default()
        })
        .unwrap();

        // Search for git commands using LIKE (fsqlite's FTS5 MATCH operator does
        // not correctly handle aggregation in the fallback execution path).
        let count = db
            .conn
            .query("SELECT rowid FROM commands_fts WHERE command LIKE '%git%'")
            .map(|rows| rows.len())
            .unwrap();

        assert_eq!(count, 2);
    }

    #[test]
    fn test_count_commands_empty() {
        let db = HistoryDb::open_in_memory().unwrap();
        assert_eq!(db.count_commands().unwrap(), 0);
    }

    #[test]
    fn test_count_commands_with_data() {
        let db = HistoryDb::open_in_memory().unwrap();

        for i in 0..10 {
            db.log_command(&CommandEntry {
                command: format!("command {i}"),
                ..Default::default()
            })
            .unwrap();
        }

        assert_eq!(db.count_commands().unwrap(), 10);
    }

    #[test]
    fn test_prune_older_than_days() {
        let db = HistoryDb::open_in_memory().unwrap();
        let now = Utc::now();

        let mut old_entry = test_entry();
        old_entry.timestamp = now - Duration::days(30);
        db.log_command(&old_entry).unwrap();

        let mut recent_entry = test_entry();
        recent_entry.timestamp = now - Duration::days(1);
        db.log_command(&recent_entry).unwrap();

        let pruned = db.prune_older_than_days(7, false).unwrap();
        assert_eq!(pruned, 1);
        assert_eq!(db.count_commands().unwrap(), 1);
    }

    #[test]
    fn test_prune_older_than_days_dry_run() {
        let db = HistoryDb::open_in_memory().unwrap();
        let now = Utc::now();

        let mut old_entry = test_entry();
        old_entry.timestamp = now - Duration::days(30);
        db.log_command(&old_entry).unwrap();

        let pruned = db.prune_older_than_days(7, true).unwrap();
        assert_eq!(pruned, 1);
        assert_eq!(db.count_commands().unwrap(), 1);
    }

    #[test]
    fn test_file_size_in_memory() {
        let db = HistoryDb::open_in_memory().unwrap();
        assert_eq!(db.file_size().unwrap(), 0);
    }

    #[test]
    fn test_all_optional_fields() {
        let db = HistoryDb::open_in_memory().unwrap();

        let entry = CommandEntry {
            timestamp: Utc::now(),
            agent_type: "claude_code".to_string(),
            working_dir: "/project".to_string(),
            command: "test command".to_string(),
            outcome: Outcome::Deny,
            pack_id: Some("core.git".to_string()),
            pattern_name: Some("force-push".to_string()),
            rule_id: None,
            eval_duration_us: 1500,
            session_id: Some("session-123".to_string()),
            exit_code: Some(0),
            parent_command_id: None,
            hostname: Some("dev-machine".to_string()),
            allowlist_layer: None,
            bypass_code: Some("ab12".to_string()),
        };

        let id = db.log_command(&entry).unwrap();
        assert!(id > 0);

        // Verify all fields stored correctly
        let row = db
            .conn
            .query_row_with_params(
                "SELECT pack_id, pattern_name, session_id, hostname, bypass_code
                 FROM commands WHERE id = ?1",
                &[SqliteValue::Integer(id)],
            )
            .unwrap();
        let vals = row.values();
        let (pack_id, pattern_name, session_id, hostname, bypass_code): OptionalFields = (
            sv_to_opt_string(&vals[0]),
            sv_to_opt_string(&vals[1]),
            sv_to_opt_string(&vals[2]),
            sv_to_opt_string(&vals[3]),
            sv_to_opt_string(&vals[4]),
        );

        assert_eq!(pack_id, Some("core.git".to_string()));
        assert_eq!(pattern_name, Some("force-push".to_string()));
        assert_eq!(session_id, Some("session-123".to_string()));
        assert_eq!(hostname, Some("dev-machine".to_string()));
        assert_eq!(bypass_code, Some("ab12".to_string()));
    }

    #[test]
    fn test_outcome_constraint() {
        let db = HistoryDb::open_in_memory().unwrap();

        // Valid outcome should work
        db.conn
            .execute(
                "INSERT INTO commands (timestamp, agent_type, working_dir, command, command_hash, outcome)
                 VALUES ('2026-01-01T00:00:00Z', 'test', '/test', 'cmd', 'hash', 'allow')",
            )
            .unwrap();

        // Note: fsqlite does not enforce CHECK constraints at this time,
        // so we only verify valid outcomes can be inserted. Application-level
        // validation in CommandEntry::outcome ensures correctness.
    }

    #[test]
    fn test_reopen_existing_db() {
        let dir = tempfile::TempDir::new().unwrap();
        let db_path = dir.path().join("test.db");

        // Create and populate
        {
            let db = HistoryDb::open(Some(db_path.clone())).unwrap();
            db.log_command(&test_entry()).unwrap();
            assert_eq!(db.count_commands().unwrap(), 1);
        }

        // Reopen and verify
        {
            let db = HistoryDb::open(Some(db_path)).unwrap();
            assert_eq!(db.count_commands().unwrap(), 1);
            assert_eq!(db.get_schema_version().unwrap(), CURRENT_SCHEMA_VERSION);
        }
    }

    // Export tests

    fn create_test_db_with_data(count: usize) -> HistoryDb {
        let db = HistoryDb::open_in_memory().unwrap();
        let now = Utc::now() - Duration::days(1);
        for idx in 0..count {
            insert_entry(
                &db,
                idx,
                now,
                Outcome::Allow,
                None,
                None,
                "claude_code",
                "/project/a",
                100,
            );
        }
        db
    }

    fn create_test_db_with_mixed_outcomes(count: usize) -> HistoryDb {
        let db = HistoryDb::open_in_memory().unwrap();
        let now = Utc::now() - Duration::days(1);
        for idx in 0..count {
            let outcome = if idx % 2 == 0 {
                Outcome::Allow
            } else {
                Outcome::Deny
            };
            insert_entry(
                &db,
                idx,
                now,
                outcome,
                if outcome == Outcome::Deny {
                    Some("reset-hard")
                } else {
                    None
                },
                if outcome == Outcome::Deny {
                    Some("core.git")
                } else {
                    None
                },
                "claude_code",
                "/project/a",
                100,
            );
        }
        db
    }

    #[test]
    fn test_json_export_format() {
        let db = create_test_db_with_data(10);
        let mut buf = Vec::new();

        db.export_json(&mut buf, &ExportOptions::default()).unwrap();

        let json: serde_json::Value = serde_json::from_slice(&buf).unwrap();
        assert!(json["exported_at"].is_string());
        assert!(json["total_records"].as_i64().unwrap() >= 10);
        assert!(json["commands"].is_array());
    }

    #[test]
    fn test_csv_export_format() {
        let db = create_test_db_with_data(10);
        let mut buf = Vec::new();

        db.export_csv(&mut buf, &ExportOptions::default()).unwrap();

        let content = String::from_utf8(buf).unwrap();
        // Should have header row
        assert!(content.starts_with("timestamp,agent_type,"));
        // Should have data rows (header + 10 data = at least 11 lines)
        assert!(content.lines().count() >= 11);
    }

    #[test]
    fn test_jsonl_export_streaming() {
        let db = create_test_db_with_data(50);
        let mut buf = Vec::new();

        db.export_jsonl(&mut buf, &ExportOptions::default())
            .unwrap();

        let content = String::from_utf8(buf).unwrap();
        // Each line should be valid JSON
        for line in content.lines() {
            serde_json::from_str::<serde_json::Value>(line).unwrap();
        }
        assert_eq!(content.lines().count(), 50);
    }

    #[test]
    fn test_export_with_outcome_filter() {
        let db = create_test_db_with_mixed_outcomes(100);
        let mut buf = Vec::new();

        db.export_json(
            &mut buf,
            &ExportOptions {
                outcome_filter: Some(Outcome::Deny),
                ..Default::default()
            },
        )
        .unwrap();

        let json: serde_json::Value = serde_json::from_slice(&buf).unwrap();
        for cmd in json["commands"].as_array().unwrap() {
            assert_eq!(cmd["outcome"], "deny");
        }
    }

    #[test]
    fn test_export_with_limit() {
        let db = create_test_db_with_data(100);
        let mut buf = Vec::new();

        db.export_json(
            &mut buf,
            &ExportOptions {
                limit: Some(10),
                ..Default::default()
            },
        )
        .unwrap();

        let json: serde_json::Value = serde_json::from_slice(&buf).unwrap();
        assert_eq!(json["commands"].as_array().unwrap().len(), 10);
    }

    #[test]
    fn test_export_with_date_range() {
        let db = HistoryDb::open_in_memory().unwrap();
        let now = Utc::now();

        // Insert commands at different times
        let mut old_entry = test_entry();
        old_entry.timestamp = now - Duration::days(30);
        db.log_command(&old_entry).unwrap();

        let mut recent_entry = test_entry();
        recent_entry.timestamp = now - Duration::days(1);
        db.log_command(&recent_entry).unwrap();

        let mut buf = Vec::new();
        db.export_json(
            &mut buf,
            &ExportOptions {
                since: Some(now - Duration::days(7)),
                ..Default::default()
            },
        )
        .unwrap();

        let json: serde_json::Value = serde_json::from_slice(&buf).unwrap();
        // Should only include the recent entry
        assert_eq!(json["commands"].as_array().unwrap().len(), 1);
    }

    #[test]
    fn test_empty_export() {
        let db = HistoryDb::open_in_memory().unwrap();
        let mut buf = Vec::new();

        let count = db.export_json(&mut buf, &ExportOptions::default()).unwrap();

        assert_eq!(count, 0);
        let json: serde_json::Value = serde_json::from_slice(&buf).unwrap();
        assert_eq!(json["total_records"].as_i64().unwrap(), 0);
        assert!(json["commands"].as_array().unwrap().is_empty());
    }

    #[test]
    fn test_csv_escape_special_chars() {
        let db = HistoryDb::open_in_memory().unwrap();

        // Insert a command with special characters
        let entry = CommandEntry {
            command: "echo \"hello, world\"\ntest".to_string(),
            ..Default::default()
        };
        db.log_command(&entry).unwrap();

        let mut buf = Vec::new();
        db.export_csv(&mut buf, &ExportOptions::default()).unwrap();

        let content = String::from_utf8(buf).unwrap();
        // The command with special chars should be quoted
        assert!(content.contains("\"echo \"\"hello, world\"\""));
    }

    #[test]
    fn test_query_commands_for_export() {
        let db = create_test_db_with_data(25);
        let entries = db
            .query_commands_for_export(&ExportOptions::default())
            .unwrap();
        assert_eq!(entries.len(), 25);

        // Test with limit
        let entries = db
            .query_commands_for_export(&ExportOptions {
                limit: Some(5),
                ..Default::default()
            })
            .unwrap();
        assert_eq!(entries.len(), 5);
    }

    // ========================================================================
    // History Analyzer Tests
    // ========================================================================

    #[test]
    fn test_history_analyzer_frequent_blocks() {
        let db = HistoryDb::open_in_memory().unwrap();
        let now = Utc::now() - Duration::days(1);

        for _ in 0..3 {
            insert_command(&db, "rm -rf ./build", Outcome::Deny, "/project/a", now);
        }
        insert_command(&db, "git reset --hard", Outcome::Deny, "/project/a", now);

        let analyzer = HistoryAnalyzer::new(&db);
        let results = analyzer.get_frequent_blocks(30, 2).unwrap();

        assert_eq!(results.len(), 1);
        assert_eq!(results[0].command, "rm -rf ./build");
        assert_eq!(results[0].block_count, 3);
    }

    #[test]
    fn test_history_analyzer_path_clusters() {
        let db = HistoryDb::open_in_memory().unwrap();
        let now = Utc::now() - Duration::days(1);

        insert_command(&db, "rm -rf ./build", Outcome::Deny, "/project/a", now);
        insert_command(&db, "rm -rf ./build", Outcome::Deny, "/project/a", now);
        insert_command(&db, "rm -rf ./build", Outcome::Deny, "/project/b", now);

        let analyzer = HistoryAnalyzer::new(&db);
        let results = analyzer.get_path_clusters(2).unwrap();

        assert_eq!(results.len(), 1);
        assert_eq!(results[0].command, "rm -rf ./build");
        assert_eq!(results[0].working_dir, "/project/a");
        assert_eq!(results[0].block_count, 2);
    }

    #[test]
    fn test_history_analyzer_suggestion_candidates() {
        let db = HistoryDb::open_in_memory().unwrap();
        let now = Utc::now() - Duration::days(1);

        insert_command(&db, "git clean -fd", Outcome::Bypass, "/project/a", now);
        insert_command(&db, "git clean -fd", Outcome::Bypass, "/project/a", now);
        insert_command(&db, "rm -rf ./tmp", Outcome::Bypass, "/project/b", now);

        let analyzer = HistoryAnalyzer::new(&db);
        let results = analyzer.get_suggestion_candidates().unwrap();

        assert_eq!(results.len(), 2);
        assert_eq!(results[0].command, "git clean -fd");
        assert_eq!(results[0].bypass_count, 2);
    }

    // ========================================================================
    // Pack Effectiveness Analysis Tests
    // ========================================================================

    /// Helper to insert entries with specific outcomes and patterns.
    fn insert_analysis_entry(
        db: &HistoryDb,
        pattern: &str,
        pack_id: &str,
        outcome: Outcome,
        timestamp: DateTime<Utc>,
    ) {
        let entry = CommandEntry {
            timestamp,
            agent_type: "claude_code".to_string(),
            working_dir: "/test/project".to_string(),
            command: format!("test command for {pattern}"),
            outcome,
            pack_id: Some(pack_id.to_string()),
            pattern_name: Some(pattern.to_string()),
            eval_duration_us: 100,
            ..Default::default()
        };
        db.log_command(&entry).unwrap();
    }

    #[test]
    fn test_identifies_high_bypass_rate() {
        let db = HistoryDb::open_in_memory().unwrap();
        let now = Utc::now();

        // Pattern A: 95 denies, 5 bypasses = 5% bypass rate (OK)
        for _ in 0..95 {
            insert_analysis_entry(&db, "pattern-a", "core.git", Outcome::Deny, now);
        }
        for _ in 0..5 {
            insert_analysis_entry(&db, "pattern-a", "core.git", Outcome::Bypass, now);
        }

        // Pattern B: 70 denies, 30 bypasses = 30% bypass rate (FLAGGED)
        for _ in 0..70 {
            insert_analysis_entry(&db, "pattern-b", "core.git", Outcome::Deny, now);
        }
        for _ in 0..30 {
            insert_analysis_entry(&db, "pattern-b", "core.git", Outcome::Bypass, now);
        }

        let analysis = db
            .analyze_pack_effectiveness(30, &["core.git", "core.filesystem"])
            .unwrap();

        // Pattern B should be flagged as aggressive (30% bypass)
        assert!(
            analysis
                .potentially_aggressive
                .iter()
                .any(|p| p.pattern == "pattern-b"),
            "Pattern B should be flagged as aggressive"
        );

        // Pattern A should NOT be flagged (5% bypass)
        assert!(
            !analysis
                .potentially_aggressive
                .iter()
                .any(|p| p.pattern == "pattern-a"),
            "Pattern A should not be flagged"
        );
    }

    #[test]
    fn test_identifies_inactive_packs() {
        let db = HistoryDb::open_in_memory().unwrap();
        let now = Utc::now();

        // Only core.git triggers
        for _ in 0..50 {
            insert_analysis_entry(&db, "pattern-a", "core.git", Outcome::Deny, now);
        }

        // core.filesystem and cloud.azure never trigger
        let enabled_packs = ["core.git", "core.filesystem", "cloud.azure"];
        let analysis = db.analyze_pack_effectiveness(30, &enabled_packs).unwrap();

        // cloud.azure and core.filesystem should be inactive
        assert!(
            analysis.inactive_packs.contains(&"cloud.azure".to_string()),
            "cloud.azure should be inactive"
        );
        assert!(
            analysis
                .inactive_packs
                .contains(&"core.filesystem".to_string()),
            "core.filesystem should be inactive"
        );
        // core.git should NOT be inactive
        assert!(
            !analysis.inactive_packs.contains(&"core.git".to_string()),
            "core.git should be active"
        );
    }

    #[test]
    fn test_identifies_high_value_patterns() {
        let db = HistoryDb::open_in_memory().unwrap();
        let now = Utc::now();

        // Pattern A: 500 denies, 10 bypasses = 2% bypass rate (high value)
        for _ in 0..500 {
            insert_analysis_entry(&db, "pattern-a", "core.git", Outcome::Deny, now);
        }
        for _ in 0..10 {
            insert_analysis_entry(&db, "pattern-a", "core.git", Outcome::Bypass, now);
        }

        // Pattern B: 9 denies, 1 bypass = 10% bypass rate (low volume)
        for _ in 0..9 {
            insert_analysis_entry(&db, "pattern-b", "core.git", Outcome::Deny, now);
        }
        insert_analysis_entry(&db, "pattern-b", "core.git", Outcome::Bypass, now);

        let analysis = db.analyze_pack_effectiveness(30, &["core.git"]).unwrap();

        // Pattern A should be high value (high volume, low bypass)
        assert!(
            analysis
                .high_value_patterns
                .iter()
                .any(|p| p.pattern == "pattern-a"),
            "Pattern A should be high value"
        );

        // Pattern B should NOT be high value (too few triggers)
        assert!(
            !analysis
                .high_value_patterns
                .iter()
                .any(|p| p.pattern == "pattern-b"),
            "Pattern B should not be high value (low volume)"
        );
    }

    #[test]
    fn test_generates_actionable_recommendations() {
        let db = HistoryDb::open_in_memory().unwrap();
        let now = Utc::now();

        // Create an aggressive pattern to trigger recommendation
        for _ in 0..60 {
            insert_analysis_entry(&db, "aggressive-pattern", "core.git", Outcome::Deny, now);
        }
        for _ in 0..40 {
            insert_analysis_entry(&db, "aggressive-pattern", "core.git", Outcome::Bypass, now);
        }

        let analysis = db
            .analyze_pack_effectiveness(30, &["core.git", "unused.pack"])
            .unwrap();

        // Should have recommendations
        assert!(
            !analysis.recommendations.is_empty(),
            "Should have recommendations"
        );

        // Each recommendation should have an action or config suggestion
        for rec in &analysis.recommendations {
            assert!(
                rec.suggested_action.is_some() || rec.config_change.is_some() || rec.priority <= 2,
                "Recommendation should be actionable: {rec:?}"
            );
        }
    }

    #[test]
    fn test_coverage_gap_detection() {
        let db = HistoryDb::open_in_memory().unwrap();
        // Use a timestamp slightly in the past to avoid race condition with
        // analyze_pack_effectiveness which uses Utc::now() as the end bound
        let entry_time = Utc::now() - Duration::seconds(1);

        // Insert allowed commands that look dangerous
        let dangerous_commands = [
            "git push --force origin feature",
            "docker system prune --all",
            "rm -rf /tmp/test",
        ];

        for cmd in &dangerous_commands {
            let entry = CommandEntry {
                timestamp: entry_time,
                agent_type: "claude_code".to_string(),
                working_dir: "/test/project".to_string(),
                command: cmd.to_string(),
                outcome: Outcome::Allow,
                pack_id: None,
                pattern_name: None,
                eval_duration_us: 100,
                ..Default::default()
            };
            db.log_command(&entry).unwrap();
        }

        let analysis = db.analyze_pack_effectiveness(30, &["core.git"]).unwrap();

        // Should detect potential gaps
        assert!(
            !analysis.potential_gaps.is_empty(),
            "Should detect coverage gaps"
        );
        assert!(
            analysis
                .potential_gaps
                .iter()
                .any(|g| g.command.contains("--force") || g.command.contains("prune")),
            "Should flag dangerous commands"
        );
    }

    #[test]
    fn test_analysis_with_no_data() {
        let db = HistoryDb::open_in_memory().unwrap();

        let analysis = db
            .analyze_pack_effectiveness(30, &["core.git", "core.filesystem"])
            .unwrap();

        // Should return empty but not error
        assert!(analysis.high_value_patterns.is_empty());
        assert!(analysis.potentially_aggressive.is_empty());
        assert_eq!(analysis.total_commands, 0);
    }

    #[test]
    fn test_machine_readable_recommendations() {
        let db = HistoryDb::open_in_memory().unwrap();
        let now = Utc::now();

        // Create some data to generate recommendations
        for _ in 0..50 {
            insert_analysis_entry(&db, "test-pattern", "core.git", Outcome::Deny, now);
        }
        for _ in 0..50 {
            insert_analysis_entry(&db, "test-pattern", "core.git", Outcome::Bypass, now);
        }

        let analysis = db
            .analyze_pack_effectiveness(30, &["core.git", "unused.pack"])
            .unwrap();

        // Should be valid JSON for automation
        let json = serde_json::to_string(&analysis.recommendations).unwrap();
        let parsed: Vec<serde_json::Value> = serde_json::from_str(&json).unwrap();

        for rec in &parsed {
            assert!(rec["type"].is_string());
            assert!(rec["description"].is_string());
        }
    }

    #[test]
    fn test_rebuild_fts() {
        let db = HistoryDb::open_in_memory().unwrap();
        let now = Utc::now();

        // Insert some commands
        let commands = ["git status", "docker ps", "npm install", "cargo build"];
        for cmd in &commands {
            let entry = CommandEntry {
                timestamp: now,
                agent_type: "test".to_string(),
                working_dir: "/test".to_string(),
                command: cmd.to_string(),
                outcome: Outcome::Allow,
                ..Default::default()
            };
            db.log_command(&entry).unwrap();
        }

        // Verify initial FTS state
        let health1 = db.check_health().unwrap();
        assert_eq!(health1.commands_count, 4);
        assert_eq!(health1.fts_count, 4);
        assert!(health1.fts_in_sync);

        // Rebuild FTS
        let reindexed = db.rebuild_fts().unwrap();
        assert_eq!(reindexed, 4);

        // Verify FTS still works after rebuild
        let health2 = db.check_health().unwrap();
        assert_eq!(health2.commands_count, 4);
        assert_eq!(health2.fts_count, 4);
        assert!(health2.fts_in_sync);
    }

    #[test]
    fn test_repair_healthy_db() {
        let db = HistoryDb::open_in_memory().unwrap();
        let now = Utc::now();

        // Insert some commands
        for i in 0..3 {
            let entry = CommandEntry {
                timestamp: now,
                agent_type: "test".to_string(),
                working_dir: "/test".to_string(),
                command: format!("test command {i}"),
                outcome: Outcome::Allow,
                ..Default::default()
            };
            db.log_command(&entry).unwrap();
        }

        // Repair a healthy database
        let (health, repairs) = db.repair().unwrap();

        // Should be healthy
        assert!(health.fts_in_sync);
        assert_eq!(health.commands_count, 3);

        // No repairs should have been made
        assert!(
            repairs.is_empty(),
            "No repairs should be needed for healthy DB"
        );
    }

    #[test]
    fn test_fts_triggers_work_after_rebuild() {
        let db = HistoryDb::open_in_memory().unwrap();
        let now = Utc::now();

        // Insert initial command
        let entry1 = CommandEntry {
            timestamp: now,
            agent_type: "test".to_string(),
            working_dir: "/test".to_string(),
            command: "initial command".to_string(),
            outcome: Outcome::Allow,
            ..Default::default()
        };
        db.log_command(&entry1).unwrap();

        // Rebuild FTS
        db.rebuild_fts().unwrap();

        // Insert new command after rebuild
        let entry2 = CommandEntry {
            timestamp: now,
            agent_type: "test".to_string(),
            working_dir: "/test".to_string(),
            command: "new command after rebuild".to_string(),
            outcome: Outcome::Allow,
            ..Default::default()
        };
        db.log_command(&entry2).unwrap();

        // Verify triggers work - FTS should have both commands
        let health = db.check_health().unwrap();
        assert_eq!(health.commands_count, 2);
        assert_eq!(health.fts_count, 2);
        assert!(health.fts_in_sync);
    }

    // ==========================================================================
    // Suggestion Audit Tests
    // ==========================================================================

    fn test_suggestion_audit_entry(action: SuggestionAction) -> SuggestionAuditEntry {
        SuggestionAuditEntry {
            timestamp: Utc::now(),
            action,
            pattern: "git reset --hard".to_string(),
            final_pattern: None,
            risk_level: "high".to_string(),
            risk_score: 0.85,
            confidence_tier: "strong".to_string(),
            confidence_points: 15,
            cluster_frequency: 42,
            unique_variants: 3,
            sample_commands: "git reset --hard HEAD~1, git reset --hard origin/main".to_string(),
            rule_id: Some("git-reset-hard-001".to_string()),
            session_id: Some("ses-abc123".to_string()),
            working_dir: Some("/test/project".to_string()),
        }
    }

    #[test]
    fn test_log_suggestion_audit_inserts_entry() {
        let db = HistoryDb::open_in_memory().unwrap();
        let entry = test_suggestion_audit_entry(SuggestionAction::Accepted);

        let id = db.log_suggestion_audit(&entry).unwrap();
        assert!(id > 0, "Should return a positive ID");

        // Verify it was inserted
        let count = db.count_suggestion_audits().unwrap();
        assert_eq!(count, 1);
    }

    #[test]
    fn test_log_suggestion_audit_with_modified_action() {
        let db = HistoryDb::open_in_memory().unwrap();
        let mut entry = test_suggestion_audit_entry(SuggestionAction::Modified);
        entry.final_pattern = Some("git reset --soft".to_string());

        let id = db.log_suggestion_audit(&entry).unwrap();
        assert!(id > 0);

        // Query and verify the final_pattern was stored
        let results = db
            .query_suggestion_audits(10, Some(SuggestionAction::Modified))
            .unwrap();
        assert_eq!(results.len(), 1);
        assert_eq!(
            results[0].final_pattern,
            Some("git reset --soft".to_string())
        );
    }

    #[test]
    fn test_count_suggestion_audits_returns_accurate_count() {
        let db = HistoryDb::open_in_memory().unwrap();

        // Insert multiple entries
        for _ in 0..5 {
            let entry = test_suggestion_audit_entry(SuggestionAction::Accepted);
            db.log_suggestion_audit(&entry).unwrap();
        }
        for _ in 0..3 {
            let entry = test_suggestion_audit_entry(SuggestionAction::Rejected);
            db.log_suggestion_audit(&entry).unwrap();
        }

        let count = db.count_suggestion_audits().unwrap();
        assert_eq!(count, 8);
    }

    #[test]
    fn test_query_suggestion_audits_returns_all_when_no_filter() {
        let db = HistoryDb::open_in_memory().unwrap();

        db.log_suggestion_audit(&test_suggestion_audit_entry(SuggestionAction::Accepted))
            .unwrap();
        db.log_suggestion_audit(&test_suggestion_audit_entry(SuggestionAction::Modified))
            .unwrap();
        db.log_suggestion_audit(&test_suggestion_audit_entry(SuggestionAction::Rejected))
            .unwrap();

        let results = db.query_suggestion_audits(100, None).unwrap();
        assert_eq!(results.len(), 3);
    }

    #[test]
    fn test_query_suggestion_audits_filters_by_action() {
        let db = HistoryDb::open_in_memory().unwrap();

        // Insert entries with different actions
        for _ in 0..4 {
            db.log_suggestion_audit(&test_suggestion_audit_entry(SuggestionAction::Accepted))
                .unwrap();
        }
        for _ in 0..2 {
            db.log_suggestion_audit(&test_suggestion_audit_entry(SuggestionAction::Modified))
                .unwrap();
        }
        db.log_suggestion_audit(&test_suggestion_audit_entry(SuggestionAction::Rejected))
            .unwrap();

        // Filter by Accepted
        let accepted = db
            .query_suggestion_audits(100, Some(SuggestionAction::Accepted))
            .unwrap();
        assert_eq!(accepted.len(), 4);
        assert!(
            accepted
                .iter()
                .all(|e| e.action == SuggestionAction::Accepted)
        );

        // Filter by Modified
        let modified = db
            .query_suggestion_audits(100, Some(SuggestionAction::Modified))
            .unwrap();
        assert_eq!(modified.len(), 2);
        assert!(
            modified
                .iter()
                .all(|e| e.action == SuggestionAction::Modified)
        );

        // Filter by Rejected
        let rejected = db
            .query_suggestion_audits(100, Some(SuggestionAction::Rejected))
            .unwrap();
        assert_eq!(rejected.len(), 1);
        assert!(
            rejected
                .iter()
                .all(|e| e.action == SuggestionAction::Rejected)
        );
    }

    #[test]
    fn test_query_suggestion_audits_respects_limit() {
        let db = HistoryDb::open_in_memory().unwrap();

        // Insert 10 entries
        for _ in 0..10 {
            db.log_suggestion_audit(&test_suggestion_audit_entry(SuggestionAction::Accepted))
                .unwrap();
        }

        // Query with limit of 5
        let results = db.query_suggestion_audits(5, None).unwrap();
        assert_eq!(results.len(), 5);
    }

    #[test]
    fn test_query_suggestion_audits_orders_by_timestamp_desc() {
        let db = HistoryDb::open_in_memory().unwrap();

        // Insert entries with different timestamps
        for i in 0..3 {
            let mut entry = test_suggestion_audit_entry(SuggestionAction::Accepted);
            entry.timestamp = Utc::now() - Duration::hours(i);
            entry.pattern = format!("pattern-{i}");
            db.log_suggestion_audit(&entry).unwrap();
        }

        let results = db.query_suggestion_audits(100, None).unwrap();
        assert_eq!(results.len(), 3);
        // Most recent first (pattern-0 has the newest timestamp)
        assert_eq!(results[0].pattern, "pattern-0");
        assert_eq!(results[1].pattern, "pattern-1");
        assert_eq!(results[2].pattern, "pattern-2");
    }

    #[test]
    fn test_suggestion_audit_stores_all_fields() {
        let db = HistoryDb::open_in_memory().unwrap();

        let entry = SuggestionAuditEntry {
            timestamp: Utc::now(),
            action: SuggestionAction::Accepted,
            pattern: "rm -rf /".to_string(),
            final_pattern: Some("rm -rf ./temp".to_string()),
            risk_level: "critical".to_string(),
            risk_score: 0.99,
            confidence_tier: "strong".to_string(),
            confidence_points: 20,
            cluster_frequency: 100,
            unique_variants: 5,
            sample_commands: "rm -rf /, rm -rf ~".to_string(),
            rule_id: Some("rm-rf-001".to_string()),
            session_id: Some("ses-xyz789".to_string()),
            working_dir: Some("/dangerous/path".to_string()),
        };

        db.log_suggestion_audit(&entry).unwrap();

        let results = db.query_suggestion_audits(1, None).unwrap();
        assert_eq!(results.len(), 1);

        let stored = &results[0];
        assert_eq!(stored.action, SuggestionAction::Accepted);
        assert_eq!(stored.pattern, "rm -rf /");
        assert_eq!(stored.final_pattern, Some("rm -rf ./temp".to_string()));
        assert_eq!(stored.risk_level, "critical");
        assert!((stored.risk_score - 0.99).abs() < 0.001);
        assert_eq!(stored.confidence_tier, "strong");
        assert_eq!(stored.confidence_points, 20);
        assert_eq!(stored.cluster_frequency, 100);
        assert_eq!(stored.unique_variants, 5);
        assert_eq!(stored.sample_commands, "rm -rf /, rm -rf ~");
        assert_eq!(stored.rule_id, Some("rm-rf-001".to_string()));
        assert_eq!(stored.session_id, Some("ses-xyz789".to_string()));
        assert_eq!(stored.working_dir, Some("/dangerous/path".to_string()));
    }

    #[test]
    fn test_suggestion_audit_with_null_optional_fields() {
        let db = HistoryDb::open_in_memory().unwrap();

        let entry = SuggestionAuditEntry {
            timestamp: Utc::now(),
            action: SuggestionAction::Rejected,
            pattern: "test pattern".to_string(),
            final_pattern: None,
            risk_level: "low".to_string(),
            risk_score: 0.1,
            confidence_tier: "weak".to_string(),
            confidence_points: 2,
            cluster_frequency: 5,
            unique_variants: 1,
            sample_commands: "test".to_string(),
            rule_id: None,
            session_id: None,
            working_dir: None,
        };

        db.log_suggestion_audit(&entry).unwrap();

        let results = db.query_suggestion_audits(1, None).unwrap();
        assert_eq!(results.len(), 1);

        let stored = &results[0];
        assert_eq!(stored.final_pattern, None);
        assert_eq!(stored.rule_id, None);
        assert_eq!(stored.session_id, None);
        assert_eq!(stored.working_dir, None);
    }

    // ==========================================================================
    // Interactive Allowlist Audit Tests
    // ==========================================================================

    fn test_interactive_audit_entry(
        option_type: InteractiveAllowlistOptionType,
    ) -> InteractiveAllowlistAuditEntry {
        InteractiveAllowlistAuditEntry {
            timestamp: Utc::now(),
            command: "git reset --hard HEAD~1".to_string(),
            pattern_added: "core.git:reset-hard".to_string(),
            option_type,
            option_detail: Some("target=rule;scope=all directories;layer=project".to_string()),
            config_file: "/home/user/project/.dcg/allowlist.toml".to_string(),
            cwd: Some("/home/user/project".to_string()),
            user: Some("tester".to_string()),
        }
    }

    #[test]
    fn test_log_interactive_allowlist_audit_inserts_entry() {
        let db = HistoryDb::open_in_memory().unwrap();
        let entry = test_interactive_audit_entry(InteractiveAllowlistOptionType::Exact);

        let id = db.log_interactive_allowlist_audit(&entry).unwrap();
        assert!(id > 0, "should return a positive ID");

        let count = db.count_interactive_allowlist_audits().unwrap();
        assert_eq!(count, 1);
    }

    #[test]
    fn test_query_interactive_allowlist_audits_filters_by_option_type() {
        let db = HistoryDb::open_in_memory().unwrap();

        for _ in 0..2 {
            db.log_interactive_allowlist_audit(&test_interactive_audit_entry(
                InteractiveAllowlistOptionType::Exact,
            ))
            .unwrap();
        }
        for _ in 0..3 {
            db.log_interactive_allowlist_audit(&test_interactive_audit_entry(
                InteractiveAllowlistOptionType::Temporary,
            ))
            .unwrap();
        }

        let all = db.query_interactive_allowlist_audits(100, None).unwrap();
        assert_eq!(all.len(), 5);

        let temporary = db
            .query_interactive_allowlist_audits(
                100,
                Some(InteractiveAllowlistOptionType::Temporary),
            )
            .unwrap();
        assert_eq!(temporary.len(), 3);
        assert!(
            temporary
                .iter()
                .all(|e| e.option_type == InteractiveAllowlistOptionType::Temporary)
        );
    }

    #[test]
    fn test_interactive_allowlist_option_type_parse_aliases() {
        assert_eq!(
            InteractiveAllowlistOptionType::parse("exact"),
            Some(InteractiveAllowlistOptionType::Exact)
        );
        assert_eq!(
            InteractiveAllowlistOptionType::parse("temporary"),
            Some(InteractiveAllowlistOptionType::Temporary)
        );
        assert_eq!(
            InteractiveAllowlistOptionType::parse("path-specific"),
            Some(InteractiveAllowlistOptionType::PathSpecific)
        );
        assert_eq!(
            InteractiveAllowlistOptionType::parse("path"),
            Some(InteractiveAllowlistOptionType::PathSpecific)
        );
        assert_eq!(InteractiveAllowlistOptionType::parse("unknown"), None);
    }

    // ============================================================================
    // Rule Metrics Unit Tests (1dri.3)
    // ============================================================================

    /// Helper to insert a command with a specific `rule_id` and outcome.
    fn insert_rule_entry(
        db: &HistoryDb,
        rule_id: &str,
        outcome: Outcome,
        timestamp: DateTime<Utc>,
        command: &str,
    ) {
        let (pack_id, pattern_name) = rule_id.split_once(':').unwrap_or((rule_id, "pattern"));
        let entry = CommandEntry {
            timestamp,
            agent_type: "test_agent".to_string(),
            working_dir: "/test".to_string(),
            command: command.to_string(),
            outcome,
            pack_id: Some(pack_id.to_string()),
            pattern_name: Some(pattern_name.to_string()),
            rule_id: Some(rule_id.to_string()),
            ..Default::default()
        };
        db.log_command(&entry).unwrap();
    }

    #[test]
    fn test_get_rule_metrics_basic() {
        let db = HistoryDb::open_in_memory().unwrap();
        let now = Utc::now();

        // Insert commands for different rules
        for i in 0..5 {
            insert_rule_entry(
                &db,
                "core.git:reset-hard",
                Outcome::Deny,
                now,
                &format!("cmd-a-{i}"),
            );
        }
        for i in 0..3 {
            insert_rule_entry(
                &db,
                "core.filesystem:rm-rf",
                Outcome::Deny,
                now,
                &format!("cmd-b-{i}"),
            );
        }

        let metrics = db.get_rule_metrics(None, 100).unwrap();

        assert_eq!(metrics.len(), 2);
        // Ordered by total_hits descending
        assert_eq!(metrics[0].rule_id, "core.git:reset-hard");
        assert_eq!(metrics[0].total_hits, 5);
        assert_eq!(metrics[1].rule_id, "core.filesystem:rm-rf");
        assert_eq!(metrics[1].total_hits, 3);
    }

    #[test]
    fn test_get_rule_metrics_with_limit() {
        let db = HistoryDb::open_in_memory().unwrap();
        let now = Utc::now();

        // Insert commands for 5 different rules
        for (i, rule) in ["rule:a", "rule:b", "rule:c", "rule:d", "rule:e"]
            .iter()
            .enumerate()
        {
            for j in 0..(5 - i) {
                insert_rule_entry(&db, rule, Outcome::Deny, now, &format!("cmd-{i}-{j}"));
            }
        }

        // Limit to top 3
        let metrics = db.get_rule_metrics(None, 3).unwrap();
        assert_eq!(metrics.len(), 3);
        assert_eq!(metrics[0].total_hits, 5);
        assert_eq!(metrics[1].total_hits, 4);
        assert_eq!(metrics[2].total_hits, 3);
    }

    #[test]
    fn test_get_rule_metrics_with_since_filter() {
        let db = HistoryDb::open_in_memory().unwrap();
        let now = Utc::now();
        let old = now - Duration::days(10);
        let recent = now - Duration::hours(1);

        // Insert old commands
        insert_rule_entry(&db, "pack:old-rule", Outcome::Deny, old, "old-cmd-1");
        insert_rule_entry(&db, "pack:old-rule", Outcome::Deny, old, "old-cmd-2");

        // Insert recent commands
        insert_rule_entry(&db, "pack:new-rule", Outcome::Deny, recent, "new-cmd-1");
        insert_rule_entry(&db, "pack:new-rule", Outcome::Deny, recent, "new-cmd-2");
        insert_rule_entry(&db, "pack:new-rule", Outcome::Deny, recent, "new-cmd-3");

        // Query with since filter (last 7 days)
        let since = now - Duration::days(7);
        let metrics = db.get_rule_metrics(Some(since), 100).unwrap();

        assert_eq!(metrics.len(), 1);
        assert_eq!(metrics[0].rule_id, "pack:new-rule");
        assert_eq!(metrics[0].total_hits, 3);
    }

    #[test]
    fn test_get_rule_metrics_override_rate() {
        let db = HistoryDb::open_in_memory().unwrap();
        let now = Utc::now();

        // Insert 10 denials and 5 bypasses for the same rule
        for i in 0..10 {
            insert_rule_entry(
                &db,
                "test:override-rule",
                Outcome::Deny,
                now,
                &format!("deny-{i}"),
            );
        }
        for i in 0..5 {
            insert_rule_entry(
                &db,
                "test:override-rule",
                Outcome::Bypass,
                now,
                &format!("bypass-{i}"),
            );
        }

        let metrics = db.get_rule_metrics(None, 100).unwrap();
        assert_eq!(metrics.len(), 1);
        assert_eq!(metrics[0].total_hits, 15);
        assert_eq!(metrics[0].allowlist_overrides, 5);
        // 5/15 = 33.33%
        assert!((metrics[0].override_rate - 33.333).abs() < 0.1);
    }

    #[test]
    fn test_get_rule_metrics_noisy_threshold() {
        let db = HistoryDb::open_in_memory().unwrap();
        let now = Utc::now();

        // Create a noisy rule (> 30% override rate)
        for i in 0..7 {
            insert_rule_entry(&db, "pack:noisy", Outcome::Deny, now, &format!("deny-{i}"));
        }
        for i in 0..3 {
            insert_rule_entry(
                &db,
                "pack:noisy",
                Outcome::Bypass,
                now,
                &format!("bypass-{i}"),
            );
        }

        // Create a non-noisy rule (< 30% override rate)
        for i in 0..9 {
            insert_rule_entry(
                &db,
                "pack:quiet",
                Outcome::Deny,
                now,
                &format!("deny-q-{i}"),
            );
        }
        insert_rule_entry(&db, "pack:quiet", Outcome::Bypass, now, "bypass-q-1");

        let metrics = db.get_rule_metrics(None, 100).unwrap();
        let noisy = metrics.iter().find(|m| m.rule_id == "pack:noisy").unwrap();
        let quiet = metrics.iter().find(|m| m.rule_id == "pack:quiet").unwrap();

        // 3/10 = 30%, which is >= NOISY_THRESHOLD
        assert!(noisy.is_noisy);
        // 1/10 = 10%, which is < NOISY_THRESHOLD
        assert!(!quiet.is_noisy);
    }

    #[test]
    fn test_get_rule_metrics_unique_commands() {
        let db = HistoryDb::open_in_memory().unwrap();
        let now = Utc::now();

        // Same command multiple times (should count as 1 unique)
        for _ in 0..5 {
            insert_rule_entry(&db, "pack:repeated", Outcome::Deny, now, "same-command");
        }

        // Different commands
        for i in 0..3 {
            insert_rule_entry(
                &db,
                "pack:varied",
                Outcome::Deny,
                now,
                &format!("unique-cmd-{i}"),
            );
        }

        let metrics = db.get_rule_metrics(None, 100).unwrap();
        let repeated = metrics
            .iter()
            .find(|m| m.rule_id == "pack:repeated")
            .unwrap();
        let varied = metrics.iter().find(|m| m.rule_id == "pack:varied").unwrap();

        assert_eq!(repeated.total_hits, 5);
        assert_eq!(repeated.unique_commands, 1);
        assert_eq!(varied.total_hits, 3);
        assert_eq!(varied.unique_commands, 3);
    }

    #[test]
    fn test_get_rule_metrics_for_rule_exists() {
        let db = HistoryDb::open_in_memory().unwrap();
        let now = Utc::now();

        insert_rule_entry(&db, "core.git:force-push", Outcome::Deny, now, "cmd-1");
        insert_rule_entry(&db, "core.git:force-push", Outcome::Deny, now, "cmd-2");
        insert_rule_entry(&db, "core.git:force-push", Outcome::Bypass, now, "cmd-3");

        let metrics = db.get_rule_metrics_for_rule("core.git:force-push").unwrap();
        assert!(metrics.is_some());
        let m = metrics.unwrap();
        assert_eq!(m.total_hits, 3);
        assert_eq!(m.allowlist_overrides, 1);
        assert_eq!(m.unique_commands, 3);
    }

    #[test]
    fn test_get_rule_metrics_for_rule_not_found() {
        let db = HistoryDb::open_in_memory().unwrap();
        let now = Utc::now();

        insert_rule_entry(&db, "core.git:reset-hard", Outcome::Deny, now, "cmd-1");

        // When querying a non-existent rule, total_hits will be 0 and the function returns None
        let metrics = db.get_rule_metrics_for_rule("nonexistent:rule").unwrap();
        // The implementation returns None for rules with 0 hits
        assert!(metrics.is_none());
    }

    #[test]
    fn test_get_noisiest_rules() {
        let db = HistoryDb::open_in_memory().unwrap();
        let now = Utc::now();

        // Create rules with varying override rates
        // Rule A: 50% override rate (5 deny, 5 bypass) - very noisy
        for i in 0..5 {
            insert_rule_entry(
                &db,
                "pack:rule-a",
                Outcome::Deny,
                now,
                &format!("a-deny-{i}"),
            );
        }
        for i in 0..5 {
            insert_rule_entry(
                &db,
                "pack:rule-a",
                Outcome::Bypass,
                now,
                &format!("a-bypass-{i}"),
            );
        }

        // Rule B: 40% override rate (6 deny, 4 bypass)
        for i in 0..6 {
            insert_rule_entry(
                &db,
                "pack:rule-b",
                Outcome::Deny,
                now,
                &format!("b-deny-{i}"),
            );
        }
        for i in 0..4 {
            insert_rule_entry(
                &db,
                "pack:rule-b",
                Outcome::Bypass,
                now,
                &format!("b-bypass-{i}"),
            );
        }

        // Rule C: 10% override rate (9 deny, 1 bypass) - less noisy
        for i in 0..9 {
            insert_rule_entry(
                &db,
                "pack:rule-c",
                Outcome::Deny,
                now,
                &format!("c-deny-{i}"),
            );
        }
        insert_rule_entry(&db, "pack:rule-c", Outcome::Bypass, now, "c-bypass-1");

        let noisy = db.get_noisiest_rules(10).unwrap();

        // get_noisiest_rules returns all rules >= MIN_HITS_FOR_TREND, ordered by override rate desc
        // It does NOT filter by NOISY_THRESHOLD - it just orders by noisiness
        assert_eq!(noisy.len(), 3);
        // Ordered by override rate descending
        assert_eq!(noisy[0].rule_id, "pack:rule-a");
        assert!((noisy[0].override_rate - 50.0).abs() < 0.1);
        assert_eq!(noisy[1].rule_id, "pack:rule-b");
        assert!((noisy[1].override_rate - 40.0).abs() < 0.1);
        assert_eq!(noisy[2].rule_id, "pack:rule-c");
        assert!((noisy[2].override_rate - 10.0).abs() < 0.1);
    }

    #[test]
    fn test_get_noisiest_rules_respects_limit() {
        let db = HistoryDb::open_in_memory().unwrap();
        let now = Utc::now();

        // Create 5 noisy rules
        for rule_num in 0..5 {
            let rule_id = format!("pack:noisy-{rule_num}");
            // Each rule has 50% override rate
            for i in 0..5 {
                insert_rule_entry(
                    &db,
                    &rule_id,
                    Outcome::Deny,
                    now,
                    &format!("deny-{rule_num}-{i}"),
                );
            }
            for i in 0..5 {
                insert_rule_entry(
                    &db,
                    &rule_id,
                    Outcome::Bypass,
                    now,
                    &format!("bypass-{rule_num}-{i}"),
                );
            }
        }

        let noisy = db.get_noisiest_rules(3).unwrap();
        assert_eq!(noisy.len(), 3);
    }

    #[test]
    fn test_get_noisiest_rules_minimum_hits() {
        let db = HistoryDb::open_in_memory().unwrap();
        let now = Utc::now();

        // Rule with high override rate but too few hits (< MIN_HITS_FOR_TREND = 5)
        insert_rule_entry(&db, "pack:few-hits", Outcome::Deny, now, "deny-1");
        insert_rule_entry(&db, "pack:few-hits", Outcome::Bypass, now, "bypass-1");
        insert_rule_entry(&db, "pack:few-hits", Outcome::Bypass, now, "bypass-2");
        // 2/3 = 66% but only 3 hits

        // Rule with enough hits
        for i in 0..5 {
            insert_rule_entry(
                &db,
                "pack:enough-hits",
                Outcome::Deny,
                now,
                &format!("deny-{i}"),
            );
        }
        for i in 0..5 {
            insert_rule_entry(
                &db,
                "pack:enough-hits",
                Outcome::Bypass,
                now,
                &format!("bypass-{i}"),
            );
        }

        let noisy = db.get_noisiest_rules(10).unwrap();

        // Only the rule with >= 5 hits should appear
        assert_eq!(noisy.len(), 1);
        assert_eq!(noisy[0].rule_id, "pack:enough-hits");
    }

    #[test]
    fn test_rule_metrics_first_and_last_seen() {
        let db = HistoryDb::open_in_memory().unwrap();
        let now = Utc::now();
        let earlier = now - Duration::days(5);
        let later = now - Duration::hours(1);

        insert_rule_entry(&db, "pack:time-test", Outcome::Deny, earlier, "first-cmd");
        insert_rule_entry(
            &db,
            "pack:time-test",
            Outcome::Deny,
            now - Duration::days(2),
            "middle-cmd",
        );
        insert_rule_entry(&db, "pack:time-test", Outcome::Deny, later, "last-cmd");

        let metrics = db.get_rule_metrics(None, 100).unwrap();
        assert_eq!(metrics.len(), 1);

        let m = &metrics[0];
        // First seen should be the earliest timestamp
        assert!(m.first_seen <= earlier + Duration::seconds(1));
        // Last seen should be the latest timestamp
        assert!(m.last_seen >= later - Duration::seconds(1));
    }

    #[test]
    fn test_rule_trend_stable_insufficient_data() {
        let db = HistoryDb::open_in_memory().unwrap();
        let now = Utc::now();

        // Only 3 hits - below MIN_HITS_FOR_TREND threshold
        for i in 0..3 {
            insert_rule_entry(&db, "pack:few", Outcome::Deny, now, &format!("cmd-{i}"));
        }

        let metrics = db.get_rule_metrics(None, 100).unwrap();
        assert_eq!(metrics[0].trend, RuleTrend::Stable);
    }

    #[test]
    fn test_rule_metrics_empty_database() {
        let db = HistoryDb::open_in_memory().unwrap();

        let metrics = db.get_rule_metrics(None, 100).unwrap();
        assert!(metrics.is_empty());

        let noisy = db.get_noisiest_rules(10).unwrap();
        assert!(noisy.is_empty());
    }

    #[test]
    fn test_rule_metrics_only_allow_outcomes_excluded() {
        let db = HistoryDb::open_in_memory().unwrap();
        let now = Utc::now();

        // Only allow outcomes (no rule_id typically set)
        let entry = CommandEntry {
            timestamp: now,
            agent_type: "test".to_string(),
            working_dir: "/test".to_string(),
            command: "git status".to_string(),
            outcome: Outcome::Allow,
            rule_id: None, // Allow typically has no rule_id
            ..Default::default()
        };
        db.log_command(&entry).unwrap();

        let metrics = db.get_rule_metrics(None, 100).unwrap();
        // Should be empty since we filter on rule_id IS NOT NULL
        assert!(metrics.is_empty());
    }

    #[test]
    fn test_rule_metrics_mixed_packs() {
        let db = HistoryDb::open_in_memory().unwrap();
        let now = Utc::now();

        // Multiple rules from different packs
        insert_rule_entry(&db, "core.git:reset-hard", Outcome::Deny, now, "git-1");
        insert_rule_entry(&db, "core.git:force-push", Outcome::Deny, now, "git-2");
        insert_rule_entry(&db, "core.filesystem:rm-rf", Outcome::Deny, now, "fs-1");
        insert_rule_entry(
            &db,
            "containers.docker:prune",
            Outcome::Deny,
            now,
            "docker-1",
        );
        insert_rule_entry(
            &db,
            "containers.docker:prune",
            Outcome::Deny,
            now,
            "docker-2",
        );

        let metrics = db.get_rule_metrics(None, 100).unwrap();
        assert_eq!(metrics.len(), 4);

        // Verify all packs represented
        let rule_ids: Vec<&str> = metrics.iter().map(|m| m.rule_id.as_str()).collect();
        assert!(rule_ids.contains(&"core.git:reset-hard"));
        assert!(rule_ids.contains(&"core.git:force-push"));
        assert!(rule_ids.contains(&"core.filesystem:rm-rf"));
        assert!(rule_ids.contains(&"containers.docker:prune"));
    }

    #[test]
    fn test_rule_metrics_contains_trending_fields() {
        let db = HistoryDb::open_in_memory().unwrap();
        let now = Utc::now();

        // Insert data for a rule with enough hits for trend calculation
        for i in 0..10 {
            let entry = CommandEntry {
                command: format!("git reset --hard HEAD~{i}"),
                outcome: Outcome::Deny,
                agent_type: "test".to_string(),
                working_dir: "/test".to_string(),
                pack_id: Some("core.git".to_string()),
                pattern_name: Some("reset-hard".to_string()),
                rule_id: Some("core.git:reset-hard".to_string()),
                timestamp: now - chrono::Duration::hours(i),
                ..Default::default()
            };
            db.log_command(&entry).unwrap();
        }

        let metrics = db.get_rule_metrics(None, 10).unwrap();
        assert_eq!(metrics.len(), 1);

        let m = &metrics[0];
        // Trending fields should be present and initialized
        // previous_period_hits is 0 since no data from 7-14 days ago
        assert_eq!(m.previous_period_hits, 0);
        // change_percentage and is_anomaly depend on previous data
        // With no previous period data, check they have reasonable defaults
        assert!(m.change_percentage.is_finite());
    }

    #[test]
    fn test_rule_metrics_change_percentage_with_trend_data() {
        let db = HistoryDb::open_in_memory().unwrap();
        let now = Utc::now();

        // Insert data from 10 days ago (previous period: 7-14 days)
        for i in 0..5 {
            let entry = CommandEntry {
                command: format!("git reset --hard HEAD~{i}"),
                outcome: Outcome::Deny,
                agent_type: "test".to_string(),
                working_dir: "/test".to_string(),
                pack_id: Some("core.git".to_string()),
                pattern_name: Some("reset-hard".to_string()),
                rule_id: Some("core.git:reset-hard".to_string()),
                timestamp: now - chrono::Duration::days(10) + chrono::Duration::hours(i64::from(i)),
                ..Default::default()
            };
            db.log_command(&entry).unwrap();
        }

        // Insert data from 3 days ago (recent period: 0-7 days)
        for i in 0..10 {
            let entry = CommandEntry {
                command: format!("git reset --hard HEAD~{i}"),
                outcome: Outcome::Deny,
                agent_type: "test".to_string(),
                working_dir: "/test".to_string(),
                pack_id: Some("core.git".to_string()),
                pattern_name: Some("reset-hard".to_string()),
                rule_id: Some("core.git:reset-hard".to_string()),
                timestamp: now - chrono::Duration::days(3) + chrono::Duration::hours(i64::from(i)),
                ..Default::default()
            };
            db.log_command(&entry).unwrap();
        }

        let metrics = db.get_rule_metrics(None, 10).unwrap();
        assert_eq!(metrics.len(), 1);

        let m = &metrics[0];
        // 5 hits in previous period, 10 in recent = 100% increase
        assert_eq!(m.previous_period_hits, 5);
        assert!((m.change_percentage - 100.0).abs() < 0.1);
        // 100% is not >= 200%, so not an anomaly
        assert!(!m.is_anomaly);
    }

    #[test]
    fn test_rule_metrics_anomaly_detection() {
        let db = HistoryDb::open_in_memory().unwrap();
        let now = Utc::now();

        // Insert 2 hits from 10 days ago (previous period)
        for i in 0..2 {
            let entry = CommandEntry {
                command: format!("git reset --hard HEAD~{i}"),
                outcome: Outcome::Deny,
                agent_type: "test".to_string(),
                working_dir: "/test".to_string(),
                pack_id: Some("core.git".to_string()),
                pattern_name: Some("reset-hard".to_string()),
                rule_id: Some("core.git:reset-hard".to_string()),
                timestamp: now - chrono::Duration::days(10) + chrono::Duration::hours(i64::from(i)),
                ..Default::default()
            };
            db.log_command(&entry).unwrap();
        }

        // Insert 10 hits from 3 days ago (recent period) - 400% increase
        for i in 0..10 {
            let entry = CommandEntry {
                command: format!("git reset --hard HEAD~{i}"),
                outcome: Outcome::Deny,
                agent_type: "test".to_string(),
                working_dir: "/test".to_string(),
                pack_id: Some("core.git".to_string()),
                pattern_name: Some("reset-hard".to_string()),
                rule_id: Some("core.git:reset-hard".to_string()),
                timestamp: now - chrono::Duration::days(3) + chrono::Duration::hours(i64::from(i)),
                ..Default::default()
            };
            db.log_command(&entry).unwrap();
        }

        let metrics = db.get_rule_metrics(None, 10).unwrap();
        let m = &metrics[0];

        // 2 hits previous, 10 recent = (10-2)/2 * 100 = 400% change
        assert_eq!(m.previous_period_hits, 2);
        assert!((m.change_percentage - 400.0).abs() < 0.1);
        // 400% >= 200% threshold, so is_anomaly should be true
        assert!(m.is_anomaly);
    }

    #[test]
    fn test_get_rule_metrics_for_rule_includes_trending_fields() {
        let db = HistoryDb::open_in_memory().unwrap();
        let now = Utc::now();

        // Insert enough data for a rule
        for i in 0..RuleMetrics::MIN_HITS_FOR_TREND {
            let entry = CommandEntry {
                command: format!("git reset --hard HEAD~{i}"),
                outcome: Outcome::Deny,
                agent_type: "test".to_string(),
                working_dir: "/test".to_string(),
                pack_id: Some("core.git".to_string()),
                pattern_name: Some("reset-hard".to_string()),
                rule_id: Some("core.git:reset-hard".to_string()),
                timestamp: now - chrono::Duration::hours(i64::try_from(i).unwrap_or(i64::MAX)),
                ..Default::default()
            };
            db.log_command(&entry).unwrap();
        }

        let m = db
            .get_rule_metrics_for_rule("core.git:reset-hard")
            .unwrap()
            .unwrap();

        // Verify trending fields are populated
        assert!(m.change_percentage.is_finite());
        // previous_period_hits should be 0 (no data 7-14 days ago)
        assert_eq!(m.previous_period_hits, 0);
    }

    #[test]
    fn test_get_noisiest_rules_includes_trending_fields() {
        let db = HistoryDb::open_in_memory().unwrap();
        let now = Utc::now();

        // Create a noisy rule with high bypass rate
        for i in 0..10 {
            let outcome = if i < 8 {
                Outcome::Bypass
            } else {
                Outcome::Deny
            };
            let entry = CommandEntry {
                command: format!("git clean -fdx {i}"),
                outcome,
                agent_type: "test".to_string(),
                working_dir: "/test".to_string(),
                pack_id: Some("core.git".to_string()),
                pattern_name: Some("clean-force".to_string()),
                rule_id: Some("core.git:clean-force".to_string()),
                timestamp: now - chrono::Duration::hours(i64::from(i)),
                ..Default::default()
            };
            db.log_command(&entry).unwrap();
        }

        let metrics = db.get_noisiest_rules(10).unwrap();
        assert_eq!(metrics.len(), 1);

        let m = &metrics[0];
        // Verify trending fields exist
        assert!(m.change_percentage.is_finite());
        assert_eq!(m.previous_period_hits, 0);
    }
}