coding-agent-search 0.6.2

Unified TUI search over local coding agent histories
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
use anyhow::{Context, Result, bail};
use console::{Term, style};
use dialoguer::{Confirm, Input, MultiSelect, Password, Select, theme::ColorfulTheme};
use indicatif::{ProgressBar, ProgressStyle};
use std::io::Write;
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use std::time::Duration;

use crate::pages::bundle::{BundleBuilder, BundleConfig};
use crate::pages::confirmation::{
    ConfirmationConfig, ConfirmationFlow, ConfirmationStep, PasswordStrengthAction, StepValidation,
    UNENCRYPTED_ACK_PHRASE, unencrypted_warning_lines, validate_unencrypted_ack,
};
use crate::pages::deploy_cloudflare::{CloudflareConfig, CloudflareDeployer};
use crate::pages::deploy_github::GitHubDeployer;
use crate::pages::docs::{DocConfig, DocumentationGenerator};
use crate::pages::encrypt::EncryptionEngine;
use crate::pages::export::{ExportEngine, ExportFilter, PathMode};
use crate::pages::password::{PasswordStrength, format_strength_inline, validate_password};
use crate::pages::secret_scan::{
    SecretScanConfig, SecretScanFilters, print_human_report, wizard_secret_scan,
};
use crate::pages::size::{BundleVerifier, SizeEstimate, SizeLimitResult};
use crate::pages::summary::{
    ExclusionSet, PrePublishSummary, SummaryFilters, SummaryGenerator, format_size,
};
use crate::storage::sqlite::FrankenStorage;
use frankensqlite::Connection;

/// Deployment target for the export
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DeployTarget {
    Local,
    GitHubPages,
    CloudflarePages,
}

impl std::fmt::Display for DeployTarget {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            DeployTarget::Local => write!(f, "Local export only"),
            DeployTarget::GitHubPages => write!(f, "GitHub Pages"),
            DeployTarget::CloudflarePages => write!(f, "Cloudflare Pages"),
        }
    }
}

/// Wizard state tracking all configuration
#[derive(Clone)]
pub struct WizardState {
    // Content selection
    pub agents: Vec<String>,
    pub time_range: Option<String>,
    pub workspaces: Option<Vec<PathBuf>>,

    // Security configuration
    pub password: Option<String>,
    pub recovery_secret: Option<Vec<u8>>,
    pub generate_recovery: bool,
    pub generate_qr: bool,

    // Site configuration
    pub title: String,
    pub description: String,
    pub hide_metadata: bool,

    // Deployment
    pub target: DeployTarget,
    pub output_dir: PathBuf,
    pub repo_name: Option<String>,

    // Database path
    pub db_path: PathBuf,

    // Pre-publish summary and exclusions
    pub exclusions: ExclusionSet,
    pub last_summary: Option<PrePublishSummary>,

    // Secret scan results
    pub secret_scan_has_findings: bool,
    pub secret_scan_has_critical: bool,
    pub secret_scan_count: usize,

    // Password entropy
    pub password_entropy_bits: f64,

    // Unencrypted export mode (DANGEROUS)
    pub no_encryption: bool,
    pub unencrypted_confirmed: bool,

    // Cloudflare Pages deployment
    pub cloudflare_branch: Option<String>,
    pub cloudflare_account_id: Option<String>,
    pub cloudflare_api_token: Option<String>,

    // Final output location (set after export)
    pub final_site_dir: Option<PathBuf>,
}

impl std::fmt::Debug for WizardState {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("WizardState")
            .field("agents", &self.agents)
            .field("time_range", &self.time_range)
            .field("workspaces", &self.workspaces)
            .field("password", &self.password.as_ref().map(|_| "[REDACTED]"))
            .field(
                "recovery_secret",
                &self.recovery_secret.as_ref().map(|_| "[REDACTED]"),
            )
            .field("generate_recovery", &self.generate_recovery)
            .field("generate_qr", &self.generate_qr)
            .field("title", &self.title)
            .field("description", &self.description)
            .field("hide_metadata", &self.hide_metadata)
            .field("target", &self.target)
            .field("output_dir", &self.output_dir)
            .field("repo_name", &self.repo_name)
            .field("db_path", &self.db_path)
            .field("exclusions", &self.exclusions)
            .field("last_summary", &self.last_summary)
            .field("secret_scan_has_findings", &self.secret_scan_has_findings)
            .field("secret_scan_has_critical", &self.secret_scan_has_critical)
            .field("secret_scan_count", &self.secret_scan_count)
            .field("password_entropy_bits", &self.password_entropy_bits)
            .field("no_encryption", &self.no_encryption)
            .field("unencrypted_confirmed", &self.unencrypted_confirmed)
            .field("cloudflare_branch", &self.cloudflare_branch)
            .field("cloudflare_account_id", &self.cloudflare_account_id)
            .field(
                "cloudflare_api_token",
                &self.cloudflare_api_token.as_ref().map(|_| "[REDACTED]"),
            )
            .field("final_site_dir", &self.final_site_dir)
            .finish()
    }
}

impl Default for WizardState {
    fn default() -> Self {
        let db_path = crate::default_db_path();

        Self {
            agents: Vec::new(),
            time_range: None,
            workspaces: None,
            password: None,
            recovery_secret: None,
            generate_recovery: true,
            generate_qr: false,
            title: "cass Archive".to_string(),
            description: "Encrypted archive of AI coding agent conversations".to_string(),
            hide_metadata: false,
            target: DeployTarget::Local,
            output_dir: PathBuf::from("cass-export"),
            repo_name: None,
            db_path,
            exclusions: ExclusionSet::new(),
            last_summary: None,
            secret_scan_has_findings: false,
            secret_scan_has_critical: false,
            secret_scan_count: 0,
            password_entropy_bits: 0.0,
            no_encryption: false,
            unencrypted_confirmed: false,
            cloudflare_branch: None,
            cloudflare_account_id: None,
            cloudflare_api_token: None,
            final_site_dir: None,
        }
    }
}

fn truncate_sample_title(title: &str) -> String {
    if title.len() > 30 {
        format!("{}...", &title[..title.floor_char_boundary(27)])
    } else {
        title.to_string()
    }
}

pub struct PagesWizard {
    state: WizardState,
    no_encryption_mode: bool,
}

impl Default for PagesWizard {
    fn default() -> Self {
        Self::new()
    }
}

impl PagesWizard {
    pub fn new() -> Self {
        Self {
            state: WizardState::default(),
            no_encryption_mode: false,
        }
    }

    /// Override the database path used for agent/workspace discovery and export.
    pub fn set_db_path(&mut self, db_path: PathBuf) {
        self.state.db_path = db_path;
    }

    /// Set whether to skip encryption (DANGEROUS - requires explicit confirmation).
    pub fn set_no_encryption(&mut self, no_encryption: bool) {
        self.no_encryption_mode = no_encryption;
        self.state.no_encryption = no_encryption;
    }

    /// Set the deployment target.
    pub fn set_deploy_target(&mut self, target: DeployTarget) {
        self.state.target = target;
    }

    /// Set the repository/project name for deployment.
    pub fn set_repo_name(&mut self, name: String) {
        self.state.repo_name = Some(name);
    }

    /// Set the Cloudflare Pages branch.
    pub fn set_cloudflare_branch(&mut self, branch: String) {
        self.state.cloudflare_branch = Some(branch);
    }

    /// Set the Cloudflare account ID.
    pub fn set_cloudflare_account_id(&mut self, account_id: String) {
        self.state.cloudflare_account_id = Some(account_id);
    }

    /// Set the Cloudflare API token.
    pub fn set_cloudflare_api_token(&mut self, api_token: String) {
        self.state.cloudflare_api_token = Some(api_token);
    }

    pub fn run(&mut self) -> Result<()> {
        let mut term = Term::stdout();
        let theme = ColorfulTheme::default();

        term.clear_screen()?;
        self.print_header(&mut term)?;

        if self.no_encryption_mode && !self.step_unencrypted_warning(&mut term, &theme)? {
            writeln!(term, "{}", style("Export cancelled.").yellow())?;
            return Ok(());
        }

        // Step 1: Content Selection
        self.step_content_selection(&mut term, &theme)?;

        // Step 2: Secret Scan
        self.step_secret_scan(&mut term, &theme)?;

        // Step 3: Security Configuration
        if !self.no_encryption_mode {
            self.step_security_config(&mut term, &theme)?;
        } else {
            self.state.generate_recovery = false;
            self.state.generate_qr = false;
        }

        // Step 4: Site Configuration
        self.step_site_config(&mut term, &theme)?;

        // Step 5: Deployment Target
        self.step_deployment_target(&mut term, &theme)?;

        // Step 6: Pre-Publish Summary
        if !self.step_summary(&mut term, &theme)? {
            writeln!(term, "{}", style("Export cancelled.").yellow())?;
            return Ok(());
        }

        // Step 7: Safety Confirmation
        if !self.no_encryption_mode && !self.step_confirmation(&mut term, &theme)? {
            writeln!(term, "{}", style("Export cancelled.").yellow())?;
            return Ok(());
        }

        // Step 8: Export Progress
        self.step_export(&mut term)?;

        // Step 9: Deploy (if not local)
        self.step_deploy(&mut term)?;

        Ok(())
    }

    /// Step for unencrypted export warning and confirmation.
    fn step_unencrypted_warning(&mut self, term: &mut Term, theme: &ColorfulTheme) -> Result<bool> {
        writeln!(term)?;
        writeln!(term, "{}", style("⚠️  SECURITY WARNING").red().bold())?;
        writeln!(term, "{}", style("".repeat(60)).red())?;
        writeln!(term)?;

        for line in unencrypted_warning_lines() {
            if line.is_empty() {
                writeln!(term)?;
            } else {
                writeln!(term, "  {}", line)?;
            }
        }

        writeln!(term)?;
        writeln!(term, "{}", style("".repeat(60)).red())?;
        writeln!(term)?;
        writeln!(term, "To proceed with unencrypted export, type exactly:")?;
        writeln!(term)?;
        writeln!(term, "  {}", style(UNENCRYPTED_ACK_PHRASE).cyan().bold())?;
        writeln!(term)?;

        loop {
            let input: String = Input::with_theme(theme)
                .with_prompt("Your input (or \"cancel\" to abort)")
                .interact_text()?;

            if input.trim().to_lowercase() == "cancel" {
                return Ok(false);
            }

            match validate_unencrypted_ack(&input) {
                StepValidation::Passed => {
                    // Additional y/N confirmation
                    writeln!(term)?;
                    let confirmed = Confirm::with_theme(theme)
                        .with_prompt(
                            "Are you ABSOLUTELY SURE you want to export WITHOUT encryption?",
                        )
                        .default(false)
                        .interact()?;

                    if !confirmed {
                        writeln!(term)?;
                        writeln!(
                            term,
                            "  {}",
                            style("Good choice. Export cancelled.").green()
                        )?;
                        writeln!(
                            term,
                            "  Remove --no-encryption to export with encryption (recommended)."
                        )?;
                        return Ok(false);
                    }

                    self.state.unencrypted_confirmed = true;
                    writeln!(term)?;
                    writeln!(
                        term,
                        "  {} Unencrypted export acknowledged",
                        style("").yellow()
                    )?;
                    writeln!(
                        term,
                        "  {}",
                        style("Proceeding without encryption...").dim()
                    )?;
                    return Ok(true);
                }
                StepValidation::Failed(msg) => {
                    writeln!(term, "  {} {}", style("").red(), msg)?;
                }
            }
        }
    }

    fn print_header(&self, term: &mut Term) -> Result<()> {
        writeln!(
            term,
            "{}",
            style("🔐 cass Pages Export Wizard").bold().cyan()
        )?;
        writeln!(
            term,
            "Create an encrypted, searchable web archive of your AI coding agent conversations."
        )?;
        writeln!(term)?;
        Ok(())
    }

    fn step_content_selection(&mut self, term: &mut Term, theme: &ColorfulTheme) -> Result<()> {
        writeln!(term, "\n{}", style("Step 1 of 9: Content Selection").bold())?;
        writeln!(term, "{}", style("".repeat(40)).dim())?;

        // Load agents dynamically from database
        let storage = FrankenStorage::open_readonly(&self.state.db_path)
            .context("Failed to open database. Run 'cass index' first.")?;
        let db_agents = storage.list_agents()?;
        let db_workspaces = storage.list_workspaces()?;
        drop(storage);

        if db_agents.is_empty() {
            writeln!(
                term,
                "{}",
                style("⚠ No agents found in database. Run 'cass index' first.").red()
            )?;
            bail!("No agents found in database");
        }

        // Build agent display list with conversation counts
        let agent_items: Vec<String> = db_agents
            .iter()
            .map(|a| format!("{} ({})", a.name, a.slug))
            .collect();

        let selected_agents = MultiSelect::with_theme(theme)
            .with_prompt("Which agents would you like to include?")
            .items(&agent_items)
            .defaults(&vec![true; agent_items.len()])
            .interact()?;

        self.state.agents = selected_agents
            .iter()
            .map(|&i| db_agents[i].slug.clone())
            .collect();

        if self.state.agents.is_empty() {
            bail!("No agents selected. Export cancelled.");
        }

        writeln!(
            term,
            "  {} {} agents selected",
            style("").green(),
            self.state.agents.len()
        )?;

        // Workspace selection (optional)
        self.state.workspaces = None;
        if !db_workspaces.is_empty() {
            let include_all = Confirm::with_theme(theme)
                .with_prompt("Include all workspaces?")
                .default(true)
                .interact()?;

            if !include_all {
                let workspace_items: Vec<String> = db_workspaces
                    .iter()
                    .map(|w| {
                        w.display_name
                            .clone()
                            .unwrap_or_else(|| w.path.to_string_lossy().to_string())
                    })
                    .collect();

                let selected_ws = MultiSelect::with_theme(theme)
                    .with_prompt("Select workspaces to include:")
                    .items(&workspace_items)
                    .interact()?;

                self.state.workspaces = Some(
                    selected_ws
                        .iter()
                        .map(|&i| db_workspaces[i].path.clone())
                        .collect(),
                );
                writeln!(
                    term,
                    "  {} {} workspaces selected",
                    style("").green(),
                    selected_ws.len()
                )?;
                if selected_ws.is_empty() {
                    writeln!(
                        term,
                        "  {} No workspaces selected. The export will contain no conversations.",
                        style("").yellow()
                    )?;
                }
            }
        }

        // Time Range
        let time_options = vec![
            "All time",
            "Last 7 days",
            "Last 30 days",
            "Last 90 days",
            "Last year",
        ];
        let time_selection = Select::with_theme(theme)
            .with_prompt("Time range")
            .default(0)
            .items(&time_options)
            .interact()?;

        self.state.time_range = match time_selection {
            1 => Some("-7d".to_string()),
            2 => Some("-30d".to_string()),
            3 => Some("-90d".to_string()),
            4 => Some("-365d".to_string()),
            _ => None,
        };

        writeln!(
            term,
            "  {} Time range: {}",
            style("").green(),
            time_options[time_selection]
        )?;

        Ok(())
    }

    fn step_secret_scan(&mut self, term: &mut Term, theme: &ColorfulTheme) -> Result<()> {
        writeln!(term, "\n{}", style("Step 2 of 9: Secret Scan").bold())?;
        writeln!(term, "{}", style("".repeat(40)).dim())?;

        let since_ts = self
            .state
            .time_range
            .as_deref()
            .and_then(crate::ui::time_parser::parse_time_input);

        let filters = SecretScanFilters {
            agents: if self.state.agents.is_empty() {
                None
            } else {
                Some(self.state.agents.clone())
            },
            workspaces: self.state.workspaces.clone(),
            since_ts,
            until_ts: None,
        };

        let config = SecretScanConfig::from_inputs(&[], &[])?;
        if !config.allowlist_raw.is_empty() || !config.denylist_raw.is_empty() {
            writeln!(
                term,
                "  {} Allowlist patterns: {} | Denylist patterns: {}",
                style("").blue(),
                config.allowlist_raw.len(),
                config.denylist_raw.len()
            )?;
        }

        let report = wizard_secret_scan(&self.state.db_path, &filters, &config)?;
        print_human_report(term, &report, 3)?;

        // Save secret scan results to state for confirmation flow
        self.state.secret_scan_has_findings = report.summary.total > 0;
        self.state.secret_scan_has_critical = report.summary.has_critical;
        self.state.secret_scan_count = report.summary.total;

        if report.summary.has_critical {
            writeln!(
                term,
                "  {} Critical secrets detected. Export is blocked without acknowledgement.",
                style("").red()
            )?;
            let ack: String = Input::with_theme(theme)
                .with_prompt("Type \"I UNDERSTAND\" to proceed")
                .interact_text()?;
            if ack.trim() != "I UNDERSTAND" {
                bail!("Export cancelled due to critical secrets");
            }
            writeln!(term, "  {} Acknowledged", style("").green())?;
        }

        Ok(())
    }

    fn step_security_config(&mut self, term: &mut Term, theme: &ColorfulTheme) -> Result<()> {
        writeln!(
            term,
            "\n{}",
            style("Step 3 of 9: Security Configuration").bold()
        )?;
        writeln!(term, "{}", style("".repeat(40)).dim())?;

        // Password
        let password = Password::with_theme(theme)
            .with_prompt("Archive password (min 8 characters)")
            .with_confirmation("Confirm password", "Passwords don't match")
            .validate_with(|input: &String| -> Result<(), &str> {
                if input.chars().count() >= 8 {
                    Ok(())
                } else {
                    Err("Password must be at least 8 characters")
                }
            })
            .interact()?;

        self.state.password = Some(password.clone());
        writeln!(term, "  {} Password set", style("").green())?;

        // Validate password using new password strength module
        let validation = validate_password(&password);

        // Calculate and save password entropy for confirmation flow
        self.state.password_entropy_bits = validation.entropy_bits;

        // Show password strength indicator with visual bar
        writeln!(
            term,
            "    Password strength: {}",
            format_strength_inline(&validation)
        )?;
        writeln!(term, "    Entropy: {:.0} bits", validation.entropy_bits)?;

        // Show improvement suggestions if not strong
        if validation.strength != PasswordStrength::Strong && !validation.suggestions.is_empty() {
            writeln!(term, "    {}", style("Suggestions:").dim())?;
            for suggestion in &validation.suggestions {
                writeln!(
                    term,
                    "      {} {}",
                    style("").dim(),
                    style(suggestion).dim()
                )?;
            }
        }

        // Recovery secret
        self.state.generate_recovery = Confirm::with_theme(theme)
            .with_prompt("Generate recovery secret? (recommended)")
            .default(true)
            .interact()?;

        if self.state.generate_recovery {
            writeln!(
                term,
                "  {} Recovery secret will be generated",
                style("").green()
            )?;
        }

        // QR code
        self.state.generate_qr = Confirm::with_theme(theme)
            .with_prompt("Generate QR code for recovery? (for mobile access)")
            .default(false)
            .interact()?;

        if self.state.generate_qr {
            writeln!(term, "  {} QR code will be generated", style("").green())?;
        }

        Ok(())
    }

    fn step_site_config(&mut self, term: &mut Term, theme: &ColorfulTheme) -> Result<()> {
        writeln!(
            term,
            "\n{}",
            style("Step 4 of 9: Site Configuration").bold()
        )?;
        writeln!(term, "{}", style("".repeat(40)).dim())?;

        // Title
        self.state.title = Input::with_theme(theme)
            .with_prompt("Archive title")
            .default(self.state.title.clone())
            .interact_text()?;

        writeln!(term, "  {} Title: {}", style("").green(), self.state.title)?;

        // Description
        self.state.description = Input::with_theme(theme)
            .with_prompt("Description (shown on unlock page)")
            .default(self.state.description.clone())
            .interact_text()?;

        writeln!(term, "  {} Description set", style("").green())?;

        // Metadata privacy
        self.state.hide_metadata = Confirm::with_theme(theme)
            .with_prompt("Hide workspace paths and file names? (for privacy)")
            .default(false)
            .interact()?;

        if self.state.hide_metadata {
            writeln!(term, "  {} Metadata will be obfuscated", style("").green())?;
        }

        Ok(())
    }

    fn step_deployment_target(&mut self, term: &mut Term, theme: &ColorfulTheme) -> Result<()> {
        writeln!(term, "\n{}", style("Step 5 of 9: Deployment Target").bold())?;
        writeln!(term, "{}", style("".repeat(40)).dim())?;

        let targets = vec![
            "Local export only (generate files)",
            "GitHub Pages (requires gh CLI)",
            "Cloudflare Pages (requires wrangler CLI)",
        ];

        let target_selection = Select::with_theme(theme)
            .with_prompt("Where would you like to deploy?")
            .default(0)
            .items(&targets)
            .interact()?;

        self.state.target = match target_selection {
            1 => DeployTarget::GitHubPages,
            2 => DeployTarget::CloudflarePages,
            _ => DeployTarget::Local,
        };

        writeln!(
            term,
            "  {} Target: {}",
            style("").green(),
            self.state.target
        )?;

        // Output directory
        self.state.output_dir = PathBuf::from(
            Input::<String>::with_theme(theme)
                .with_prompt("Output directory")
                .default("cass-export".to_string())
                .interact_text()?,
        );

        writeln!(
            term,
            "  {} Output: {}",
            style("").green(),
            self.state.output_dir.display()
        )?;

        // Repository name for remote deployment
        if self.state.target != DeployTarget::Local {
            let default_repo = format!("cass-archive-{}", chrono::Utc::now().format("%Y%m%d"));
            let repo_name = Input::<String>::with_theme(theme)
                .with_prompt("Repository/project name")
                .default(default_repo)
                .interact_text()?;
            self.state.repo_name = Some(repo_name.clone());

            writeln!(term, "  {} Repo: {}", style("").green(), repo_name)?;
        }

        Ok(())
    }

    fn step_summary(&mut self, term: &mut Term, theme: &ColorfulTheme) -> Result<bool> {
        writeln!(
            term,
            "\n{}",
            style("Step 6 of 9: Pre-Publish Summary").bold()
        )?;
        writeln!(term, "{}", style("".repeat(40)).dim())?;

        // Generate comprehensive summary from database
        writeln!(term, "\n  Generating summary...")?;
        let summary = self.generate_prepublish_summary()?;
        self.state.last_summary = Some(summary.clone());

        // Display content overview
        writeln!(term, "\n{}", style("📊 CONTENT OVERVIEW").bold().cyan())?;
        writeln!(term, "{}", style("".repeat(40)).dim())?;
        writeln!(
            term,
            "  Conversations: {}",
            style(summary.total_conversations).green()
        )?;
        writeln!(
            term,
            "  Messages:      {}",
            style(summary.total_messages).green()
        )?;
        writeln!(
            term,
            "  Characters:    {} (~{})",
            summary.total_characters,
            format_size(summary.total_characters)
        )?;
        writeln!(
            term,
            "  Archive Size:  ~{} (estimated, compressed + encrypted)",
            style(format_size(summary.estimated_size_bytes)).yellow()
        )?;

        // Display date range
        writeln!(term, "\n{}", style("📅 DATE RANGE").bold().cyan())?;
        writeln!(term, "{}", style("".repeat(40)).dim())?;
        if let (Some(earliest), Some(latest)) =
            (&summary.earliest_timestamp, &summary.latest_timestamp)
        {
            let days = (*latest - *earliest).num_days();
            writeln!(
                term,
                "  From: {}  To: {}  ({} days)",
                style(earliest.format("%Y-%m-%d")).white(),
                style(latest.format("%Y-%m-%d")).white(),
                days
            )?;

            // Show activity histogram (simplified sparkline)
            if !summary.date_histogram.is_empty() {
                let bars = ["", "", "", "", "", "", "", ""];

                // Group by month for display
                let mut months: std::collections::BTreeMap<String, usize> =
                    std::collections::BTreeMap::new();
                for entry in &summary.date_histogram {
                    if entry.date.len() >= 7 {
                        let month = &entry.date[0..7];
                        *months.entry(month.to_string()).or_insert(0) += entry.message_count;
                    }
                }

                if !months.is_empty() {
                    let month_max = months.values().max().copied().unwrap_or(1).max(1);
                    let sparkline: String = months
                        .values()
                        .map(|&count| {
                            let idx = (count * 7 / month_max).min(7);
                            bars[idx]
                        })
                        .collect();
                    writeln!(term, "  Activity: {}", style(sparkline).cyan())?;
                }
            }
        } else {
            writeln!(term, "  No date information available")?;
        }

        // Display workspaces
        writeln!(
            term,
            "\n{} ({})",
            style("📁 WORKSPACES").bold().cyan(),
            summary.workspaces.len()
        )?;
        writeln!(term, "{}", style("".repeat(40)).dim())?;
        for (_idx, ws) in summary.workspaces.iter().enumerate().take(5) {
            let included_marker =
                if ws.included && !self.state.exclusions.is_workspace_excluded(&ws.path) {
                    style("").green()
                } else {
                    style("").red()
                };
            writeln!(
                term,
                "  {} {} ({} conversations)",
                included_marker,
                style(&ws.display_name).white(),
                ws.conversation_count
            )?;
            if !ws.sample_titles.is_empty() {
                let titles: Vec<_> = ws
                    .sample_titles
                    .iter()
                    .take(2)
                    .map(|t| truncate_sample_title(t))
                    .collect();
                writeln!(
                    term,
                    "      {}",
                    style(format!("\"{}\"", titles.join("\", \""))).dim()
                )?;
            }
        }
        if summary.workspaces.len() > 5 {
            writeln!(
                term,
                "  {} and {} more...",
                style("...").dim(),
                summary.workspaces.len() - 5
            )?;
        }

        // Display agents
        writeln!(term, "\n{}", style("🤖 AGENTS").bold().cyan())?;
        writeln!(term, "{}", style("".repeat(40)).dim())?;
        for agent in &summary.agents {
            writeln!(
                term,
                "{}: {} conversations ({:.0}%)",
                style(&agent.name).white(),
                agent.conversation_count,
                agent.percentage
            )?;
        }

        // Display security status
        writeln!(term, "\n{}", style("🔒 SECURITY").bold().cyan())?;
        writeln!(term, "{}", style("".repeat(40)).dim())?;
        if let Some(enc) = &summary.encryption_config {
            writeln!(term, "  Encryption: {}", enc.algorithm)?;
            writeln!(term, "  Key Derivation: {}", enc.key_derivation)?;
            writeln!(term, "  Key Slots: {}", enc.key_slot_count)?;
        } else {
            writeln!(term, "  Encryption: AES-256-GCM")?;
            writeln!(term, "  Key Derivation: Argon2id")?;
        }

        // Secret scan status
        let secret_status = if summary.secret_scan.total_findings == 0 {
            style("✓ No secrets detected".to_string()).green()
        } else if summary.secret_scan.has_critical {
            style(format!(
                "⚠️  {} issues (CRITICAL)",
                summary.secret_scan.total_findings
            ))
            .red()
        } else {
            style(format!(
                "⚠️  {} issues found",
                summary.secret_scan.total_findings
            ))
            .yellow()
        };
        writeln!(term, "  Secret Scan: {}", secret_status)?;

        // Configuration summary
        writeln!(term, "\n{}", style("⚙️  CONFIGURATION").bold().cyan())?;
        writeln!(term, "{}", style("".repeat(40)).dim())?;
        writeln!(term, "  Title: {}", self.state.title)?;
        writeln!(term, "  Target: {}", self.state.target)?;
        writeln!(term, "  Output: {}", self.state.output_dir.display())?;
        writeln!(
            term,
            "  Recovery Key: {}",
            if self.state.generate_recovery {
                "Yes"
            } else {
                "No"
            }
        )?;
        writeln!(
            term,
            "  QR Code: {}",
            if self.state.generate_qr { "Yes" } else { "No" }
        )?;

        // Exclusion summary
        let (ws_excluded, conv_excluded, pattern_excluded) =
            self.state.exclusions.exclusion_counts();
        if ws_excluded > 0 || conv_excluded > 0 || pattern_excluded > 0 {
            writeln!(term, "\n{}", style("🚫 EXCLUSIONS").bold().yellow())?;
            writeln!(term, "{}", style("".repeat(40)).dim())?;
            if ws_excluded > 0 {
                writeln!(term, "  {} workspace(s) excluded", ws_excluded)?;
            }
            if conv_excluded > 0 {
                writeln!(term, "  {} conversation(s) excluded", conv_excluded)?;
            }
            if pattern_excluded > 0 {
                writeln!(term, "  {} pattern(s) active", pattern_excluded)?;
            }
        }

        writeln!(term)?;

        // Options menu
        loop {
            let options = vec![
                "✓ Proceed with export",
                "📁 View/Edit workspace exclusions",
                "✗ Cancel export",
            ];

            let selection = Select::with_theme(theme)
                .with_prompt("What would you like to do?")
                .items(&options)
                .default(0)
                .interact()?;

            match selection {
                0 => return Ok(true), // Proceed
                1 => {
                    // Edit workspace exclusions
                    self.edit_workspace_exclusions(term, theme, &summary)?;
                }
                2 => return Ok(false), // Cancel
                _ => unreachable!(),
            }
        }
    }

    /// Generate the pre-publish summary from the database.
    fn generate_prepublish_summary(&self) -> Result<PrePublishSummary> {
        let conn = Connection::open(self.state.db_path.to_string_lossy().as_ref())
            .context("Failed to open database for summary generation")?;

        conn.execute_batch(
            "PRAGMA busy_timeout = 5000;
             PRAGMA journal_mode = WAL;",
        )
        .context("Failed to set PRAGMAs for summary generation")?;

        let since_ts = self
            .state
            .time_range
            .as_deref()
            .and_then(crate::ui::time_parser::parse_time_input);

        let filters = SummaryFilters {
            agents: if self.state.agents.is_empty() {
                None
            } else {
                Some(self.state.agents.clone())
            },
            workspaces: self
                .state
                .workspaces
                .as_ref()
                .map(|ws| ws.iter().map(|p| p.to_string_lossy().to_string()).collect()),
            since_ts,
            until_ts: None,
        };

        let generator = SummaryGenerator::new(&conn);
        let summary = generator.generate_with_exclusions(Some(&filters), &self.state.exclusions)?;

        Ok(summary)
    }

    /// Interactive workspace exclusion editing.
    fn edit_workspace_exclusions(
        &mut self,
        term: &mut Term,
        theme: &ColorfulTheme,
        summary: &PrePublishSummary,
    ) -> Result<()> {
        writeln!(term, "\n{}", style("Workspace Exclusions").bold())?;
        writeln!(term, "{}", style("".repeat(40)).dim())?;

        if summary.workspaces.is_empty() {
            writeln!(term, "  No workspaces to configure.")?;
            return Ok(());
        }

        // Build list of workspaces with current inclusion status
        let items: Vec<String> = summary
            .workspaces
            .iter()
            .map(|ws| {
                format!(
                    "{} ({} conversations)",
                    ws.display_name, ws.conversation_count
                )
            })
            .collect();

        // Determine which are currently selected (included)
        let defaults: Vec<bool> = summary
            .workspaces
            .iter()
            .map(|ws| !self.state.exclusions.is_workspace_excluded(&ws.path))
            .collect();

        let selections = MultiSelect::with_theme(theme)
            .with_prompt("Select workspaces to INCLUDE (unselected will be excluded)")
            .items(&items)
            .defaults(&defaults)
            .interact()?;

        // Update exclusions based on selections
        for (idx, ws) in summary.workspaces.iter().enumerate() {
            if selections.contains(&idx) {
                // Include this workspace (remove from exclusions)
                self.state.exclusions.include_workspace(&ws.path);
            } else {
                // Exclude this workspace
                self.state.exclusions.exclude_workspace(&ws.path);
            }
        }

        let (ws_excluded, _, _) = self.state.exclusions.exclusion_counts();
        writeln!(
            term,
            "  {} {} workspace(s) now excluded",
            style("").green(),
            ws_excluded
        )?;

        Ok(())
    }

    /// Multi-step safety confirmation flow.
    fn step_confirmation(&mut self, term: &mut Term, theme: &ColorfulTheme) -> Result<bool> {
        writeln!(
            term,
            "\n{}",
            style("Step 7 of 9: Safety Confirmation").bold()
        )?;
        writeln!(term, "{}", style("".repeat(40)).dim())?;

        // Build confirmation configuration
        let target_domain = if self.state.target != DeployTarget::Local {
            self.state
                .repo_name
                .as_ref()
                .map(|name| match self.state.target {
                    DeployTarget::GitHubPages => format!("{}.github.io", name),
                    DeployTarget::CloudflarePages => format!("{}.pages.dev", name),
                    DeployTarget::Local => String::new(),
                })
        } else {
            None
        };

        let summary = if let Some(summary) = self.state.last_summary.clone() {
            summary
        } else {
            let generated = self
                .generate_prepublish_summary()
                .context("Failed to generate pre-publish summary for confirmation")?;
            self.state.last_summary = Some(generated.clone());
            generated
        };

        let config = ConfirmationConfig {
            has_secrets: self.state.secret_scan_has_findings,
            has_critical_secrets: self.state.secret_scan_has_critical,
            secret_count: self.state.secret_scan_count,
            target_domain,
            is_remote_publish: self.state.target != DeployTarget::Local,
            password_entropy_bits: self.state.password_entropy_bits,
            has_recovery_key: self.state.generate_recovery,
            recovery_key_phrase: None, // Will be set after generation
            summary,
        };

        let mut flow = ConfirmationFlow::new(config);

        // Process each confirmation step
        loop {
            match flow.current_step() {
                ConfirmationStep::SecretScanAcknowledgment => {
                    if !self.confirm_secret_ack(term, theme, &flow)? {
                        return Ok(false);
                    }
                    flow.complete_current_step();
                }
                ConfirmationStep::ContentReview => {
                    if !self.confirm_content_review(term, theme, &flow)? {
                        return Ok(false);
                    }
                    flow.complete_current_step();
                }
                ConfirmationStep::PublicPublishingWarning => {
                    if !self.confirm_public_warning(term, theme, &flow)? {
                        return Ok(false);
                    }
                    flow.complete_current_step();
                }
                ConfirmationStep::PasswordStrengthWarning => {
                    match self.confirm_password_strength(term, theme, &mut flow)? {
                        PasswordStrengthAction::SetStronger => {
                            // User wants to set a stronger password - go back
                            writeln!(
                                term,
                                "\n  {} Returning to security configuration...",
                                style("").cyan()
                            )?;
                            return Ok(false);
                        }
                        PasswordStrengthAction::ProceedAnyway => {
                            flow.complete_current_step();
                        }
                        PasswordStrengthAction::Abort => {
                            return Ok(false);
                        }
                    }
                }
                ConfirmationStep::RecoveryKeyBackup => {
                    if !self.confirm_recovery_key(term, theme, &flow)? {
                        return Ok(false);
                    }
                    flow.complete_current_step();
                }
                ConfirmationStep::FinalConfirmation => {
                    if !self.confirm_final(term, theme, &mut flow)? {
                        return Ok(false);
                    }
                    flow.complete_current_step();
                    break;
                }
            }
        }

        writeln!(
            term,
            "\n  {} All safety checks completed",
            style("").green()
        )?;
        Ok(true)
    }

    /// Confirm acknowledgment of detected secrets.
    fn confirm_secret_ack(
        &self,
        term: &mut Term,
        theme: &ColorfulTheme,
        flow: &ConfirmationFlow,
    ) -> Result<bool> {
        writeln!(
            term,
            "\n  {}",
            style("⚠️  SECRETS DETECTED").yellow().bold()
        )?;
        writeln!(term)?;
        writeln!(
            term,
            "  The secret scan found {} potential sensitive data item(s).",
            flow.config().secret_count
        )?;
        writeln!(term)?;
        writeln!(
            term,
            "  Even though the export will be encrypted, publishing content"
        )?;
        writeln!(term, "  containing secrets carries additional risk:")?;
        writeln!(term)?;
        writeln!(
            term,
            "  {} If your password is weak, secrets could be exposed",
            style("").yellow()
        )?;
        writeln!(
            term,
            "  {} Secrets may remain valid if encryption is ever compromised",
            style("").yellow()
        )?;
        writeln!(term)?;

        loop {
            let input: String = Input::with_theme(theme)
                .with_prompt("Type \"I understand the risks\" to proceed (or \"abort\" to cancel)")
                .interact_text()?;

            if input.trim().to_lowercase() == "abort" {
                return Ok(false);
            }

            match flow.validate_secret_ack(&input) {
                StepValidation::Passed => {
                    writeln!(term, "  {} Secrets acknowledged", style("").green())?;
                    return Ok(true);
                }
                StepValidation::Failed(msg) => {
                    writeln!(term, "  {} {}", style("").red(), msg)?;
                }
            }
        }
    }

    /// Confirm review of content summary.
    fn confirm_content_review(
        &self,
        term: &mut Term,
        theme: &ColorfulTheme,
        flow: &ConfirmationFlow,
    ) -> Result<bool> {
        writeln!(term, "\n  {}", style("📋 CONTENT REVIEW").cyan().bold())?;
        writeln!(term)?;
        writeln!(term, "  You are about to export:")?;
        writeln!(term)?;
        writeln!(
            term,
            "{} conversations from {} workspaces",
            flow.config().summary.total_conversations,
            flow.config().summary.workspaces.len()
        )?;
        writeln!(
            term,
            "{} messages",
            flow.config().summary.total_messages
        )?;
        writeln!(
            term,
            "  • Content from: {}",
            flow.config()
                .summary
                .agents
                .iter()
                .map(|a| a.name.as_str())
                .collect::<Vec<_>>()
                .join(", ")
        )?;
        writeln!(term)?;

        let confirmed = Confirm::with_theme(theme)
            .with_prompt("Have you reviewed the content summary?")
            .default(false)
            .interact()?;

        if confirmed {
            writeln!(term, "  {} Content reviewed", style("").green())?;
        }
        Ok(confirmed)
    }

    /// Confirm public publishing warning.
    fn confirm_public_warning(
        &self,
        term: &mut Term,
        theme: &ColorfulTheme,
        flow: &ConfirmationFlow,
    ) -> Result<bool> {
        let domain = flow
            .config()
            .target_domain
            .as_deref()
            .unwrap_or("your-site");

        writeln!(
            term,
            "\n  {}",
            style("🌐 PUBLIC PUBLISHING WARNING").yellow().bold()
        )?;
        writeln!(term)?;
        writeln!(term, "  You are about to publish to:")?;
        writeln!(term, "    {}", style(format!("https://{}/", domain)).cyan())?;
        writeln!(term)?;
        writeln!(
            term,
            "  {} This URL will be publicly accessible on the internet",
            style("").yellow()
        )?;
        writeln!(
            term,
            "  {} Anyone with the URL can download the encrypted archive",
            style("").yellow()
        )?;
        writeln!(
            term,
            "  {} The security depends entirely on your password strength",
            style("").yellow()
        )?;
        writeln!(term)?;

        loop {
            let input: String = Input::with_theme(theme)
                .with_prompt(format!(
                    "Type \"publish to {}\" to confirm (or \"abort\" to cancel)",
                    domain
                ))
                .interact_text()?;

            if input.trim().to_lowercase() == "abort" {
                return Ok(false);
            }

            match flow.validate_public_warning(&input) {
                StepValidation::Passed => {
                    writeln!(term, "  {} Public URL confirmed", style("").green())?;
                    return Ok(true);
                }
                StepValidation::Failed(msg) => {
                    writeln!(term, "  {} {}", style("").red(), msg)?;
                }
            }
        }
    }

    /// Handle password strength warning.
    fn confirm_password_strength(
        &self,
        term: &mut Term,
        theme: &ColorfulTheme,
        flow: &mut ConfirmationFlow,
    ) -> Result<PasswordStrengthAction> {
        writeln!(
            term,
            "\n  {}",
            style("🔐 PASSWORD STRENGTH WARNING").yellow().bold()
        )?;
        writeln!(term)?;
        writeln!(
            term,
            "  Your password has estimated entropy of {:.0} bits.",
            self.state.password_entropy_bits
        )?;
        writeln!(term)?;
        writeln!(term, "  Recommended minimum: 60 bits")?;
        writeln!(term)?;
        writeln!(
            term,
            "  A password with low entropy could potentially be cracked"
        )?;
        writeln!(
            term,
            "  by a determined attacker with sufficient resources."
        )?;
        writeln!(term)?;
        writeln!(term, "  For long-term security, consider:")?;
        writeln!(term, "  • Using a longer password (16+ characters)")?;
        writeln!(term, "  • Including numbers, symbols, and mixed case")?;
        writeln!(term, "  • Using a passphrase of 5+ random words")?;
        writeln!(term)?;

        let options = vec![
            "[S] Set a stronger password",
            "[P] Proceed with current password (not recommended)",
            "[A] Abort export",
        ];

        let selection = Select::with_theme(theme)
            .with_prompt("What would you like to do?")
            .items(&options)
            .default(0)
            .interact()?;

        let action = match selection {
            0 => PasswordStrengthAction::SetStronger,
            1 => {
                writeln!(
                    term,
                    "  {} Password warning acknowledged",
                    style("").yellow()
                )?;
                PasswordStrengthAction::ProceedAnyway
            }
            _ => PasswordStrengthAction::Abort,
        };

        flow.set_password_action(action);
        Ok(action)
    }

    /// Confirm recovery key backup.
    fn confirm_recovery_key(
        &self,
        term: &mut Term,
        theme: &ColorfulTheme,
        _flow: &ConfirmationFlow,
    ) -> Result<bool> {
        writeln!(
            term,
            "\n  {}",
            style("💾 RECOVERY KEY BACKUP").cyan().bold()
        )?;
        writeln!(term)?;
        writeln!(
            term,
            "  A recovery key will be generated. This is the ONLY way"
        )?;
        writeln!(term, "  to recover your data if you forget your password.")?;
        writeln!(term)?;
        writeln!(
            term,
            "  {} If you lose both your password AND the recovery key,",
            style("").yellow()
        )?;
        writeln!(term, "     your data will be permanently inaccessible.")?;
        writeln!(term)?;

        let confirmed = Confirm::with_theme(theme)
            .with_prompt("I understand that I must save the recovery key securely")
            .default(false)
            .interact()?;

        if confirmed {
            writeln!(
                term,
                "  {} Recovery key backup confirmed",
                style("").green()
            )?;
        }
        Ok(confirmed)
    }

    /// Final double-enter confirmation.
    fn confirm_final(
        &self,
        term: &mut Term,
        theme: &ColorfulTheme,
        flow: &mut ConfirmationFlow,
    ) -> Result<bool> {
        writeln!(term, "\n  {}", style("✓ FINAL CONFIRMATION").green().bold())?;
        writeln!(term)?;
        writeln!(term, "  Ready to publish:")?;
        writeln!(term)?;

        // Show completed steps
        for (_, label) in flow.completed_steps_summary() {
            writeln!(term, "  {} {}", style("").green(), label)?;
        }
        writeln!(term)?;

        // Show target info
        if self.state.target != DeployTarget::Local {
            if let Some(domain) = &flow.config().target_domain {
                writeln!(term, "  Target: https://{}/", domain)?;
            }
        } else {
            writeln!(
                term,
                "  Target: {} (local)",
                self.state.output_dir.display()
            )?;
        }

        if let Some(summary) = &self.state.last_summary {
            writeln!(
                term,
                "  Size: ~{}",
                format_size(summary.estimated_size_bytes)
            )?;
        }
        writeln!(term)?;

        writeln!(
            term,
            "  {}",
            style("Press Enter TWICE to confirm and begin export").dim()
        )?;
        writeln!(term)?;

        // First Enter
        let _: String = Input::with_theme(theme)
            .with_prompt("[First confirmation - press Enter]")
            .allow_empty(true)
            .interact_text()?;

        flow.process_final_enter();
        writeln!(term, "  {} First confirmation received", style("").cyan())?;

        // Second Enter
        let _: String = Input::with_theme(theme)
            .with_prompt("[Second confirmation - press Enter to proceed]")
            .allow_empty(true)
            .interact_text()?;

        flow.process_final_enter();
        writeln!(
            term,
            "  {} Second confirmation received",
            style("").green()
        )?;

        Ok(true)
    }

    fn step_export(&mut self, term: &mut Term) -> Result<()> {
        writeln!(term, "\n{}", style("Step 8 of 9: Export Progress").bold())?;
        writeln!(term, "{}", style("".repeat(40)).dim())?;

        // Phase 0: Size estimation and limit checking
        writeln!(term, "\n  Estimating export size...")?;

        let since_ts = self
            .state
            .time_range
            .as_deref()
            .and_then(crate::ui::time_parser::parse_time_input);

        let agents: Vec<String> = self.state.agents.to_vec();
        let estimate = SizeEstimate::from_database(
            &self.state.db_path,
            if agents.is_empty() {
                None
            } else {
                Some(&agents)
            },
            since_ts,
            None,
        )?;

        // Display estimate
        writeln!(term)?;
        for line in estimate.format_display().lines() {
            writeln!(term, "  {}", line)?;
        }
        writeln!(term)?;

        // Check limits
        match estimate.check_limits() {
            SizeLimitResult::Ok => {
                writeln!(term, "  {} Size within limits", style("").green())?;
            }
            SizeLimitResult::Warning(warning) => {
                writeln!(term, "  {} {}", style("").yellow(), warning)?;
                writeln!(term)?;

                let theme = ColorfulTheme::default();
                if !Confirm::with_theme(&theme)
                    .with_prompt("Continue with export?")
                    .default(true)
                    .interact()?
                {
                    bail!("Export cancelled due to size warning");
                }
            }
            SizeLimitResult::ExceedsLimit(error) => {
                writeln!(term)?;
                writeln!(term, "  {} {}", style("").red(), error)?;
                writeln!(term)?;
                bail!("Export blocked: {}", error);
            }
        }

        writeln!(term)?;

        // Stage export/encryption artifacts in a temp directory so the final
        // bundle root only contains deployable output (site/ + private/).
        let staging_dir = tempfile::tempdir()?;
        let export_db_path = staging_dir.path().join("export.db");
        let encrypted_dir = staging_dir.path().join("encrypted");
        std::fs::create_dir_all(&encrypted_dir)?;

        // Phase 1: Database Export with progress
        let pb = ProgressBar::new_spinner();
        let spinner_style = ProgressStyle::default_spinner()
            .template("{spinner:.cyan} {msg}")
            .context("build progress spinner style for export phase")?;
        pb.set_style(spinner_style);
        pb.enable_steady_tick(Duration::from_millis(100));
        pb.set_message("Filtering and exporting conversations...");

        // Build export filter with workspaces
        let workspaces = self.state.workspaces.clone();
        let since_dt = self.state.time_range.as_deref().and_then(|s| {
            crate::ui::time_parser::parse_time_input(s)
                .and_then(chrono::DateTime::from_timestamp_millis)
        });

        let filter = ExportFilter {
            agents: Some(self.state.agents.clone()),
            workspaces,
            since: since_dt,
            until: None,
            path_mode: if self.state.hide_metadata {
                PathMode::Hash
            } else {
                PathMode::Relative
            },
        };

        let engine = ExportEngine::new(&self.state.db_path, &export_db_path, filter);
        let running = Arc::new(AtomicBool::new(true));

        let stats = engine.execute(
            |current, total| {
                if total > 0 {
                    pb.set_message(format!("Exporting... {}/{} conversations", current, total));
                }
            },
            Some(running),
        )?;

        pb.finish_with_message(format!(
            "✓ Exported {} conversations, {} messages",
            stats.conversations_processed, stats.messages_processed
        ));

        // Phase 2: Encryption (skip if no_encryption mode)
        if self.no_encryption_mode {
            writeln!(term)?;
            writeln!(
                term,
                "  {} Skipping encryption (unencrypted mode)",
                style("").yellow()
            )?;
            writeln!(
                term,
                "  {}",
                style("WARNING: All content will be publicly readable!").red()
            )?;

            // For unencrypted mode, just copy the export.db to payload directory
            let payload_dir = encrypted_dir.join("payload");
            std::fs::create_dir_all(&payload_dir)?;
            let dest_db = payload_dir.join("data.db");
            std::fs::copy(&export_db_path, &dest_db)?;

            // Write minimal config.json for unencrypted bundle
            let db_size = std::fs::metadata(&dest_db).map(|m| m.len()).unwrap_or(0);
            let config = unencrypted_bundle_config(db_size);
            let config_path = encrypted_dir.join("config.json");
            crate::pages::write_file_durably(
                &config_path,
                serde_json::to_string_pretty(&config)?.as_bytes(),
            )?;
        } else {
            let pb2 = ProgressBar::new_spinner();
            let spinner_style = ProgressStyle::default_spinner()
                .template("{spinner:.cyan} {msg}")
                .context("build progress spinner style for encryption phase")?;
            pb2.set_style(spinner_style);
            pb2.enable_steady_tick(Duration::from_millis(100));
            pb2.set_message("Encrypting archive...");

            // Initialize encryption engine
            let mut enc_engine = EncryptionEngine::default();

            // Add password slot
            if let Some(password) = &self.state.password {
                enc_engine.add_password_slot(password)?;
            }

            // Generate and add recovery secret if requested
            if self.state.generate_recovery {
                let mut recovery_bytes = [0u8; 32];
                use rand::Rng;
                let mut rng = rand::rng();
                rng.fill_bytes(&mut recovery_bytes);
                enc_engine.add_recovery_slot(&recovery_bytes)?;
                self.state.recovery_secret = Some(recovery_bytes.to_vec());
            }

            // Guard: refuse to produce an archive with zero key slots
            if enc_engine.key_slot_count() == 0 {
                bail!(
                    "No encryption key slots configured — archive would be permanently undecryptable"
                );
            }

            // Encrypt the database
            enc_engine.encrypt_file(&export_db_path, &encrypted_dir, |_, _| {})?;

            pb2.finish_with_message("✓ Encryption complete");
        }

        // Phase 3: Build static site bundle
        let pb3 = ProgressBar::new_spinner();
        let spinner_style = ProgressStyle::default_spinner()
            .template("{spinner:.cyan} {msg}")
            .context("build progress spinner style for bundle phase")?;
        pb3.set_style(spinner_style);
        pb3.enable_steady_tick(Duration::from_millis(100));
        pb3.set_message("Building static site bundle...");

        // Generate documentation
        let generated_docs = if let Some(ref summary) = self.state.last_summary {
            // Determine target URL based on deployment target
            // Note: GitHub Pages URL requires the username which isn't known until deployment,
            // so we omit the URL for that target. The actual URL will be shown after deployment.
            let target_url = match self.state.target {
                DeployTarget::GitHubPages => None, // Username unknown at this stage
                DeployTarget::CloudflarePages => self
                    .state
                    .repo_name
                    .as_ref()
                    .map(|name| format!("https://{}.pages.dev", name)),
                DeployTarget::Local => None,
            };

            let doc_config = if let Some(url) = target_url {
                DocConfig::new().with_url(url)
            } else {
                DocConfig::new()
            };

            let doc_generator = DocumentationGenerator::new(doc_config, summary.clone());
            doc_generator.generate_all()
        } else {
            Vec::new()
        };

        // Create bundle configuration
        let bundle_config = BundleConfig {
            title: self.state.title.clone(),
            description: self.state.description.clone(),
            hide_metadata: self.state.hide_metadata,
            recovery_secret: self.state.recovery_secret.clone(),
            generate_qr: self.state.generate_qr,
            generated_docs,
        };

        let builder = BundleBuilder::with_config(bundle_config);
        let bundle_result =
            builder.build(&encrypted_dir, &self.state.output_dir, |phase, msg| {
                pb3.set_message(format!("{}: {}", phase, msg));
            })?;
        self.state.final_site_dir = Some(bundle_result.site_dir.clone());

        pb3.finish_with_message(format!(
            "✓ Bundle complete: {} files, fingerprint {}",
            bundle_result.total_files,
            bundle_result
                .fingerprint
                .get(..8)
                .unwrap_or(&bundle_result.fingerprint)
        ));

        // Phase 4: Post-export verification
        let warnings = BundleVerifier::verify(&bundle_result.site_dir)?;
        if !warnings.is_empty() {
            writeln!(term)?;
            writeln!(term, "  {} Size warnings:", style("").yellow())?;
            for warning in &warnings {
                writeln!(term, "    {}", warning)?;
            }
        }

        writeln!(term)?;
        writeln!(
            term,
            "  {} Site directory (deploy this): {}",
            style("").green(),
            style(bundle_result.site_dir.display()).cyan()
        )?;
        writeln!(
            term,
            "  {} Private directory (keep secure): {}",
            style("").green(),
            style(bundle_result.private_dir.display()).cyan()
        )?;
        writeln!(
            term,
            "  {} Integrity fingerprint: {}",
            style("").green(),
            style(&bundle_result.fingerprint).cyan()
        )?;

        // Display recovery secret location if generated
        if self.state.recovery_secret.is_some() {
            writeln!(term)?;
            writeln!(
                term,
                "  {} Recovery secret saved to: {}",
                style("").yellow().bold(),
                style(
                    bundle_result
                        .private_dir
                        .join("recovery-secret.txt")
                        .display()
                )
                .cyan()
            )?;
            writeln!(
                term,
                "  {}",
                style("Store this file securely - it can unlock your archive if you forget the password.").dim()
            )?;
        }

        if self.state.generate_qr {
            writeln!(
                term,
                "  {} QR codes saved to private directory",
                style("").green()
            )?;
        }

        Ok(())
    }

    fn deploy_site_dir(&self) -> PathBuf {
        self.state
            .final_site_dir
            .as_ref()
            .cloned()
            .unwrap_or_else(|| self.state.output_dir.join("site"))
    }

    fn deploy_project_name(&self) -> String {
        self.state
            .repo_name
            .clone()
            .unwrap_or_else(|| "cass-archive".to_string())
    }

    fn step_deploy(&self, term: &mut Term) -> Result<()> {
        writeln!(term, "\n{}", style("Step 9 of 9: Deployment").bold())?;
        writeln!(term, "{}", style("".repeat(40)).dim())?;

        match self.state.target {
            DeployTarget::Local => {
                let site_dir = self.deploy_site_dir();
                writeln!(term)?;
                writeln!(term, "{}", style("✓ Export complete!").green().bold())?;
                writeln!(term)?;
                writeln!(
                    term,
                    "Your archive bundle has been exported to: {}",
                    style(self.state.output_dir.display()).cyan()
                )?;
                writeln!(term)?;
                writeln!(
                    term,
                    "Deployable site directory: {}",
                    style(site_dir.display()).cyan()
                )?;
                writeln!(term)?;
                writeln!(term, "To preview locally, run:")?;
                writeln!(
                    term,
                    "  {}",
                    style(format!(
                        "cass pages --preview {} --no-open",
                        site_dir.display()
                    ))
                    .dim()
                )?;
                writeln!(term)?;
                writeln!(
                    term,
                    "Then open {} in your browser.",
                    style("http://localhost:8080").cyan()
                )?;
            }
            DeployTarget::GitHubPages => {
                writeln!(term, "  {} GitHub Pages deployment...", style("").cyan())?;
                let site_dir = self.deploy_site_dir();

                // Determine repository name
                let repo_name = self.deploy_project_name();

                // Configure the deployer
                let deployer = GitHubDeployer::new(repo_name.clone());

                // Check prerequisites first
                match deployer.check_prerequisites() {
                    Ok(prereqs) if prereqs.is_ready() => {
                        // Deploy with progress output
                        match deployer.deploy(&site_dir, |_phase, msg| {
                            let _ = writeln!(term, "    {} {}", style("").dim(), msg);
                        }) {
                            Ok(result) => {
                                writeln!(term)?;
                                writeln!(
                                    term,
                                    "  {} Deployed to GitHub Pages!",
                                    style("").green().bold()
                                )?;
                                writeln!(term)?;
                                writeln!(term, "  Repository: {}", style(&result.repo_url).cyan())?;
                                writeln!(
                                    term,
                                    "  Your archive is available at: {}",
                                    style(&result.pages_url).cyan().bold()
                                )?;
                            }
                            Err(e) => {
                                writeln!(term)?;
                                writeln!(term, "  {} Deployment failed: {}", style("").red(), e)?;
                                writeln!(term)?;
                                writeln!(
                                    term,
                                    "To deploy manually, push the {} directory to a gh-pages branch.",
                                    site_dir.display()
                                )?;
                            }
                        }
                    }
                    Ok(prereqs) => {
                        let missing = prereqs.missing();
                        writeln!(term)?;
                        writeln!(term, "  {} Prerequisites not met:", style("").yellow())?;
                        for item in &missing {
                            writeln!(term, "    {} {}", style("").dim(), item)?;
                        }
                        writeln!(term)?;
                        writeln!(
                            term,
                            "Please install/configure the missing tools and try again."
                        )?;
                        writeln!(
                            term,
                            "To deploy manually after fixing prerequisites, push the {} directory to a gh-pages branch.",
                            site_dir.display()
                        )?;
                    }
                    Err(e) => {
                        writeln!(term)?;
                        writeln!(
                            term,
                            "  {} Could not check prerequisites: {}",
                            style("").yellow(),
                            e
                        )?;
                        writeln!(term)?;
                        writeln!(
                            term,
                            "To deploy manually, push the {} directory to a gh-pages branch.",
                            site_dir.display()
                        )?;
                    }
                }
            }
            DeployTarget::CloudflarePages => {
                writeln!(
                    term,
                    "  {} Cloudflare Pages deployment...",
                    style("").cyan()
                )?;
                let site_dir = self.deploy_site_dir();

                // Determine project name from repo_name or use default
                let project_name = self.deploy_project_name();

                // Configure the deployer
                let deployer = CloudflareDeployer::new(CloudflareConfig {
                    project_name: project_name.clone(),
                    custom_domain: None,
                    create_if_missing: true,
                    branch: "main".to_string(),
                    account_id: dotenvy::var("CLOUDFLARE_ACCOUNT_ID").ok(),
                    api_token: dotenvy::var("CLOUDFLARE_API_TOKEN").ok(),
                });

                // Check prerequisites first
                match deployer.check_prerequisites() {
                    Ok(prereqs) if prereqs.is_ready() => {
                        // Deploy with progress output
                        match deployer.deploy(&site_dir, |_phase, msg| {
                            let _ = writeln!(term, "    {} {}", style("").dim(), msg);
                        }) {
                            Ok(result) => {
                                writeln!(term)?;
                                writeln!(
                                    term,
                                    "  {} Deployed to Cloudflare Pages!",
                                    style("").green().bold()
                                )?;
                                writeln!(term)?;
                                writeln!(
                                    term,
                                    "  Your archive is available at: {}",
                                    style(&result.pages_url).cyan().bold()
                                )?;
                                if let Some(ref domain) = result.custom_domain {
                                    writeln!(term, "  Custom domain: {}", style(domain).cyan())?;
                                }
                            }
                            Err(e) => {
                                writeln!(term)?;
                                writeln!(term, "  {} Deployment failed: {}", style("").red(), e)?;
                                writeln!(term)?;
                                writeln!(
                                    term,
                                    "To deploy manually, use wrangler to deploy the {} directory:",
                                    site_dir.display()
                                )?;
                                writeln!(
                                    term,
                                    "  {}",
                                    style(format!(
                                        "wrangler pages deploy {} --project-name {}",
                                        site_dir.display(),
                                        project_name
                                    ))
                                    .dim()
                                )?;
                            }
                        }
                    }
                    Ok(prereqs) => {
                        let missing = prereqs.missing();
                        writeln!(term)?;
                        writeln!(term, "  {} Prerequisites not met:", style("").yellow())?;
                        for item in &missing {
                            writeln!(term, "    {} {}", style("").dim(), item)?;
                        }
                        writeln!(term)?;
                        writeln!(term, "To deploy manually after meeting prerequisites:")?;
                        writeln!(
                            term,
                            "  {}",
                            style(format!(
                                "wrangler pages deploy {} --project-name {}",
                                site_dir.display(),
                                project_name
                            ))
                            .dim()
                        )?;
                    }
                    Err(e) => {
                        writeln!(term)?;
                        writeln!(
                            term,
                            "  {} Could not check prerequisites: {}",
                            style("").yellow(),
                            e
                        )?;
                        writeln!(term)?;
                        writeln!(
                            term,
                            "To deploy manually, use wrangler to deploy the {} directory:",
                            site_dir.display()
                        )?;
                        writeln!(
                            term,
                            "  {}",
                            style(format!(
                                "wrangler pages deploy {} --project-name {}",
                                site_dir.display(),
                                project_name
                            ))
                            .dim()
                        )?;
                    }
                }
            }
        }

        writeln!(term)?;
        Ok(())
    }
}

fn unencrypted_bundle_config(db_size: u64) -> serde_json::Value {
    serde_json::json!({
        "encrypted": false,
        "version": "1.0.0",
        "payload": {
            "path": "payload/data.db",
            "format": "sqlite",
            "size_bytes": db_size
        },
        "warning": "UNENCRYPTED - All content is publicly readable"
    })
}

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

    // =========================
    // DeployTarget Tests
    // =========================

    #[test]
    fn deploy_target_display() {
        assert_eq!(DeployTarget::Local.to_string(), "Local export only");
        assert_eq!(DeployTarget::GitHubPages.to_string(), "GitHub Pages");
        assert_eq!(
            DeployTarget::CloudflarePages.to_string(),
            "Cloudflare Pages"
        );
    }

    #[test]
    fn deploy_target_equality() {
        assert_eq!(DeployTarget::Local, DeployTarget::Local);
        assert_eq!(DeployTarget::GitHubPages, DeployTarget::GitHubPages);
        assert_eq!(DeployTarget::CloudflarePages, DeployTarget::CloudflarePages);
        assert_ne!(DeployTarget::Local, DeployTarget::GitHubPages);
        assert_ne!(DeployTarget::GitHubPages, DeployTarget::CloudflarePages);
    }

    #[test]
    fn deploy_target_clone() {
        let target = DeployTarget::CloudflarePages;
        let cloned = target;
        assert_eq!(target, cloned);
    }

    #[test]
    fn unencrypted_bundle_config_shape() {
        let config = unencrypted_bundle_config(1234);

        assert_eq!(
            config,
            serde_json::json!({
                "encrypted": false,
                "version": "1.0.0",
                "payload": {
                    "path": "payload/data.db",
                    "format": "sqlite",
                    "size_bytes": 1234
                },
                "warning": "UNENCRYPTED - All content is publicly readable"
            })
        );
    }

    // =========================
    // WizardState Tests
    // =========================

    #[test]
    fn wizard_state_default_values() {
        let state = WizardState::default();

        // Content selection defaults
        assert!(state.agents.is_empty());
        assert!(state.time_range.is_none());
        assert!(state.workspaces.is_none());

        // Security defaults
        assert!(state.password.is_none());
        assert!(state.recovery_secret.is_none());
        assert!(state.generate_recovery); // Should default to true
        assert!(!state.generate_qr); // Should default to false

        // Site configuration defaults
        assert_eq!(state.title, "cass Archive");
        assert_eq!(
            state.description,
            "Encrypted archive of AI coding agent conversations"
        );
        assert!(!state.hide_metadata);

        // Deployment defaults
        assert_eq!(state.target, DeployTarget::Local);
        assert_eq!(state.output_dir, PathBuf::from("cass-export"));
        assert!(state.repo_name.is_none());

        // Exclusions default
        assert_eq!(state.exclusions.exclusion_counts(), (0, 0, 0));

        // Summary default
        assert!(state.last_summary.is_none());

        // Secret scan defaults
        assert!(!state.secret_scan_has_findings);
        assert!(!state.secret_scan_has_critical);
        assert_eq!(state.secret_scan_count, 0);

        // Password entropy default
        assert_eq!(state.password_entropy_bits, 0.0);

        // Unencrypted mode defaults
        assert!(!state.no_encryption);
        assert!(!state.unencrypted_confirmed);
    }

    #[test]
    fn wizard_state_db_path_is_set() {
        let state = WizardState::default();
        // db_path should be set to a valid path containing the expected filename
        assert!(state.db_path.to_string_lossy().contains("agent_search.db"));
    }

    #[test]
    fn wizard_state_clone() {
        let state = WizardState {
            title: "Custom Title".to_string(),
            agents: vec!["claude".to_string(), "codex".to_string()],
            no_encryption: true,
            ..Default::default()
        };

        let cloned = state.clone();
        assert_eq!(cloned.title, "Custom Title");
        assert_eq!(
            cloned.agents,
            vec!["claude".to_string(), "codex".to_string()]
        );
        assert!(cloned.no_encryption);
    }

    // =========================
    // PagesWizard Tests
    // =========================

    #[test]
    fn pages_wizard_new_initializes_default_state() {
        let wizard = PagesWizard::new();
        // Access state through the no_encryption_mode field which is false by default
        assert!(!wizard.no_encryption_mode);
    }

    #[test]
    fn pages_wizard_default_impl() {
        let wizard1 = PagesWizard::new();
        let wizard2 = PagesWizard::default();
        // Both should have same default state
        assert_eq!(wizard1.no_encryption_mode, wizard2.no_encryption_mode);
    }

    #[test]
    fn pages_wizard_set_no_encryption() {
        let mut wizard = PagesWizard::new();
        assert!(!wizard.no_encryption_mode);
        assert!(!wizard.state.no_encryption);

        wizard.set_no_encryption(true);
        assert!(wizard.no_encryption_mode);
        assert!(wizard.state.no_encryption);

        wizard.set_no_encryption(false);
        assert!(!wizard.no_encryption_mode);
        assert!(!wizard.state.no_encryption);
    }

    // Test for pages_wizard_set_include_attachments removed: flag removed
    // from WizardState per bead adyyt.

    // =========================
    // Time Range Mapping Tests
    // =========================

    #[test]
    fn time_range_selection_mapping() {
        // Test the time range mapping logic from step_content_selection
        // This is the mapping: 1 => -7d, 2 => -30d, 3 => -90d, 4 => -365d, 0/_ => None

        fn map_time_selection(selection: usize) -> Option<String> {
            match selection {
                1 => Some("-7d".to_string()),
                2 => Some("-30d".to_string()),
                3 => Some("-90d".to_string()),
                4 => Some("-365d".to_string()),
                _ => None,
            }
        }

        assert_eq!(map_time_selection(0), None);
        assert_eq!(map_time_selection(1), Some("-7d".to_string()));
        assert_eq!(map_time_selection(2), Some("-30d".to_string()));
        assert_eq!(map_time_selection(3), Some("-90d".to_string()));
        assert_eq!(map_time_selection(4), Some("-365d".to_string()));
        assert_eq!(map_time_selection(5), None);
    }

    // =========================
    // Deploy Target Selection Mapping Tests
    // =========================

    #[test]
    fn deploy_target_selection_mapping() {
        // Test the target selection mapping from step_deployment_target
        fn map_target_selection(selection: usize) -> DeployTarget {
            match selection {
                1 => DeployTarget::GitHubPages,
                2 => DeployTarget::CloudflarePages,
                _ => DeployTarget::Local,
            }
        }

        assert_eq!(map_target_selection(0), DeployTarget::Local);
        assert_eq!(map_target_selection(1), DeployTarget::GitHubPages);
        assert_eq!(map_target_selection(2), DeployTarget::CloudflarePages);
        assert_eq!(map_target_selection(3), DeployTarget::Local);
    }

    // =========================
    // State Modification Tests
    // =========================

    #[test]
    fn wizard_state_agents_modification() {
        let mut state = WizardState::default();
        assert!(state.agents.is_empty());

        state.agents = vec!["claude".to_string()];
        assert_eq!(state.agents.len(), 1);

        state.agents.push("codex".to_string());
        assert_eq!(state.agents.len(), 2);
        assert_eq!(
            state.agents,
            vec!["claude".to_string(), "codex".to_string()]
        );
    }

    #[test]
    fn wizard_state_workspaces_modification() {
        let mut state = WizardState::default();
        assert!(state.workspaces.is_none());

        state.workspaces = Some(vec![PathBuf::from("/project1")]);
        assert_eq!(state.workspaces.as_ref().unwrap().len(), 1);

        state
            .workspaces
            .as_mut()
            .unwrap()
            .push(PathBuf::from("/project2"));
        assert_eq!(state.workspaces.as_ref().unwrap().len(), 2);
    }

    #[test]
    fn wizard_state_security_configuration() {
        let state = WizardState {
            password: Some("test_password".to_string()),
            recovery_secret: Some(vec![1, 2, 3, 4]),
            generate_recovery: false,
            generate_qr: true,
            ..Default::default()
        };

        assert_eq!(state.password, Some("test_password".to_string()));
        assert_eq!(state.recovery_secret, Some(vec![1, 2, 3, 4]));
        assert!(!state.generate_recovery);
        assert!(state.generate_qr);
    }

    #[test]
    fn wizard_state_debug_redacts_sensitive_fields() {
        let state = WizardState {
            password: Some("test_password".to_string()),
            recovery_secret: Some(vec![1, 2, 3, 4]),
            cloudflare_api_token: Some("cf-secret-token".to_string()),
            ..Default::default()
        };

        let debug = format!("{state:?}");
        assert!(debug.contains("password"));
        assert!(debug.contains("recovery_secret"));
        assert!(debug.contains("cloudflare_api_token"));
        assert!(debug.contains("[REDACTED]"));
        assert!(!debug.contains("test_password"));
        assert!(!debug.contains("cf-secret-token"));
        assert!(!debug.contains("[1, 2, 3, 4]"));
    }

    #[test]
    fn sample_title_truncation_is_utf8_boundary_safe() {
        let ascii = "abcdefghijklmnopqrstuvwxyz0123456789";
        assert_eq!(
            truncate_sample_title(ascii),
            "abcdefghijklmnopqrstuvwxyz0..."
        );

        let unicode = format!("{}{}", "日本語".repeat(12), "suffix");
        let truncated = truncate_sample_title(&unicode);
        assert!(truncated.ends_with("..."));
        assert!(truncated.is_char_boundary(truncated.len()));
        assert!(truncated.len() <= 30);
    }

    #[test]
    fn wizard_state_password_entropy() {
        let mut state = WizardState::default();
        assert_eq!(state.password_entropy_bits, 0.0);

        state.password_entropy_bits = 64.5;
        assert!((state.password_entropy_bits - 64.5).abs() < f64::EPSILON);
    }

    #[test]
    fn wizard_state_secret_scan_results() {
        let state = WizardState {
            secret_scan_has_findings: true,
            secret_scan_has_critical: true,
            secret_scan_count: 5,
            ..Default::default()
        };

        assert!(state.secret_scan_has_findings);
        assert!(state.secret_scan_has_critical);
        assert_eq!(state.secret_scan_count, 5);
    }

    #[test]
    fn wizard_state_output_configuration() {
        let state = WizardState {
            output_dir: PathBuf::from("/custom/output"),
            repo_name: Some("my-archive".to_string()),
            ..Default::default()
        };

        assert_eq!(state.output_dir, PathBuf::from("/custom/output"));
        assert_eq!(state.repo_name, Some("my-archive".to_string()));
    }

    // =========================
    // Edge Cases
    // =========================

    #[test]
    fn wizard_state_with_unicode_values() {
        let state = WizardState {
            title: "日本語タイトル".to_string(),
            description: "説明文 with émojis 🎉".to_string(),
            agents: vec!["クローード".to_string()],
            ..Default::default()
        };

        assert_eq!(state.title, "日本語タイトル");
        assert_eq!(state.description, "説明文 with émojis 🎉");
        assert_eq!(state.agents[0], "クローード");
    }

    #[test]
    fn wizard_state_empty_strings() {
        let state = WizardState {
            title: "".to_string(),
            description: "".to_string(),
            ..Default::default()
        };

        assert!(state.title.is_empty());
        assert!(state.description.is_empty());
    }
}