warcraft-rs 0.7.0

Unified CLI for World of Warcraft file format parsing, conversion, and validation
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
//! MPQ archive command implementations

use anyhow::{Context, Result};
use clap::{Subcommand, ValueEnum};
use std::fs;
use std::path::Path;
use wow_mpq::{
    Archive, ArchiveBuilder, FormatVersion, PatchChain, RebuildOptions,
    compare_archives as mpq_compare_archives,
    debug::{
        HexDumpConfig, dump_block_entry, dump_hash_entry, format_bet_table, format_block_table,
        format_hash_table, format_het_table, hex_dump,
    },
    path::mpq_path_to_system,
    rebuild_archive,
    single_archive_parallel::{ParallelArchive, ParallelConfig},
};

use crate::utils::{
    NodeType, TreeNode, TreeOptions, add_table_row, create_progress_bar, create_spinner,
    create_table, detect_ref_type, format_bytes, format_compression_ratio, matches_pattern,
    render_tree, truncate_path,
};

#[derive(ValueEnum, Clone, Debug)]
pub enum VersionArg {
    V1,
    V2,
    V3,
    V4,
}

impl From<VersionArg> for FormatVersion {
    fn from(arg: VersionArg) -> Self {
        match arg {
            VersionArg::V1 => FormatVersion::V1,
            VersionArg::V2 => FormatVersion::V2,
            VersionArg::V3 => FormatVersion::V3,
            VersionArg::V4 => FormatVersion::V4,
        }
    }
}

#[derive(Subcommand)]
pub enum MpqCommands {
    /// Show information about an MPQ archive or specific file
    Info {
        /// Path to the MPQ archive
        archive: String,

        /// Optional file to show detailed information for
        file: Option<String>,

        /// Show hash table details
        #[arg(long)]
        show_hash_table: bool,

        /// Show block table details
        #[arg(long)]
        show_block_table: bool,
    },

    /// Validate integrity of an MPQ archive
    Validate {
        /// Path to the MPQ archive
        archive: String,

        /// Check CRC/MD5 checksums if available
        #[arg(long)]
        check_checksums: bool,

        /// Number of threads for parallel validation (default: CPU cores)
        #[arg(long)]
        threads: Option<usize>,
    },

    /// List files in an MPQ archive
    List {
        /// Path to the MPQ archive
        archive: String,

        /// Show detailed information (size, compression ratio)
        #[arg(short, long)]
        long: bool,

        /// Filter files by pattern (supports wildcards)
        #[arg(short, long)]
        filter: Option<String>,

        /// Use hash database for name resolution
        #[arg(long)]
        use_db: bool,

        /// Automatically record found filenames to database
        #[arg(long)]
        record_to_db: bool,

        /// Show only files with patch flag (Cataclysm+ PTCH files)
        #[arg(long)]
        show_patches: bool,
    },

    /// Extract files from an MPQ archive
    Extract {
        /// Path to the MPQ archive
        archive: String,

        /// Output directory
        #[arg(short, long, default_value = ".")]
        output: String,

        /// Specific files to extract (extracts all if not specified)
        files: Vec<String>,

        /// File types to extract (e.g. ".txt", "jpg"). Case-insensitive. Ignored if \[FILES\] are specified.
        #[arg(short, long)]
        file_type: Option<String>,

        /// Preserve directory structure
        #[arg(short, long)]
        preserve_paths: bool,

        /// Number of threads for parallel extraction (default: CPU cores)
        #[arg(long)]
        threads: Option<usize>,

        /// Continue extraction even if some files fail
        #[arg(long)]
        skip_errors: bool,

        /// Patch archives to apply (in order of priority)
        #[arg(long = "patch", action = clap::ArgAction::Append)]
        patches: Vec<String>,
    },

    /// Create a new MPQ archive
    Create {
        /// Path for the new MPQ archive
        archive: String,

        /// Files to add to the archive
        #[arg(short, long, required = true)]
        add: Vec<String>,

        /// Archive format version (v1, v2, v3, v4)
        #[arg(long, default_value = "v2")]
        version: String,

        /// Compression method (none, zlib, bzip2, lzma)
        #[arg(short, long, default_value = "zlib")]
        compression: String,

        /// Create or update (listfile)
        #[arg(long)]
        with_listfile: bool,
    },

    /// Rebuild an MPQ archive 1:1
    Rebuild {
        /// Source MPQ archive
        source: String,

        /// Target path for rebuilt archive
        target: String,

        /// Preserve original MPQ format version
        #[arg(long, default_value_t = true)]
        preserve_format: bool,

        /// Upgrade to specific format version
        #[arg(long, value_enum)]
        upgrade_to: Option<VersionArg>,

        /// Skip encrypted files
        #[arg(long)]
        skip_encrypted: bool,

        /// Skip digital signatures
        #[arg(long, default_value_t = true)]
        skip_signatures: bool,

        /// Verify rebuilt archive matches original
        #[arg(long)]
        verify: bool,

        /// Override compression method
        #[arg(long)]
        compression: Option<String>,

        /// Override block size
        #[arg(long)]
        block_size: Option<u16>,

        /// List files that would be processed (dry run)
        #[arg(long)]
        list_only: bool,
    },

    /// Compare two MPQ archives
    Compare {
        /// Source MPQ archive
        source: String,

        /// Target MPQ archive to compare against
        target: String,

        /// Show detailed file-by-file comparison
        #[arg(short, long)]
        detailed: bool,

        /// Compare actual file contents (slower but thorough)
        #[arg(long)]
        content_check: bool,

        /// Only compare archive metadata
        #[arg(long)]
        metadata_only: bool,

        /// Ignore file order differences
        #[arg(long)]
        ignore_order: bool,

        /// Output format: table, json, summary
        #[arg(long, default_value = "table")]
        output: String,

        /// Filter files by pattern (supports wildcards)
        #[arg(short, long)]
        filter: Option<String>,
    },

    /// Show tree structure of an MPQ archive
    Tree {
        /// Path to the MPQ archive
        archive: String,

        /// Maximum depth to display
        #[arg(long)]
        depth: Option<usize>,

        /// Hide external file references
        #[arg(long)]
        no_external_refs: bool,

        /// Disable colored output
        #[arg(long)]
        no_color: bool,

        /// Show compact metadata inline
        #[arg(long)]
        compact: bool,

        /// Filter files by pattern (supports wildcards)
        #[arg(short, long)]
        filter: Option<String>,
    },

    /// Debug MPQ archive internals
    Debug {
        /// Path to the MPQ archive
        archive: String,

        /// Show hash table entries
        #[arg(long)]
        hash_table: bool,

        /// Show block table entries
        #[arg(long)]
        block_table: bool,

        /// Show HET table (if present)
        #[arg(long)]
        het_table: bool,

        /// Show BET table (if present)
        #[arg(long)]
        bet_table: bool,

        /// Show specific entry by index
        #[arg(long)]
        entry: Option<usize>,

        /// Find and show entries for a specific file
        #[arg(long)]
        find: Option<String>,

        /// Show raw hex dump of table data
        #[arg(long)]
        raw: bool,

        /// Show all tables
        #[arg(long)]
        all: bool,
    },

    /// Visualize patch chain information
    PatchChain {
        /// Base MPQ archive
        base: String,

        /// Patch archives to include (in priority order)
        #[arg(long = "patch", action = clap::ArgAction::Append)]
        patches: Vec<String>,

        /// Show detailed file-level information
        #[arg(short, long)]
        detailed: bool,
    },

    /// Database operations for MPQ hash resolution
    #[command(subcommand)]
    Db(DbCommands),
}

#[derive(Subcommand)]
pub enum DbCommands {
    /// Initialize or show status of the hash database
    Status {
        /// Show detailed statistics
        #[arg(long)]
        detailed: bool,
    },

    /// Import filenames from various sources
    Import {
        /// Path to import from (listfile, MPQ archive, or directory)
        path: String,

        /// Source type
        #[arg(value_enum)]
        source_type: ImportSourceArg,

        /// Show progress
        #[arg(long)]
        show_progress: bool,
    },

    /// Analyze an MPQ archive and record its filenames
    Analyze {
        /// Path to the MPQ archive
        archive: String,

        /// Also record anonymous files with generated names
        #[arg(long)]
        include_anonymous: bool,
    },

    /// Look up a filename's hash values
    Lookup {
        /// Filename to look up
        filename: String,
    },

    /// Export database to listfile format
    Export {
        /// Output file path
        output: String,

        /// Filter by source
        #[arg(long)]
        source: Option<String>,
    },

    /// List entries in the database
    List {
        /// Filter entries by pattern (supports wildcards)
        #[arg(short, long)]
        filter: Option<String>,

        /// Show detailed information
        #[arg(short, long)]
        long: bool,

        /// Limit number of results
        #[arg(short = 'n', long, default_value = "100")]
        limit: usize,
    },
}

#[derive(ValueEnum, Clone, Debug)]
pub enum ImportSourceArg {
    /// Import from a listfile
    Listfile,
    /// Import from an MPQ archive's internal listfile
    Archive,
    /// Scan a directory for WoW file patterns
    Directory,
}

pub async fn execute(command: MpqCommands) -> Result<()> {
    match command {
        MpqCommands::List {
            archive,
            long,
            filter,
            use_db,
            record_to_db,
            show_patches,
        } => list_archive(&archive, long, filter, use_db, record_to_db, show_patches).await,
        MpqCommands::Extract {
            archive,
            output,
            files,
            file_type,
            preserve_paths,
            threads,
            skip_errors,
            patches,
        } => extract_files(
            &archive,
            &output,
            files,
            file_type,
            preserve_paths,
            threads,
            skip_errors,
            patches,
        ),
        MpqCommands::Create {
            archive,
            add,
            version,
            compression,
            with_listfile,
        } => create_archive(&archive, add, &version, &compression, with_listfile),
        MpqCommands::Info {
            archive,
            file,
            show_hash_table,
            show_block_table,
        } => show_info(&archive, file.as_deref(), show_hash_table, show_block_table),
        MpqCommands::Validate {
            archive,
            check_checksums,
            threads,
        } => validate_archive(&archive, check_checksums, threads),
        MpqCommands::Rebuild {
            source,
            target,
            preserve_format,
            upgrade_to,
            skip_encrypted,
            skip_signatures,
            verify,
            compression,
            block_size,
            list_only,
        } => rebuild_mpq_archive(RebuildParams {
            source_path: &source,
            target_path: &target,
            preserve_format,
            upgrade_to,
            skip_encrypted,
            skip_signatures,
            verify,
            compression,
            block_size,
            list_only,
        }),
        MpqCommands::Compare {
            source,
            target,
            detailed,
            content_check,
            metadata_only,
            ignore_order,
            output,
            filter,
        } => compare_archives(CompareParams {
            source_path: &source,
            target_path: &target,
            detailed,
            content_check,
            metadata_only,
            ignore_order,
            output_format: &output,
            filter,
        }),
        MpqCommands::Tree {
            archive,
            depth,
            no_external_refs,
            no_color,
            compact,
            filter,
        } => show_tree(
            &archive,
            depth,
            !no_external_refs,
            no_color,
            compact,
            filter,
        ),
        MpqCommands::Debug {
            archive,
            hash_table,
            block_table,
            het_table,
            bet_table,
            entry,
            find,
            raw,
            all,
        } => debug_archive(DebugParams {
            archive_path: &archive,
            show_hash_table: hash_table || all,
            show_block_table: block_table || all,
            show_het_table: het_table || all,
            show_bet_table: bet_table || all,
            entry_index: entry,
            find_file: find,
            raw_dump: raw,
        }),
        MpqCommands::PatchChain {
            base,
            patches,
            detailed,
        } => visualize_patch_chain(&base, patches, detailed),
        MpqCommands::Db(db_command) => execute_db_command(db_command).await,
    }
}

async fn list_archive(
    path: &str,
    long: bool,
    filter: Option<String>,
    use_db: bool,
    record_to_db: bool,
    show_patches: bool,
) -> Result<()> {
    use crate::database::Database;

    let spinner = create_spinner("Opening archive...");
    let mut archive = Archive::open(path).context("Failed to open archive")?;
    spinner.finish_and_clear();

    // Open database if needed
    let db = if use_db || record_to_db {
        Some(
            Database::open_default()
                .await
                .context("Failed to open database")?,
        )
    } else {
        None
    };

    // Record filenames to database if requested
    if record_to_db && let Some(ref db) = db {
        let count = record_listfile_to_db(&mut archive, db).await?;
        if count > 0 {
            println!("Recorded {count} filenames to database");
        }
    }

    // Get file list
    let entries = if use_db {
        if let Some(ref db) = db {
            list_with_db(&mut archive, db).await?
        } else {
            archive.list()?
        }
    } else {
        archive.list()?
    };

    // Filter for patch files if requested
    let files: Vec<String> = if show_patches {
        entries
            .into_iter()
            .filter(|e| e.is_patch_file())
            .map(|e| e.name)
            .collect()
    } else {
        entries.into_iter().map(|e| e.name).collect()
    };

    let pattern = filter.as_deref().unwrap_or("*");

    let mut filtered_files: Vec<_> = files
        .iter()
        .filter(|f| matches_pattern(f, pattern))
        .collect();
    filtered_files.sort();

    if filtered_files.is_empty() {
        println!("No files found matching pattern: {pattern}");
        return Ok(());
    }

    if long {
        let mut table = create_table(vec!["File", "Size", "Compressed", "Ratio"]);

        for file in filtered_files {
            // Try to get file info from the entries
            if let Ok(entries) = archive.list()
                && let Some(entry) = entries.iter().find(|e| &e.name == file)
            {
                add_table_row(
                    &mut table,
                    vec![
                        truncate_path(file, 50),
                        format_bytes(entry.size),
                        format_bytes(entry.compressed_size),
                        format_compression_ratio(entry.size, entry.compressed_size),
                    ],
                );
            }
        }

        table.printstd();
    } else {
        for file in filtered_files {
            println!("{file}");
        }
    }

    Ok(())
}

/// List files in an archive with database lookup for names
async fn list_with_db(
    archive: &mut Archive,
    db: &crate::database::Database,
) -> Result<Vec<wow_mpq::FileEntry>> {
    use crate::database::HashLookup;

    let mut entries = archive.list_all_with_hashes()?;

    for entry in &mut entries {
        if let Some((hash_a, hash_b)) = entry.hashes
            && let Ok(Some(filename)) = db.lookup_filename(hash_a, hash_b).await
        {
            entry.name = filename;
        }
    }

    Ok(entries)
}

/// Record all filenames from an archive's listfile to the database
async fn record_listfile_to_db(
    archive: &mut Archive,
    db: &crate::database::Database,
) -> Result<usize> {
    use crate::database::HashLookup;

    if archive.find_file("(listfile)")?.is_some()
        && let Ok(listfile_data) = archive.read_file("(listfile)")
        && let Ok(filenames) = wow_mpq::special_files::parse_listfile(&listfile_data)
    {
        let source = format!("archive:{}", archive.path().display());
        let filenames_with_source: Vec<(&str, Option<&str>)> = filenames
            .iter()
            .map(|f| (f.as_str(), Some(source.as_str())))
            .collect();

        match db.store_filenames(&filenames_with_source).await {
            Ok((new_count, updated_count)) => {
                log::info!("Recorded {new_count} new and {updated_count} updated filenames");
                return Ok(new_count + updated_count);
            }
            Err(e) => {
                log::error!("Failed to store filenames in database: {e}");
                anyhow::bail!("Database error: {e}");
            }
        }
    }

    Ok(0)
}

struct ExtractOptions {
    archive_path: String,
    output_dir: String,
    files: Vec<String>,
    file_type: Option<String>,
    preserve_paths: bool,
    threads: Option<usize>,
    skip_errors: bool,
    patches: Vec<String>,
}

#[allow(clippy::too_many_arguments)]
fn extract_files(
    archive_path: &str,
    output_dir: &str,
    files: Vec<String>,
    file_type: Option<String>,
    preserve_paths: bool,
    threads: Option<usize>,
    skip_errors: bool,
    patches: Vec<String>,
) -> Result<()> {
    let options = ExtractOptions {
        archive_path: archive_path.to_string(),
        output_dir: output_dir.to_string(),
        files,
        file_type,
        preserve_paths,
        threads,
        skip_errors,
        patches,
    };

    extract_files_with_options(options)
}

fn extract_files_with_options(options: ExtractOptions) -> Result<()> {
    let ExtractOptions {
        archive_path,
        output_dir,
        files,
        file_type,
        preserve_paths,
        threads,
        skip_errors,
        patches,
    } = options;
    if patches.is_empty() {
        // Use parallel extraction by default
        let files_to_extract: Vec<String> = if files.is_empty() {
            // For bulk extraction, read listfile directly to avoid slow database lookups
            println!("Reading file list from archive...");
            let mut archive = Archive::open(&archive_path).context("Failed to open archive")?;

            // Try to read (listfile) directly for faster bulk operations
            let mut file_list = match archive.read_file("(listfile)") {
                Ok(listfile_data) => {
                    println!("Parsing listfile...");
                    match wow_mpq::special_files::parse_listfile(&listfile_data) {
                        Ok(filenames) => {
                            println!("Found {} files in listfile", filenames.len());
                            filenames
                        }
                        Err(_) => {
                            println!(
                                "Failed to parse listfile, falling back to slow enumeration..."
                            );
                            let file_list = archive
                                .list()?
                                .into_iter()
                                .map(|e| e.name)
                                .collect::<Vec<String>>();
                            println!("Found {} files", file_list.len());
                            file_list
                        }
                    }
                }
                Err(_) => {
                    println!("No listfile found, using slow enumeration...");
                    let file_list = archive
                        .list()?
                        .into_iter()
                        .map(|e| e.name)
                        .collect::<Vec<String>>();
                    println!("Found {} files", file_list.len());
                    file_list
                }
            };

            // Filter by file type if specified
            if let Some(file_type) = file_type {
                println!("Filtering by file type...");
                file_list.retain(|f| {
                    // Ignore case
                    let lowercase_filename = f.to_lowercase();
                    let lowercase_file_type = file_type.to_lowercase();
                    lowercase_filename.ends_with(&lowercase_file_type)
                });
                println!(
                    "Found {} files matching type {}",
                    file_list.len(),
                    file_type
                );
            }

            file_list
        } else {
            files
        };

        let pb = create_progress_bar(files_to_extract.len() as u64, "Extracting files");

        // Configure parallel extraction with sensible defaults for large extractions
        let default_threads = std::thread::available_parallelism()
            .map(|n| n.get())
            .unwrap_or(4);
        let batch_size = if files_to_extract.len() > 5000 {
            // For very large extractions, use bigger batches to reduce overhead
            std::cmp::max(
                50,
                files_to_extract.len() / (threads.unwrap_or(default_threads) * 4),
            )
        } else if files_to_extract.len() > 1000 {
            // For moderately large extractions, use medium batches
            25
        } else {
            // For small extractions, use small batches
            10
        };

        let mut config = ParallelConfig::new()
            .batch_size(batch_size)
            .skip_errors(skip_errors);

        if let Some(num_threads) = threads {
            config = config.threads(num_threads);
        }

        // Extract files in parallel using the direct API (avoids slow ParallelArchive::open)
        let file_refs: Vec<&str> = files_to_extract.iter().map(|s| s.as_str()).collect();
        use wow_mpq::single_archive_parallel::extract_with_config;
        let results = extract_with_config(archive_path, &file_refs, config)?;

        // Write extracted files to disk
        let mut success_count = 0;
        let mut error_count = 0;

        for (file, data_result) in results {
            pb.set_message(format!("Writing: {file}"));

            match data_result {
                Ok(data) => {
                    let output_path = if preserve_paths {
                        let system_path = mpq_path_to_system(&file);
                        Path::new(&output_dir).join(system_path)
                    } else {
                        let system_path = mpq_path_to_system(&file);
                        let filename = Path::new(&system_path).file_name().unwrap_or_default();
                        Path::new(&output_dir).join(filename)
                    };

                    if let Some(parent) = output_path.parent() {
                        fs::create_dir_all(parent)?;
                    }

                    fs::write(&output_path, data)?;
                    success_count += 1;
                }
                Err(e) => {
                    log::warn!("Failed to extract {file}: {e}");
                    error_count += 1;
                }
            }

            pb.inc(1);
        }

        let msg = if error_count > 0 {
            format!("Extraction complete: {success_count} succeeded, {error_count} failed")
        } else {
            format!("Extraction complete: {success_count} files")
        };
        pb.finish_with_message(msg);

        // Return error if skip_errors is false and some files failed
        if !skip_errors && error_count > 0 {
            anyhow::bail!(
                "Failed to extract {error_count} file(s). Use --skip-errors to ignore extraction failures."
            );
        }
    } else {
        // Use patch chain logic
        let spinner = create_spinner("Building patch chain...");
        let mut chain = PatchChain::new();

        // Add base archive with priority 0
        chain
            .add_archive(archive_path, 0)
            .context("Failed to add base archive to patch chain")?;

        // Add patch archives with increasing priority
        for (index, patch_path) in patches.iter().enumerate() {
            let priority = (index + 1) * 100;
            chain
                .add_archive(patch_path, priority as i32)
                .with_context(|| format!("Failed to add patch archive: {patch_path}"))?;
        }

        spinner.finish_and_clear();

        println!("Patch chain built with {} archives", chain.archive_count());

        let files_to_extract = if files.is_empty() {
            // Get all files from the chain
            let entries = chain.list()?;
            entries.into_iter().map(|e| e.name).collect()
        } else {
            files
        };

        let pb = create_progress_bar(files_to_extract.len() as u64, "Extracting files");

        let mut success_count = 0;
        let mut error_count = 0;

        for file in files_to_extract.iter() {
            pb.set_message(format!("Extracting: {file}"));

            match chain.read_file(file) {
                Ok(data) => {
                    let output_path = if preserve_paths {
                        // Convert MPQ path separators to system path separators
                        let system_path = mpq_path_to_system(file);
                        Path::new(&output_dir).join(system_path)
                    } else {
                        // Convert MPQ path to system path, then extract just the filename
                        let system_path = mpq_path_to_system(file);
                        let filename = Path::new(&system_path).file_name().unwrap_or_default();
                        Path::new(&output_dir).join(filename)
                    };

                    if let Some(parent) = output_path.parent() {
                        fs::create_dir_all(parent)?;
                    }

                    fs::write(&output_path, data)?;
                    success_count += 1;

                    // Show which archive the file came from
                    if let Some(source) = chain.find_file_archive(file) {
                        log::debug!("Extracted {} from {}", file, source.display());
                    }
                }
                Err(e) => {
                    log::warn!("Failed to extract {file}: {e}");
                    error_count += 1;
                }
            }

            pb.inc(1);
        }

        let msg = if error_count > 0 {
            format!("Extraction complete: {success_count} succeeded, {error_count} failed")
        } else {
            format!("Extraction complete: {success_count} files")
        };
        pb.finish_with_message(msg);

        // Show patch chain info
        println!("\nPatch chain info:");
        for info in chain.get_chain_info() {
            println!(
                "  {} (priority {}, {} files)",
                info.path.display(),
                info.priority,
                info.file_count
            );
        }

        // Return error if skip_errors is false and some files failed
        if !skip_errors && error_count > 0 {
            anyhow::bail!(
                "Failed to extract {error_count} file(s) from patch chain. Use --skip-errors to ignore extraction failures."
            );
        }
    }

    Ok(())
}

fn create_archive(
    path: &str,
    files: Vec<String>,
    version: &str,
    compression: &str,
    with_listfile: bool,
) -> Result<()> {
    let mut builder = ArchiveBuilder::new();

    // Parse version
    let format_version = match version {
        "v1" => FormatVersion::V1,
        "v2" => FormatVersion::V2,
        "v3" => FormatVersion::V3,
        "v4" => FormatVersion::V4,
        _ => anyhow::bail!("Invalid version: {}", version),
    };
    builder = builder.version(format_version);

    // Parse compression
    let compression_flags = match compression {
        "none" => 0,
        "zlib" => wow_mpq::compression::flags::ZLIB,
        "bzip2" => wow_mpq::compression::flags::BZIP2,
        "lzma" => wow_mpq::compression::flags::LZMA,
        _ => anyhow::bail!("Invalid compression: {}", compression),
    };
    builder = builder.default_compression(compression_flags);

    if with_listfile {
        builder = builder.listfile_option(wow_mpq::ListfileOption::Generate);
    }

    let pb = create_progress_bar(files.len() as u64, "Adding files");

    for file_path in files {
        pb.set_message(format!("Adding: {file_path}"));
        let data = fs::read(&file_path)?;
        let archive_path = Path::new(&file_path)
            .file_name()
            .and_then(|n| n.to_str())
            .unwrap_or(&file_path);
        builder = builder.add_file_data(data, archive_path);
        pb.inc(1);
    }

    pb.finish_and_clear();

    let spinner = create_spinner("Building archive...");
    builder.build(path)?;
    spinner.finish_with_message("Archive created successfully");

    Ok(())
}

fn show_info(
    path: &str,
    file: Option<&str>,
    include_hash_table: bool,
    include_block_table: bool,
) -> Result<()> {
    let spinner = create_spinner("Opening archive...");
    let mut archive = Archive::open(path).context("Failed to open archive")?;
    spinner.finish_and_clear();

    // If a specific file is requested, show file-specific information
    if let Some(filename) = file {
        show_file_info(&mut archive, filename)?;
        return Ok(());
    }

    // Otherwise show archive-level information
    let info = archive.get_info()?;

    println!("MPQ Archive Information");
    println!("======================");
    println!("Path: {path}");
    println!("Format version: {:?}", info.format_version);
    println!("Archive size: {}", format_bytes(info.file_size));
    println!("Number of files: {}", info.file_count);

    if include_hash_table {
        println!();
        show_hash_table(&mut archive, false)?;
    }

    if include_block_table {
        println!();
        show_block_table(&mut archive, false)?;
    }

    Ok(())
}

fn show_file_info(archive: &mut Archive, filename: &str) -> Result<()> {
    // Flag constants from BlockEntry
    const FLAG_IMPLODE: u32 = 0x00000100;
    const FLAG_COMPRESS: u32 = 0x00000200;
    const FLAG_ENCRYPTED: u32 = 0x00010000;
    const FLAG_FIX_KEY: u32 = 0x00020000;
    const FLAG_PATCH_FILE: u32 = 0x00100000;
    const FLAG_SINGLE_UNIT: u32 = 0x01000000;
    const FLAG_DELETE_MARKER: u32 = 0x02000000;
    const FLAG_SECTOR_CRC: u32 = 0x04000000;
    const FLAG_EXISTS: u32 = 0x80000000;

    let file_info = archive
        .find_file(filename)?
        .ok_or_else(|| anyhow::anyhow!("File not found: {filename}"))?;

    println!("File Information");
    println!("================");
    println!("Filename: {filename}");
    println!("File size: {}", format_bytes(file_info.file_size));
    println!(
        "Compressed size: {}",
        format_bytes(file_info.compressed_size)
    );
    println!(
        "Compression ratio: {}",
        format_compression_ratio(file_info.file_size, file_info.compressed_size)
    );
    println!("File position: 0x{:X}", file_info.file_pos);
    println!("Flags: 0x{:08X}", file_info.flags);

    // Decode flags
    println!("\nFlag Details:");
    if file_info.flags & FLAG_IMPLODE != 0 {
        println!("  - Compressed (PKWARE DCL)");
    }
    if file_info.flags & FLAG_COMPRESS != 0 {
        println!("  - Compressed");
    }
    if file_info.flags & FLAG_ENCRYPTED != 0 {
        println!("  - Encrypted");
    }
    if file_info.flags & FLAG_FIX_KEY != 0 {
        println!("  - Fix Key");
    }
    if file_info.flags & FLAG_PATCH_FILE != 0 {
        println!("  - ⚠️  PATCH FILE (binary patch, cannot be extracted directly)");
    }
    if file_info.flags & FLAG_SINGLE_UNIT != 0 {
        println!("  - Single Unit");
    }
    if file_info.flags & FLAG_DELETE_MARKER != 0 {
        println!("  - Delete Marker");
    }
    if file_info.flags & FLAG_SECTOR_CRC != 0 {
        println!("  - Sector CRC");
    }
    if file_info.flags & FLAG_EXISTS != 0 {
        println!("  - Exists");
    }

    Ok(())
}

fn validate_archive(path: &str, check_checksums: bool, threads: Option<usize>) -> Result<()> {
    // Use parallel validation by default
    let spinner = create_spinner("Opening archive...");
    let parallel_archive = ParallelArchive::open(path).context("Failed to open archive")?;
    spinner.finish_and_clear();

    let files: Vec<&str> = parallel_archive
        .list_files()
        .iter()
        .map(|s| s.as_str())
        .collect();
    let pb = create_progress_bar(files.len() as u64, "Validating files");

    // Configure parallel processing
    let mut config = ParallelConfig::new().skip_errors(true);
    if let Some(num_threads) = threads {
        config = config.threads(num_threads);
    }

    // Validate files by trying to read them
    use wow_mpq::single_archive_parallel::extract_with_config;
    let validation_results = extract_with_config(path, &files, config)?;

    let mut errors = 0;
    let mut total_size = 0u64;

    for (filename, result) in validation_results {
        pb.set_message(format!("Validating: {filename}"));
        match result {
            Ok(data) => {
                total_size += data.len() as u64;
                if check_checksums {
                    // TODO: Implement checksum validation
                }
            }
            Err(e) => {
                log::error!("Failed to read {filename}: {e}");
                errors += 1;
            }
        }
        pb.inc(1);
    }

    pb.finish_and_clear();

    if errors == 0 {
        println!(
            "✓ Archive validation passed - {} files ({} total)",
            files.len(),
            format_bytes(total_size)
        );
    } else {
        println!("✗ Archive validation failed with {errors} errors");
        println!(
            "  Successfully validated: {} files ({})",
            files.len() - errors,
            format_bytes(total_size)
        );
    }

    Ok(())
}

/// Parameters for MPQ archive rebuild operation
struct RebuildParams<'a> {
    source_path: &'a str,
    target_path: &'a str,
    preserve_format: bool,
    upgrade_to: Option<VersionArg>,
    skip_encrypted: bool,
    skip_signatures: bool,
    verify: bool,
    compression: Option<String>,
    block_size: Option<u16>,
    list_only: bool,
}

fn rebuild_mpq_archive(params: RebuildParams<'_>) -> Result<()> {
    // Parse compression override if provided
    let override_compression = if let Some(comp) = params.compression {
        let compression_flags = match comp.as_str() {
            "none" => 0,
            "zlib" => wow_mpq::compression::flags::ZLIB,
            "bzip2" => wow_mpq::compression::flags::BZIP2,
            "lzma" => wow_mpq::compression::flags::LZMA,
            _ => anyhow::bail!("Invalid compression: {}", comp),
        };
        Some(compression_flags)
    } else {
        None
    };

    // Set up rebuild options
    let options = RebuildOptions {
        preserve_format: params.preserve_format,
        target_format: params.upgrade_to.map(|v| v.into()),
        preserve_order: true,
        skip_encrypted: params.skip_encrypted,
        skip_signatures: params.skip_signatures,
        verify: params.verify,
        override_compression,
        override_block_size: params.block_size,
        list_only: params.list_only,
    };

    if params.list_only {
        println!("Analyzing source archive: {}", params.source_path);
    } else {
        println!(
            "Rebuilding archive: {} -> {}",
            params.source_path, params.target_path
        );
    }

    // Set up progress callback
    let progress_callback = Some(Box::new(|current: usize, total: usize, file: &str| {
        if current.is_multiple_of(100) || current == total {
            println!("  [{current}/{total}] Processing: {file}");
        }
    }) as Box<dyn Fn(usize, usize, &str) + Send + Sync>);

    // Perform the rebuild
    let spinner = if params.list_only {
        create_spinner("Analyzing archive...")
    } else {
        create_spinner("Rebuilding archive...")
    };

    let summary = rebuild_archive(
        params.source_path,
        params.target_path,
        options,
        progress_callback,
    )
    .context("Failed to rebuild archive")?;

    spinner.finish_and_clear();

    // Display results
    println!("\nRebuild Summary:");
    println!("================");
    println!("Source files: {}", summary.source_files);
    println!("Extracted files: {}", summary.extracted_files);
    if summary.skipped_files > 0 {
        println!("Skipped files: {}", summary.skipped_files);
    }
    println!("Target format: {:?}", summary.target_format);

    if params.list_only {
        println!("\nDry run completed. Use without --list-only to perform actual rebuild.");
    } else {
        if summary.verified {
            println!("✓ Verification: PASSED");
        } else if params.verify {
            println!("⚠ Verification: SKIPPED");
        }
        println!("✓ Archive rebuilt successfully: {}", params.target_path);
    }

    Ok(())
}

/// Parameters for MPQ archive comparison operation
struct CompareParams<'a> {
    source_path: &'a str,
    target_path: &'a str,
    detailed: bool,
    content_check: bool,
    metadata_only: bool,
    ignore_order: bool,
    output_format: &'a str,
    filter: Option<String>,
}

/// Parameters for MPQ archive debug operation
struct DebugParams<'a> {
    archive_path: &'a str,
    show_hash_table: bool,
    show_block_table: bool,
    show_het_table: bool,
    show_bet_table: bool,
    entry_index: Option<usize>,
    find_file: Option<String>,
    raw_dump: bool,
}

fn compare_archives(params: CompareParams<'_>) -> Result<()> {
    let spinner = create_spinner("Comparing archives...");

    let comparison_result = mpq_compare_archives(
        params.source_path,
        params.target_path,
        params.detailed,
        params.content_check,
        params.metadata_only,
        params.ignore_order,
        params.filter,
    )?;

    spinner.finish_and_clear();

    // Display results based on output format
    match params.output_format {
        "json" => {
            display_json_output(&comparison_result)?;
        }
        "summary" => {
            display_summary_output(params.source_path, params.target_path, &comparison_result)?;
        }
        "table" => {
            display_table_output(params.source_path, params.target_path, &comparison_result)?;
        }
        _ => {
            display_table_output(params.source_path, params.target_path, &comparison_result)?;
        }
    }

    Ok(())
}

fn display_summary_output(
    source_path: &str,
    target_path: &str,
    result: &wow_mpq::ComparisonResult,
) -> Result<()> {
    println!("Archive Comparison Summary");
    println!("=========================");
    println!("Source: {source_path}");
    println!("Target: {target_path}");
    println!();

    if result.identical {
        println!("✓ Archives are identical");
        return Ok(());
    }

    println!("✗ Archives differ");
    println!();

    // Metadata differences
    if !result.metadata.matches {
        println!("Metadata Differences:");
        if result.metadata.format_version.0 != result.metadata.format_version.1 {
            println!(
                "  Format Version: {:?}{:?}",
                result.metadata.format_version.0, result.metadata.format_version.1
            );
        }
        if result.metadata.block_size.0 != result.metadata.block_size.1 {
            println!(
                "  Block Size: {}{}",
                result.metadata.block_size.0, result.metadata.block_size.1
            );
        }
        if result.metadata.file_count.0 != result.metadata.file_count.1 {
            println!(
                "  File Count: {}{}",
                result.metadata.file_count.0, result.metadata.file_count.1
            );
        }
        if result.metadata.archive_size.0 != result.metadata.archive_size.1 {
            println!(
                "  Archive Size: {}{}",
                format_bytes(result.metadata.archive_size.0),
                format_bytes(result.metadata.archive_size.1)
            );
        }
        println!();
    }

    // File differences
    if let Some(files) = &result.files {
        if !files.source_only.is_empty() {
            println!(
                "Files only in source ({}): {}",
                files.source_only.len(),
                files
                    .source_only
                    .iter()
                    .take(5)
                    .cloned()
                    .collect::<Vec<_>>()
                    .join(", ")
            );
            if files.source_only.len() > 5 {
                println!("  ... and {} more", files.source_only.len() - 5);
            }
            println!();
        }

        if !files.target_only.is_empty() {
            println!(
                "Files only in target ({}): {}",
                files.target_only.len(),
                files
                    .target_only
                    .iter()
                    .take(5)
                    .cloned()
                    .collect::<Vec<_>>()
                    .join(", ")
            );
            if files.target_only.len() > 5 {
                println!("  ... and {} more", files.target_only.len() - 5);
            }
            println!();
        }

        if !files.size_differences.is_empty() {
            println!(
                "Files with size differences: {}",
                files.size_differences.len()
            );
        }

        if !files.content_differences.is_empty() {
            println!(
                "Files with content differences: {}",
                files.content_differences.len()
            );
        }

        if !files.metadata_differences.is_empty() {
            println!(
                "Files with metadata differences: {}",
                files.metadata_differences.len()
            );
        }
    }

    println!();
    println!(
        "Summary: {} total differences",
        result.summary.different_files
            + result.summary.source_only_count
            + result.summary.target_only_count
    );

    Ok(())
}

fn display_table_output(
    source_path: &str,
    target_path: &str,
    result: &wow_mpq::ComparisonResult,
) -> Result<()> {
    println!(
        "Archive Comparison: {} vs {}",
        truncate_path(source_path, 30),
        truncate_path(target_path, 30)
    );
    println!("{}", "=".repeat(80));

    if result.identical {
        println!("✓ Archives are identical");
        return Ok(());
    }

    // Metadata table
    let mut metadata_table = create_table(vec!["Property", "Source", "Target", "Match"]);
    add_table_row(
        &mut metadata_table,
        vec![
            "Format Version".to_string(),
            format!("{:?}", result.metadata.format_version.0),
            format!("{:?}", result.metadata.format_version.1),
            if result.metadata.format_version.0 == result.metadata.format_version.1 {
                ""
            } else {
                ""
            }
            .to_string(),
        ],
    );
    add_table_row(
        &mut metadata_table,
        vec![
            "Block Size".to_string(),
            result.metadata.block_size.0.to_string(),
            result.metadata.block_size.1.to_string(),
            if result.metadata.block_size.0 == result.metadata.block_size.1 {
                ""
            } else {
                ""
            }
            .to_string(),
        ],
    );
    add_table_row(
        &mut metadata_table,
        vec![
            "File Count".to_string(),
            result.metadata.file_count.0.to_string(),
            result.metadata.file_count.1.to_string(),
            if result.metadata.file_count.0 == result.metadata.file_count.1 {
                ""
            } else {
                ""
            }
            .to_string(),
        ],
    );
    add_table_row(
        &mut metadata_table,
        vec![
            "Archive Size".to_string(),
            format_bytes(result.metadata.archive_size.0),
            format_bytes(result.metadata.archive_size.1),
            if result.metadata.archive_size.0 == result.metadata.archive_size.1 {
                ""
            } else {
                ""
            }
            .to_string(),
        ],
    );

    println!("\nMetadata Comparison:");
    metadata_table.printstd();

    // File differences
    if let Some(files) = &result.files
        && (!files.source_only.is_empty()
            || !files.target_only.is_empty()
            || !files.size_differences.is_empty())
    {
        println!("\nFile Differences:");

        if !files.source_only.is_empty() {
            println!("\nFiles only in source ({}):", files.source_only.len());
            for file in files.source_only.iter().take(10) {
                println!("  - {file}");
            }
            if files.source_only.len() > 10 {
                println!("  ... and {} more", files.source_only.len() - 10);
            }
        }

        if !files.target_only.is_empty() {
            println!("\nFiles only in target ({}):", files.target_only.len());
            for file in files.target_only.iter().take(10) {
                println!("  + {file}");
            }
            if files.target_only.len() > 10 {
                println!("  ... and {} more", files.target_only.len() - 10);
            }
        }

        if !files.size_differences.is_empty() {
            println!("\nFiles with size differences:");
            let mut size_table =
                create_table(vec!["File", "Source Size", "Target Size", "Compression"]);

            for diff in files.size_differences.iter().take(10) {
                add_table_row(
                    &mut size_table,
                    vec![
                        truncate_path(&diff.name, 40),
                        format_bytes(diff.source_size),
                        format_bytes(diff.target_size),
                        format!(
                            "{}{}",
                            format_compression_ratio(diff.source_size, diff.source_compressed),
                            format_compression_ratio(diff.target_size, diff.target_compressed)
                        ),
                    ],
                );
            }

            size_table.printstd();

            if files.size_differences.len() > 10 {
                println!(
                    "... and {} more files with size differences",
                    files.size_differences.len() - 10
                );
            }
        }

        if !files.content_differences.is_empty() {
            println!(
                "\nFiles with content differences ({}):",
                files.content_differences.len()
            );
            for file in files.content_differences.iter().take(10) {
                println!("{file}");
            }
            if files.content_differences.len() > 10 {
                println!("  ... and {} more", files.content_differences.len() - 10);
            }
        }
    }

    // Summary
    println!("\nSummary:");
    println!("  {} files identical", result.summary.identical_files);
    println!("  {} files different", result.summary.different_files);
    println!(
        "  {} files only in source",
        result.summary.source_only_count
    );
    println!(
        "  {} files only in target",
        result.summary.target_only_count
    );

    Ok(())
}

fn display_json_output(result: &wow_mpq::ComparisonResult) -> Result<()> {
    // For now, just pretty-print the debug representation
    // In a real implementation, you'd use serde_json
    println!("{result:#?}");
    Ok(())
}

fn show_tree(
    path: &str,
    max_depth: Option<usize>,
    show_external_refs: bool,
    no_color: bool,
    compact: bool,
    filter: Option<String>,
) -> Result<()> {
    let spinner = create_spinner("Analyzing archive structure...");
    let mut archive = Archive::open(path).context("Failed to open archive")?;
    let info = archive.get_info()?;
    spinner.finish_and_clear();

    // Create root node with archive information
    let mut root = TreeNode::new(
        format!(
            "{}",
            std::path::Path::new(path)
                .file_name()
                .unwrap()
                .to_string_lossy()
        ),
        NodeType::Root,
    )
    .with_size(info.file_size)
    .with_metadata("format", &format!("{:?}", info.format_version))
    .with_metadata("files", &info.file_count.to_string());

    // Add header information
    let header = TreeNode::new("Header".to_string(), NodeType::Header)
        .with_size(32) // Typical MPQ header size
        .with_metadata("version", &format!("{:?}", info.format_version))
        .with_metadata("sector_size", &format!("{}", info.sector_size));

    root = root.add_child(header);

    // Add hash table information
    if let Some(hash_table) = archive.hash_table() {
        let hash_node = TreeNode::new("Hash Table".to_string(), NodeType::Table)
            .with_size((hash_table.size() * 16) as u64) // Each hash entry is 16 bytes
            .with_metadata("entries", &hash_table.size().to_string())
            .with_metadata("encrypted", "true");
        root = root.add_child(hash_node);
    }

    // Add block table information
    if let Some(block_table) = archive.block_table() {
        let block_node = TreeNode::new("Block Table".to_string(), NodeType::Table)
            .with_size((block_table.size() * 16) as u64) // Each block entry is 16 bytes
            .with_metadata("entries", &block_table.size().to_string())
            .with_metadata("encrypted", "true");
        root = root.add_child(block_node);
    }

    // Add HET/BET tables if present
    if archive.het_table().is_some() {
        let het_node = TreeNode::new("HET Table".to_string(), NodeType::Table)
            .with_metadata("type", "Extended Hash Table")
            .with_metadata("version", "v4");
        root = root.add_child(het_node);
    }

    if archive.bet_table().is_some() {
        let bet_node = TreeNode::new("BET Table".to_string(), NodeType::Table)
            .with_metadata("type", "Extended Block Table")
            .with_metadata("version", "v4");
        root = root.add_child(bet_node);
    }

    // Build file tree
    let files: Vec<String> = archive.list()?.into_iter().map(|e| e.name).collect();
    let pattern = filter.as_deref().unwrap_or("*");
    let filtered_files: Vec<_> = files
        .iter()
        .filter(|f| matches_pattern(f, pattern))
        .collect();

    if !filtered_files.is_empty() {
        let mut files_node = TreeNode::new("Files".to_string(), NodeType::Directory)
            .with_metadata("count", &filtered_files.len().to_string());

        // Build directory structure
        let mut dir_structure = std::collections::BTreeMap::<String, Vec<&String>>::new();

        for file in &filtered_files {
            let path_parts: Vec<&str> = file.split('\\').collect();
            if path_parts.len() > 1 {
                let dir = path_parts[..path_parts.len() - 1].join("\\");
                dir_structure.entry(dir).or_default().push(file);
            } else {
                dir_structure.entry("/".to_string()).or_default().push(file);
            }
        }

        // Add directories and files to tree
        for (dir_path, dir_files) in dir_structure {
            if dir_path == "/" {
                // Root level files
                for file in dir_files {
                    let file_node = create_file_node(file, &mut archive, show_external_refs)?;
                    files_node = files_node.add_child(file_node);
                }
            } else {
                // Directory with files
                let mut dir_node = TreeNode::new(
                    format!("{}/", dir_path.split('\\').next_back().unwrap_or(&dir_path)),
                    NodeType::Directory,
                )
                .with_metadata("files", &dir_files.len().to_string());

                for file in dir_files {
                    let file_node = create_file_node(file, &mut archive, show_external_refs)?;
                    dir_node = dir_node.add_child(file_node);
                }

                files_node = files_node.add_child(dir_node);
            }
        }

        root = root.add_child(files_node);
    }

    // Add special files
    let special_files = vec!["(listfile)", "(attributes)", "(signature)"];
    for special_file in special_files {
        if archive.read_file(special_file).is_ok() {
            let special_node = match special_file {
                "(listfile)" => TreeNode::new("(listfile)".to_string(), NodeType::File)
                    .with_metadata("type", "Auto-generated file list")
                    .with_metadata("purpose", "File enumeration"),
                "(attributes)" => TreeNode::new("(attributes)".to_string(), NodeType::File)
                    .with_metadata("type", "File attributes")
                    .with_metadata("purpose", "CRC checksums and timestamps"),
                "(signature)" => TreeNode::new("(signature)".to_string(), NodeType::File)
                    .with_metadata("type", "Digital signature")
                    .with_metadata("purpose", "Archive integrity verification"),
                _ => continue,
            };
            root = root.add_child(special_node);
        }
    }

    // Render the tree
    let options = TreeOptions {
        max_depth,
        show_external_refs,
        no_color,
        show_metadata: true,
        compact,
        verbose: false,
    };

    println!("{}", render_tree(&root, &options));
    Ok(())
}

fn create_file_node(
    file_path: &str,
    archive: &mut Archive,
    show_external_refs: bool,
) -> Result<TreeNode> {
    let file_name = file_path.split('\\').next_back().unwrap_or(file_path);
    let extension = std::path::Path::new(file_name)
        .extension()
        .and_then(|e| e.to_str())
        .unwrap_or("");

    let mut node = TreeNode::new(file_name.to_string(), NodeType::File);

    // Add file size if available
    if let Ok(entries) = archive.list()
        && let Some(entry) = entries.iter().find(|e| e.name == file_path)
    {
        node = node
            .with_size(entry.size)
            .with_metadata("compressed_size", &format_bytes(entry.compressed_size))
            .with_metadata(
                "compression_ratio",
                &format_compression_ratio(entry.size, entry.compressed_size),
            );
    }

    // Add file type metadata
    let file_type = match extension.to_lowercase().as_str() {
        "blp" => "Texture",
        "m2" | "mdx" => "Model",
        "wdt" => "World Map Definition",
        "adt" => "Terrain Data",
        "wdl" => "Low-res Terrain",
        "dbc" => "Database",
        "lua" => "Script",
        "xml" => "Interface Definition",
        "toc" => "AddOn Manifest",
        "wav" | "mp3" => "Audio",
        _ => "Data",
    };
    node = node.with_metadata("type", file_type);

    // Add external references for certain file types
    if show_external_refs {
        match extension.to_lowercase().as_str() {
            "wdt" => {
                // WDT files reference ADT files
                let base_name = file_name.trim_end_matches(".wdt");
                node = node
                    .with_external_ref(&format!("{base_name}/*.adt"), detect_ref_type("file.adt"));
            }
            "adt" => {
                // ADT files might reference textures and models
                node = node.with_external_ref("*.blp", detect_ref_type("file.blp"));
                node = node.with_external_ref("*.m2", detect_ref_type("file.m2"));
            }
            "m2" => {
                // M2 files reference textures and animations
                let base_name = file_name.trim_end_matches(".m2");
                node = node
                    .with_external_ref(&format!("{base_name}.skin"), detect_ref_type("file.skin"));
                node = node.with_external_ref("*.blp", detect_ref_type("file.blp"));
            }
            "dbc"
                if file_name.to_lowercase().contains("item") =>
            {
                node = node.with_external_ref("Interface/Icons/*.blp", detect_ref_type("file.blp"));
            }
            _ => {}
        }
    }

    Ok(node)
}

fn debug_archive(params: DebugParams<'_>) -> Result<()> {
    let spinner = create_spinner("Opening archive...");
    let mut archive = Archive::open(params.archive_path).context("Failed to open archive")?;
    spinner.finish_and_clear();

    println!("🔍 MPQ Debug Information");
    println!("========================");
    println!("Archive: {}", params.archive_path);

    let info = archive.get_info()?;
    println!("Format: {:?}", info.format_version);
    println!("Files: {}/{}", info.file_count, info.max_file_count);
    println!();

    // Handle finding a specific file first
    if let Some(filename) = &params.find_file {
        return find_file_entries(&mut archive, filename, params.raw_dump);
    }

    // Handle specific entry index
    if let Some(index) = params.entry_index {
        return show_entry_at_index(&mut archive, index, params.raw_dump);
    }

    // Show requested tables
    if params.show_hash_table {
        show_hash_table(&mut archive, params.raw_dump)?;
    }

    if params.show_block_table {
        show_block_table(&mut archive, params.raw_dump)?;
    }

    if params.show_het_table {
        show_het_table(&mut archive, params.raw_dump)?;
    }

    if params.show_bet_table {
        show_bet_table(&mut archive, params.raw_dump)?;
    }

    Ok(())
}

fn show_hash_table(archive: &mut Archive, raw_dump: bool) -> Result<()> {
    println!("🔑 Hash Table");
    println!("-------------");

    if let Some(hash_table) = archive.hash_table() {
        if raw_dump {
            // Show raw hex dump of the hash table
            let entries = hash_table.entries();
            let data_size = std::mem::size_of_val(entries);
            println!("Raw data ({data_size} bytes):");

            // Convert entries to bytes for hex dump
            let bytes =
                unsafe { std::slice::from_raw_parts(entries.as_ptr() as *const u8, data_size) };

            let config = HexDumpConfig {
                bytes_per_line: 16,
                show_ascii: false,
                show_offset: true,
                max_bytes: 512,
            };
            println!("{}", hex_dump(bytes, &config));
        } else {
            // Use the formatted table display
            println!("{}", format_hash_table(hash_table.entries()));
        }
    } else {
        println!("No hash table found (archive may use HET/BET tables)");
    }
    println!();

    Ok(())
}

fn show_block_table(archive: &mut Archive, raw_dump: bool) -> Result<()> {
    println!("📦 Block Table");
    println!("--------------");

    if let Some(block_table) = archive.block_table() {
        if raw_dump {
            // Show raw hex dump of the block table
            let entries = block_table.entries();
            let data_size = std::mem::size_of_val(entries);
            println!("Raw data ({data_size} bytes):");

            // Convert entries to bytes for hex dump
            let bytes =
                unsafe { std::slice::from_raw_parts(entries.as_ptr() as *const u8, data_size) };

            let config = HexDumpConfig {
                bytes_per_line: 16,
                show_ascii: false,
                show_offset: true,
                max_bytes: 512,
            };
            println!("{}", hex_dump(bytes, &config));
        } else {
            // Use the formatted table display
            println!("{}", format_block_table(block_table.entries()));
        }
    } else {
        println!("No block table found (archive may use HET/BET tables)");
    }
    println!();

    Ok(())
}

fn show_het_table(archive: &mut Archive, raw_dump: bool) -> Result<()> {
    println!("🔍 HET Table (Extended Hash Table)");
    println!("----------------------------------");

    if let Some(het_table) = archive.het_table() {
        if raw_dump {
            println!("Raw HET data not yet implemented");
        } else {
            // Use the formatted display
            println!("{}", format_het_table(het_table));
        }
    } else {
        println!("No HET table found");
    }
    println!();

    Ok(())
}

fn show_bet_table(archive: &mut Archive, raw_dump: bool) -> Result<()> {
    println!("📋 BET Table (Extended Block Table)");
    println!("-----------------------------------");

    if let Some(bet_table) = archive.bet_table() {
        if raw_dump {
            println!("Raw BET data not yet implemented");
        } else {
            // Use the formatted display
            println!("{}", format_bet_table(bet_table));
        }
    } else {
        println!("No BET table found");
    }
    println!();

    Ok(())
}

fn find_file_entries(archive: &mut Archive, filename: &str, _raw_dump: bool) -> Result<()> {
    println!("🔎 Finding entries for: {filename}");
    println!("========================");

    // Try to find the file using the archive's find_file method
    match archive.find_file(filename)? {
        Some(file_info) => {
            println!("✓ File found!");
            println!("  Hash table index: {}", file_info.hash_index);
            println!("  Block table index: {}", file_info.block_index);
            println!("  File position: 0x{:08X}", file_info.file_pos);
            println!("  File size: {}", format_bytes(file_info.file_size));
            println!(
                "  Compressed size: {}",
                format_bytes(file_info.compressed_size)
            );
            println!("  Flags: 0x{:08X}", file_info.flags);
            println!("  Locale: 0x{:04X}", file_info.locale);
            println!();

            // Show hash entry
            if let Some(hash_table) = archive.hash_table()
                && let Some(hash_entry) = hash_table.entries().get(file_info.hash_index)
            {
                println!("Hash Entry:");
                println!("{}", dump_hash_entry(hash_entry, file_info.hash_index));
            }

            // Show block entry
            if let Some(block_table) = archive.block_table()
                && let Some(block_entry) = block_table.entries().get(file_info.block_index)
            {
                println!("\nBlock Entry:");
                println!("{}", dump_block_entry(block_entry, file_info.block_index));
            }
        }
        None => {
            println!("✗ File not found in archive");
        }
    }

    Ok(())
}

fn show_entry_at_index(archive: &mut Archive, index: usize, _raw_dump: bool) -> Result<()> {
    println!("📍 Entry at index: {index}");
    println!("===================");

    let mut found = false;

    // Check hash table
    if let Some(hash_table) = archive.hash_table()
        && let Some(hash_entry) = hash_table.entries().get(index)
    {
        println!("Hash Entry:");
        println!("{}", dump_hash_entry(hash_entry, index));
        found = true;
    }

    // Check block table
    if let Some(block_table) = archive.block_table()
        && let Some(block_entry) = block_table.entries().get(index)
    {
        if found {
            println!();
        }
        println!("Block Entry:");
        println!("{}", dump_block_entry(block_entry, index));
        found = true;
    }

    if !found {
        println!("No entry found at index {index}");
    }

    Ok(())
}

// Database command implementation
async fn execute_db_command(command: DbCommands) -> Result<()> {
    use crate::database::{Database, HashLookup, ImportSource, Importer};
    use crate::database::{calculate_het_hashes, calculate_mpq_hashes};
    use std::io::Write;

    match command {
        DbCommands::Status { detailed } => {
            let db = Database::open_default()
                .await
                .context("Failed to open database")?;
            let conn = db.connection();

            // Get basic statistics
            let filename_count: i64 = {
                let mut rows = conn.query("SELECT COUNT(*) FROM filenames", ()).await?;
                match rows.next().await? {
                    Some(row) => row.get(0)?,
                    None => 0,
                }
            };

            println!("MPQ Hash Database Status");
            println!("========================");
            println!("Database location: {}", db.path().display());
            println!("Total filenames: {filename_count}");

            if detailed {
                println!("\nDetailed Statistics:");

                // Count by source
                let mut rows = conn
                    .query(
                        "SELECT source, COUNT(*) FROM filenames GROUP BY source ORDER BY COUNT(*) DESC",
                        (),
                    )
                    .await?;

                println!("\nFilenames by source:");
                while let Some(row) = rows.next().await? {
                    let src: Option<String> = row.get(0).ok();
                    let count: i64 = row.get(1)?;
                    println!(
                        "  {}: {}",
                        src.unwrap_or_else(|| "unknown".to_string()),
                        count
                    );
                }

                // Recent additions
                let mut rows = conn
                    .query(
                        "SELECT filename, created_at FROM filenames ORDER BY created_at DESC LIMIT 10",
                        (),
                    )
                    .await?;

                println!("\nMost recent additions:");
                while let Some(row) = rows.next().await? {
                    let filename: String = row.get(0)?;
                    let created_at: String = row.get(1)?;
                    println!("  {filename} - {created_at}");
                }
            }

            Ok(())
        }

        DbCommands::Import {
            path,
            source_type,
            show_progress,
        } => {
            let db = Database::open_default()
                .await
                .context("Failed to open database")?;
            let importer = Importer::new(&db);

            let import_source = match source_type {
                ImportSourceArg::Listfile => ImportSource::Listfile,
                ImportSourceArg::Archive => ImportSource::Archive,
                ImportSourceArg::Directory => ImportSource::Directory,
            };

            let spinner = if show_progress {
                Some(create_spinner(&format!("Importing from {path}...")))
            } else {
                None
            };

            let stats = importer
                .import(Path::new(&path), import_source)
                .await
                .context("Import failed")?;

            if let Some(s) = spinner {
                s.finish_and_clear();
            }

            println!("Import completed:");
            println!("  Files processed: {}", stats.files_processed);
            println!("  New entries added: {}", stats.new_entries);
            println!("  Existing entries updated: {}", stats.updated_entries);
            if stats.errors > 0 {
                println!("  Errors: {}", stats.errors);
            }

            Ok(())
        }

        DbCommands::Analyze {
            archive,
            include_anonymous,
        } => {
            let db = Database::open_default()
                .await
                .context("Failed to open database")?;
            let mut mpq = Archive::open(&archive).context("Failed to open archive")?;

            let spinner = create_spinner("Analyzing archive...");

            // Record listfile entries
            let count = record_listfile_to_db(&mut mpq, &db).await?;

            spinner.finish_with_message(format!("Recorded {count} filenames from listfile"));

            if include_anonymous {
                // TODO: Could also record anonymous entries with generated names
                println!("Note: Recording anonymous entries not yet implemented");
            }

            Ok(())
        }

        DbCommands::Lookup { filename } => {
            let db = Database::open_default()
                .await
                .context("Failed to open database")?;

            // Calculate and display hashes
            let (hash_a, hash_b, hash_offset) = calculate_mpq_hashes(&filename);
            let het_40 = calculate_het_hashes(&filename, 40);
            let het_48 = calculate_het_hashes(&filename, 48);
            let het_56 = calculate_het_hashes(&filename, 56);
            let het_64 = calculate_het_hashes(&filename, 64);

            println!("Filename: {filename}");
            println!("\nTraditional MPQ hashes:");
            println!("  Hash A (Name1):  0x{hash_a:08X}");
            println!("  Hash B (Name2):  0x{hash_b:08X}");
            println!("  Table Offset:    0x{hash_offset:08X}");

            println!("\nHET hashes:");
            println!(
                "  40-bit: file=0x{:010X}, name=0x{:010X}",
                het_40.0, het_40.1
            );
            println!(
                "  48-bit: file=0x{:012X}, name=0x{:012X}",
                het_48.0, het_48.1
            );
            println!(
                "  56-bit: file=0x{:014X}, name=0x{:014X}",
                het_56.0, het_56.1
            );
            println!(
                "  64-bit: file=0x{:016X}, name=0x{:016X}",
                het_64.0, het_64.1
            );

            // Check if it exists in database
            if db.filename_exists(&filename).await? {
                println!("\n✓ Filename exists in database");
            } else {
                println!("\n✗ Filename not found in database");
            }

            Ok(())
        }

        DbCommands::Export { output, source } => {
            let db = Database::open_default()
                .await
                .context("Failed to open database")?;
            let conn = db.connection();

            let mut file = fs::File::create(&output).context("Failed to create output file")?;
            let mut count = 0;

            if let Some(src) = source {
                let mut rows = conn
                    .query(
                        "SELECT DISTINCT filename FROM filenames WHERE source = ?1 ORDER BY filename",
                        turso::params![src],
                    )
                    .await?;

                while let Some(row) = rows.next().await? {
                    let filename: String = row.get(0)?;
                    writeln!(file, "{filename}")?;
                    count += 1;
                }
            } else {
                let mut rows = conn
                    .query(
                        "SELECT DISTINCT filename FROM filenames ORDER BY filename",
                        (),
                    )
                    .await?;

                while let Some(row) = rows.next().await? {
                    let filename: String = row.get(0)?;
                    writeln!(file, "{filename}")?;
                    count += 1;
                }
            };

            println!("Exported {count} filenames to {output}");

            Ok(())
        }

        DbCommands::List {
            filter,
            long,
            limit,
        } => {
            let db = Database::open_default()
                .await
                .context("Failed to open database")?;
            let conn = db.connection();

            let mut result_rows: Vec<(String, i64, i64, Option<String>)> = Vec::new();

            if let Some(pattern) = filter {
                let like_pattern = pattern.replace('*', "%");
                let query = format!(
                    "SELECT filename, hash_a, hash_b, source FROM filenames WHERE filename LIKE ?1 ORDER BY filename LIMIT {limit}"
                );
                let mut rows = conn.query(&query, turso::params![like_pattern]).await?;

                while let Some(row) = rows.next().await? {
                    result_rows.push((
                        row.get::<String>(0)?,
                        row.get::<i64>(1)?,
                        row.get::<i64>(2)?,
                        row.get::<Option<String>>(3).ok().flatten(),
                    ));
                }
            } else {
                let query = format!(
                    "SELECT filename, hash_a, hash_b, source FROM filenames ORDER BY filename LIMIT {limit}"
                );
                let mut rows = conn.query(&query, ()).await?;

                while let Some(row) = rows.next().await? {
                    result_rows.push((
                        row.get::<String>(0)?,
                        row.get::<i64>(1)?,
                        row.get::<i64>(2)?,
                        row.get::<Option<String>>(3).ok().flatten(),
                    ));
                }
            }

            if long {
                let mut table = create_table(vec!["Filename", "Hash A", "Hash B", "Source"]);
                for (filename, hash_a, hash_b, source) in result_rows {
                    add_table_row(
                        &mut table,
                        vec![
                            filename,
                            format!("0x{hash_a:08X}"),
                            format!("0x{hash_b:08X}"),
                            source.unwrap_or_else(|| "unknown".to_string()),
                        ],
                    );
                }
                println!("{table}");
            } else {
                for (filename, _, _, _) in result_rows {
                    println!("{filename}");
                }
            }

            Ok(())
        }
    }
}

fn visualize_patch_chain(base: &str, patches: Vec<String>, detailed: bool) -> Result<()> {
    println!("Building patch chain...");

    let mut chain = PatchChain::new();

    // Add base archive with priority 0
    chain
        .add_archive(base, 0)
        .context("Failed to add base archive")?;
    println!("  [0] {} (base)", base);

    // Add patch archives with increasing priority
    for (index, patch_path) in patches.iter().enumerate() {
        let priority = (index + 1) * 100;
        chain
            .add_archive(patch_path, priority as i32)
            .with_context(|| format!("Failed to add patch archive: {patch_path}"))?;
        println!("  [{}] {} (priority: {})", index + 1, patch_path, priority);
    }

    println!("\nChain summary:");
    let chain_info = chain.get_chain_info();
    let total_files: usize = chain_info.iter().map(|i| i.file_count).sum();
    println!("  Total archives: {}", chain_info.len());
    println!("  Total files (with overlaps): {total_files}");

    // Count unique files
    let unique_files = chain.list()?.len();
    println!("  Unique files: {unique_files}");

    if detailed {
        println!("\nDetailed archive information:");
        let mut table = create_table(vec!["Archive", "Priority", "Files", "Path"]);

        for info in chain_info {
            add_table_row(
                &mut table,
                vec![
                    info.path
                        .file_name()
                        .and_then(|n| n.to_str())
                        .unwrap_or("?")
                        .to_string(),
                    info.priority.to_string(),
                    info.file_count.to_string(),
                    truncate_path(&info.path.display().to_string(), 60),
                ],
            );
        }

        table.printstd();

        // Show sample of files that have patches
        println!("\nScanning for patch files...");
        let mut patch_count = 0;
        let entries = chain.list()?;

        for entry in &entries {
            if entry.is_patch_file() {
                patch_count += 1;
            }
        }

        if patch_count > 0 {
            println!("  Found {} file(s) with patch flag", patch_count);

            if patch_count <= 20 {
                println!("\nPatch files:");
                for entry in entries {
                    if entry.is_patch_file() {
                        println!("  - {} ({} bytes)", entry.name, entry.size);
                    }
                }
            } else {
                println!("  (Use 'mpq list <archive> --show-patches' to see all patch files)");
            }
        } else {
            println!("  No PTCH format patch files found (files may use replacement method)");
        }
    }

    Ok(())
}