fs-mac 0.1.0

Read, edit, create, check and clone classic Mac filesystems: MFS, HFS (incl. HFV images), HFS+/HFSX and Lisa, plus resource forks and BinHex
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
//! Macintosh File System (MFS) — the pre-HFS filesystem shipped on 400 KB
//! single-sided 3.5" floppies for the original Mac, Mac 512K, and the
//! Macintosh Plus (until System 3.0 brought HFS).
//!
//! Used by the MiSTer **MacPlus** core when a `.dsk` is a 400 KB MFS
//! floppy rather than an HFS volume. The plan ([`docs/mister_filesystem_
//! implementation_plan.md`] Wave 1) targets an **extract-only floor**:
//! browse + read data fork (+ surface resource-fork size). Add/Delete and
//! resize are intentionally out of scope — the core itself rarely writes
//! MFS, and `BasiliskII` is the natural authoring path when one does.
//!
//! ## On-disk layout (Inside Macintosh: Files, Volume II, ch. 2)
//!
//! - **Sectors 0..1** (offset 0..1024) — boot blocks (zeroed on most non-
//!   bootable disks)
//! - **Sector 2** (offset 1024) — Master Directory Block (MDB):
//!
//! ```text
//! 0x00  u16   drSigWord     0xD2D7  (MFS magic)
//! 0x02  u32   drCrDate      create date (Mac epoch 1904-01-01)
//! 0x06  u32   drLsBkUp      last backup date
//! 0x0A  u16   drAtrb        volume attributes
//! 0x0C  u16   drNmFls       number of files
//! 0x0E  u16   drDirSt       first logical (512 B) block of the file directory
//! 0x10  u16   drBlLen       length of file directory in logical blocks
//! 0x12  u16   drNmAlBlks    number of allocation blocks
//! 0x14  u32   drAlBlkSiz    allocation-block size in bytes
//! 0x18  u32   drClpSiz      clump size (unused for extract)
//! 0x1C  u16   drAlBlSt      first allocation block in logical sectors
//! 0x1E  u32   drNxtFNum     next free file number
//! 0x22  u16   drFreeBks     free allocation blocks
//! 0x24  pstr  drVN          volume name (Pascal string, ≤27 chars)
//! ```
//!
//! - **Volume map** — starts immediately after the volume-name Pascal
//!   string and continues into subsequent sectors as needed. 12 bits per
//!   allocation block:
//!     - entries 0, 1 reserved
//!     - entry N ≥ 2 = pointer to next allocation block in the file's
//!       chain, or `0` (free) or `1` (last block of chain)
//!
//! - **File Directory** — `drBlLen` × 512 B sectors starting at logical
//!   sector `drDirSt`. Variable-length entries (rounded to even):
//!
//! ```text
//! 0x00  u8    flFlags       bit7 set = entry used; bit0 = locked
//! 0x01  u8    flTyp         version (=0)
//! 0x02  16    flUsrWds      Finder info (type/creator at +0/+4)
//! 0x12  u32   flFlNum       file number
//! 0x16  u16   flStBlk       first data-fork allocation block (0 = empty)
//! 0x18  u32   flLgLen       logical data-fork length
//! 0x1C  u32   flPyLen       physical data-fork length (rounded)
//! 0x20  u16   flRStBlk      first resource-fork allocation block
//! 0x22  u32   flRLgLen      logical resource-fork length
//! 0x26  u32   flRPyLen      physical resource-fork length
//! 0x2A  u32   flCrDat       create date
//! 0x2E  u32   flMdDat       modify date
//! 0x32  pstr  flNam         Pascal string filename (≤255 in spec; in
//!                           practice ≤63 because System 1.0 limited it)
//! ```
//!
//! Entry length = `0x32 + 1 + name_len`, padded up to the next even
//! offset. An entry where `flFlags & 0x80 == 0` ends the directory in
//! its sector (and the next sector starts a fresh entry).
//!
//! All multi-byte fields are **big-endian** (m68k native).

#[cfg(feature = "rust173-polyfill")]
use disk_core::rust173::IntIsMultipleOf as _;
use std::io::{Read, Seek, SeekFrom, Write};

use byteorder::{BigEndian, ByteOrder};

use disk_core::entry::{EntryType, FileEntry};
use disk_core::filesystem::{
    CreateDirectoryOptions, CreateFileOptions, EditableFilesystem, Filesystem, FilesystemError,
};
use disk_core::fsck::{FsckIssue, FsckResult, FsckStats, RepairReport};

/// MFS magic — big-endian u16 at byte 1024.
pub const MFS_SIGNATURE: u16 = 0xD2D7;

/// MDB offset within the volume.
const MDB_OFFSET: u64 = 1024;

/// 400 KB single-sided 3.5" floppy — the canonical MFS volume size.
pub const MFS_400K_BYTES: u64 = 409_600;

/// 800 KB double-sided 3.5" floppy — supported by MFS too, though rare.
pub const MFS_800K_BYTES: u64 = 819_200;

/// Maximum allocation blocks per the on-disk u16 field.
const MAX_ALLOC_BLOCKS: u32 = 0xFFFF;

/// Maximum allocation-block chain length we walk while reading one fork.
/// MFS volumes are tiny (≤ 800 KB) so this is generous; the cap is a
/// runaway guard, not a real limit.
const MAX_ALLOC_CHAIN: usize = 4096;

/// Parsed MDB fields the rest of the module needs. Stored on the FS so
/// every list/read call can use them without re-reading the boot sector.
#[derive(Debug, Clone)]
pub struct MfsMdb {
    pub create_date: u32,
    pub last_backup_date: u32,
    pub volume_attributes: u16,
    pub num_files: u16,
    pub dir_start_sector: u16,
    pub dir_length_sectors: u16,
    pub num_alloc_blocks: u16,
    pub alloc_block_size: u32,
    pub clump_size: u32,
    pub first_alloc_block_sector: u16,
    pub next_file_number: u32,
    pub free_blocks: u16,
    pub volume_name: String,
    /// Volume-map base byte offset within the partition (right after the
    /// MDB header + volume name Pascal string).
    map_offset: u64,
}

impl MfsMdb {
    /// Parse from a 512-byte buffer assumed to be the MDB sector.
    fn parse(buf: &[u8; 512]) -> Result<Self, FilesystemError> {
        let sig = BigEndian::read_u16(&buf[0..2]);
        if sig != MFS_SIGNATURE {
            return Err(FilesystemError::InvalidData(format!(
                "bad MFS signature: 0x{sig:04X} (expected 0x{MFS_SIGNATURE:04X})"
            )));
        }

        let create_date = BigEndian::read_u32(&buf[2..6]);
        let last_backup_date = BigEndian::read_u32(&buf[6..10]);
        let volume_attributes = BigEndian::read_u16(&buf[10..12]);
        let num_files = BigEndian::read_u16(&buf[12..14]);
        let dir_start_sector = BigEndian::read_u16(&buf[14..16]);
        let dir_length_sectors = BigEndian::read_u16(&buf[16..18]);
        let num_alloc_blocks = BigEndian::read_u16(&buf[18..20]);
        let alloc_block_size = BigEndian::read_u32(&buf[20..24]);
        let clump_size = BigEndian::read_u32(&buf[24..28]);
        let first_alloc_block_sector = BigEndian::read_u16(&buf[28..30]);
        let next_file_number = BigEndian::read_u32(&buf[30..34]);
        let free_blocks = BigEndian::read_u16(&buf[34..36]);

        // Volume name: Pascal string at offset 36 (1 length byte + chars).
        let name_len = buf[36] as usize;
        if 37 + name_len > 64 {
            // Spec caps Pascal-string name length at 27 in MFS; we tolerate
            // up to 27, defensively reject anything past 64 - 37 = 27 bytes.
            return Err(FilesystemError::InvalidData(format!(
                "MFS volume name length {name_len} exceeds 27"
            )));
        }
        let volume_name = crate::hfs::mac_roman_to_utf8(&buf[37..37 + name_len]);

        // The volume allocation block map begins at a *fixed* offset 64 within
        // the MDB block (the volume-name field is fixed-width: 1 length byte +
        // 27 reserved chars = bytes 36..63, map at 64). The bit-packed map
        // continues into subsequent sectors when num_alloc_blocks * 12 bits
        // overflows. (An earlier version placed it right after the actual name,
        // which only coincides with 64 for a full 27-char name and corrupted
        // every real disk with a shorter name.)
        let map_offset = MDB_OFFSET + 64;

        // Sanity: alloc_block_size must be a positive multiple of 512.
        if alloc_block_size == 0 || alloc_block_size % 512 != 0 {
            return Err(FilesystemError::InvalidData(format!(
                "MFS allocation block size {alloc_block_size} is not a positive multiple of 512"
            )));
        }
        if num_alloc_blocks as u32 > MAX_ALLOC_BLOCKS {
            return Err(FilesystemError::InvalidData(format!(
                "MFS allocation-block count {num_alloc_blocks} exceeds 65535"
            )));
        }
        if dir_length_sectors == 0 {
            return Err(FilesystemError::InvalidData(
                "MFS file directory length is 0".into(),
            ));
        }

        Ok(MfsMdb {
            create_date,
            last_backup_date,
            volume_attributes,
            num_files,
            dir_start_sector,
            dir_length_sectors,
            num_alloc_blocks,
            alloc_block_size,
            clump_size,
            first_alloc_block_sector,
            next_file_number,
            free_blocks,
            volume_name,
            map_offset,
        })
    }
}

/// One File Directory entry, decoded.
#[derive(Debug, Clone)]
#[allow(dead_code)] // dates + finder_info kept for round-trip / future write
struct MfsDirEntry {
    /// Bit 7 = entry is in use; bit 0 = file locked.
    flags: u8,
    /// 16-byte Finder info — type at +0, creator at +4.
    finder_info: [u8; 16],
    file_number: u32,
    data_first_block: u16,
    data_logical_length: u32,
    rsrc_first_block: u16,
    rsrc_logical_length: u32,
    create_date: u32,
    modify_date: u32,
    name: String,
}

impl MfsDirEntry {
    fn is_in_use(&self) -> bool {
        self.flags & 0x80 != 0
    }

    /// Finder flags (`FInfo.fdFlags`) — the big-endian 2-byte field at offset 8
    /// of the 16-byte Finder info. Surfaced on `FileEntry` so copy /
    /// `get-binhex` round-trips preserve them.
    fn finder_flags(&self) -> u16 {
        u16::from_be_bytes([self.finder_info[8], self.finder_info[9]])
    }
}

/// Live MFS reader. Holds the parsed MDB, the volume bitmap, and a
/// re-decoded directory cache (small — at most a few hundred entries on
/// a 400 KB floppy).
pub struct MfsFilesystem<R: Read + Seek + Send> {
    reader: R,
    partition_offset: u64,
    pub(crate) mdb: MfsMdb,
    /// Cached directory entries, keyed by file number for O(1) lookup
    /// from `read_file`.
    entries: Vec<MfsDirEntry>,
    /// Allocation-block-map bytes (12-bit packed). Cached on open.
    map_bytes: Vec<u8>,
}

impl<R: Read + Seek + Send> MfsFilesystem<R> {
    /// Open an MFS volume at the given partition offset.
    pub fn open(mut reader: R, partition_offset: u64) -> Result<Self, FilesystemError> {
        reader.seek(SeekFrom::Start(partition_offset + MDB_OFFSET))?;
        let mut mdb_buf = [0u8; 512];
        reader.read_exact(&mut mdb_buf)?;
        let mdb = MfsMdb::parse(&mdb_buf)?;

        // Read the allocation-block map. We need (num_alloc_blocks * 12 + 7) / 8
        // bytes starting at `mdb.map_offset`, possibly straddling sectors.
        let map_bits = mdb.num_alloc_blocks as usize * 12;
        let map_byte_len = map_bits.div_ceil(8);
        let mut map_bytes = vec![0u8; map_byte_len];
        reader.seek(SeekFrom::Start(partition_offset + mdb.map_offset))?;
        reader.read_exact(&mut map_bytes)?;

        // Read the file directory.
        let mut entries = Vec::new();
        for sector_idx in 0..mdb.dir_length_sectors {
            let sector_no = mdb.dir_start_sector as u64 + sector_idx as u64;
            let sector_off = partition_offset + sector_no * 512;
            reader.seek(SeekFrom::Start(sector_off))?;
            let mut sec = [0u8; 512];
            if reader.read_exact(&mut sec).is_err() {
                break;
            }
            parse_dir_sector(&sec, &mut entries);
        }

        Ok(MfsFilesystem {
            reader,
            partition_offset,
            mdb,
            entries,
            map_bytes,
        })
    }

    /// Look up entry index by file number.
    fn entry_by_file_number(&self, fnum: u32) -> Option<&MfsDirEntry> {
        self.entries
            .iter()
            .find(|e| e.is_in_use() && e.file_number == fnum)
    }

    /// Look up a 12-bit volume-map entry. Returns 0 if `block` is out of
    /// range (allocation blocks 0 and 1 are reserved and always read as 0).
    fn map_get(&self, block: u16) -> u16 {
        if block < 2 {
            return 0;
        }
        // Map entry index 0 corresponds to allocation block 2, so the entry for
        // block N lives at bit (N - 2) * 12. Entries are 12-bit, high-order
        // first; two pack into three bytes.
        let bit_off = (block as usize - 2) * 12;
        let byte_off = bit_off / 8;
        if byte_off + 1 >= self.map_bytes.len() {
            return 0;
        }
        // Entry-index parity equals block parity (index = block - 2), so the
        // nibble alignment can still key off `block`.
        if block.is_multiple_of(2) {
            // even block: high nibble of byte_off (which is block*12/8) is the LOW
            // 4 bits of the entry, byte_off+1 high 8 bits... Actually it's
            // simpler: 12 bits big-endian-packed: bits b*12 .. b*12+11 of the map.
            let hi = self.map_bytes[byte_off] as u16;
            let lo = (self.map_bytes[byte_off + 1] >> 4) as u16;
            (hi << 4) | lo
        } else {
            let hi = (self.map_bytes[byte_off] & 0x0F) as u16;
            let lo = self.map_bytes[byte_off + 1] as u16;
            (hi << 8) | lo
        }
    }

    /// Byte offset of allocation block N in the volume.
    fn alloc_block_offset(&self, block: u16) -> u64 {
        // Allocation block 2 maps to logical sector `first_alloc_block_sector`.
        // Block N maps to logical sector first_alloc_block_sector + (N - 2) * (alloc_block_size / 512).
        debug_assert!(block >= 2);
        let sectors_per_block = (self.mdb.alloc_block_size / 512) as u64;
        let sector =
            self.mdb.first_alloc_block_sector as u64 + (block as u64 - 2) * sectors_per_block;
        sector * 512
    }

    /// Walk an allocation-block chain starting at `first` and read
    /// `logical_len` bytes. Returns the chained bytes (truncated to
    /// `logical_len`).
    fn read_chain(&mut self, first: u16, logical_len: u32) -> Result<Vec<u8>, FilesystemError> {
        if first == 0 || logical_len == 0 {
            return Ok(Vec::new());
        }
        let mut data = Vec::with_capacity(logical_len as usize);
        let bs = self.mdb.alloc_block_size as usize;
        let mut block = first;
        for _hop in 0..MAX_ALLOC_CHAIN {
            if block < 2 || block as u32 - 2 >= self.mdb.num_alloc_blocks as u32 {
                return Err(FilesystemError::InvalidData(format!(
                    "MFS chain references out-of-range alloc block {block}"
                )));
            }
            let off = self.partition_offset + self.alloc_block_offset(block);
            self.reader.seek(SeekFrom::Start(off))?;
            let want = (logical_len as usize).saturating_sub(data.len()).min(bs);
            let mut chunk = vec![0u8; bs];
            self.reader.read_exact(&mut chunk)?;
            data.extend_from_slice(&chunk[..want]);
            if data.len() >= logical_len as usize {
                break;
            }
            let next = self.map_get(block);
            if next == 1 {
                // End-of-chain. Data may be shorter than logical_len if the
                // catalog is inconsistent; truncate to what we have.
                break;
            }
            if next == 0 {
                return Err(FilesystemError::InvalidData(format!(
                    "MFS chain hits a free block at {block}"
                )));
            }
            block = next;
        }
        Ok(data)
    }

    /// Read the resource fork of a directory entry. Returns an empty `Vec`
    /// if the file has no resource fork. Surfaced as a side channel
    /// because the trait's `read_file` only exposes the data fork; classic
    /// Mac apps often live in the resource fork and consumers (e.g. the
    /// `mac_archive` exporter) need access.
    pub fn read_resource_fork(&mut self, entry: &FileEntry) -> Result<Vec<u8>, FilesystemError> {
        let fnum = entry.location as u32;
        let de = self
            .entry_by_file_number(fnum)
            .ok_or_else(|| FilesystemError::NotFound(format!("file number {fnum} not found")))?
            .clone();
        self.read_chain(de.rsrc_first_block, de.rsrc_logical_length)
    }
}

/// Parse every used entry out of one 512-byte directory sector. Stops at
/// the first unused entry (per spec, an unused entry terminates the
/// current sector's entry list).
fn parse_dir_sector(sec: &[u8; 512], out: &mut Vec<MfsDirEntry>) {
    let mut off = 0usize;
    while off + 50 < sec.len() {
        let flags = sec[off];
        if flags & 0x80 == 0 {
            // Unused entry — terminates the sector per spec.
            break;
        }
        let mut finder_info = [0u8; 16];
        finder_info.copy_from_slice(&sec[off + 2..off + 18]);
        let file_number = BigEndian::read_u32(&sec[off + 18..off + 22]);
        let data_first_block = BigEndian::read_u16(&sec[off + 22..off + 24]);
        let data_logical_length = BigEndian::read_u32(&sec[off + 24..off + 28]);
        let _data_phys_length = BigEndian::read_u32(&sec[off + 28..off + 32]);
        let rsrc_first_block = BigEndian::read_u16(&sec[off + 32..off + 34]);
        let rsrc_logical_length = BigEndian::read_u32(&sec[off + 34..off + 38]);
        let _rsrc_phys_length = BigEndian::read_u32(&sec[off + 38..off + 42]);
        let create_date = BigEndian::read_u32(&sec[off + 42..off + 46]);
        let modify_date = BigEndian::read_u32(&sec[off + 46..off + 50]);
        let name_len = sec[off + 50] as usize;
        if off + 51 + name_len > sec.len() {
            // Truncated entry — stop here.
            break;
        }
        let name = crate::hfs::mac_roman_to_utf8(&sec[off + 51..off + 51 + name_len]);

        out.push(MfsDirEntry {
            flags,
            finder_info,
            file_number,
            data_first_block,
            data_logical_length,
            rsrc_first_block,
            rsrc_logical_length,
            create_date,
            modify_date,
            name,
        });

        // Advance past header + name (Pascal byte + chars) padded to even.
        let entry_len = 51 + name_len;
        let padded = entry_len + (entry_len & 1);
        off += padded;
    }
}

/// Maximum length of an MFS filename in bytes (Mac Roman). The on-disk
/// field is a 28-byte Pascal string, so 1 length byte + up to 27 chars.
pub const MFS_MAX_NAME_LEN: usize = 27;

/// MFS name equality as the File Manager sees it: Mac Roman bytes compared
/// through the HFS case-folding order, so "Doc" and "DOC" are the same file.
fn mfs_names_equal(a: &str, b: &str) -> bool {
    let a_bytes = crate::hfs::utf8_to_mac_roman(a).unwrap_or_else(|_| a.as_bytes().to_vec());
    let b_bytes = crate::hfs::utf8_to_mac_roman(b).unwrap_or_else(|_| b.as_bytes().to_vec());
    crate::hfs_common::compare_hfs_keys(0, &a_bytes, 0, &b_bytes) == std::cmp::Ordering::Equal
}

/// Validate a candidate filename for `create_file` / `set_type_creator`.
/// MFS uses Mac Roman encoding and disallows the path-separator ':' (a
/// Classic Mac OS convention also enforced by HFS).
fn validate_mfs_name(name: &str) -> Result<Vec<u8>, FilesystemError> {
    if name.is_empty() {
        return Err(FilesystemError::InvalidData("MFS filename is empty".into()));
    }
    if name.contains(':') {
        return Err(FilesystemError::InvalidData(
            "MFS filename contains ':' (Mac path separator) — use '-' or '_'".into(),
        ));
    }
    let bytes = crate::hfs::utf8_to_mac_roman(name).map_err(|_| {
        FilesystemError::InvalidData(
            "MFS filename contains characters not representable in Mac Roman".into(),
        )
    })?;
    if bytes.len() > MFS_MAX_NAME_LEN {
        return Err(FilesystemError::InvalidData(format!(
            "MFS filename is {} bytes; max is {MFS_MAX_NAME_LEN}",
            bytes.len()
        )));
    }
    Ok(bytes)
}

impl MfsDirEntry {
    /// Serialize a single directory entry into a fresh `Vec<u8>` padded to
    /// even length (the on-disk constraint — entries align to even byte
    /// offsets within a directory sector). Caller stamps the result into
    /// the sector buffer.
    fn encode(&self, alloc_block_size: u32) -> Vec<u8> {
        // flPyLen / flRPyLen are the allocated sizes: whole allocation blocks.
        let physical = |logical: u32| -> u32 {
            if logical == 0 || alloc_block_size == 0 {
                0
            } else {
                logical
                    .div_ceil(alloc_block_size)
                    .saturating_mul(alloc_block_size)
            }
        };
        let name_bytes = crate::hfs::utf8_to_mac_roman(&self.name).unwrap_or_default();
        let name_len = name_bytes.len().min(MFS_MAX_NAME_LEN) as u8;
        let total = 51 + name_len as usize;
        let padded = total + (total & 1);
        let mut buf = vec![0u8; padded];
        buf[0] = self.flags;
        // byte 1 = version (=0); already zeroed
        buf[2..18].copy_from_slice(&self.finder_info);
        BigEndian::write_u32(&mut buf[18..22], self.file_number);
        BigEndian::write_u16(&mut buf[22..24], self.data_first_block);
        BigEndian::write_u32(&mut buf[24..28], self.data_logical_length);
        BigEndian::write_u32(&mut buf[28..32], physical(self.data_logical_length));
        BigEndian::write_u16(&mut buf[32..34], self.rsrc_first_block);
        BigEndian::write_u32(&mut buf[34..38], self.rsrc_logical_length);
        BigEndian::write_u32(&mut buf[38..42], physical(self.rsrc_logical_length));
        BigEndian::write_u32(&mut buf[42..46], self.create_date);
        BigEndian::write_u32(&mut buf[46..50], self.modify_date);
        buf[50] = name_len;
        buf[51..51 + name_len as usize].copy_from_slice(&name_bytes[..name_len as usize]);
        buf
    }
}

impl<R: Read + Write + Seek + Send> MfsFilesystem<R> {
    // --- low-level block-map editing ---------------------------------------

    /// Set a 12-bit volume-map entry to `value`. Mirrors `map_get`'s
    /// high-nibble-first packing. Panics on out-of-range `block`.
    fn map_set(&mut self, block: u16, value: u16) {
        debug_assert!(
            block as u32 >= 2 && (block as u32) < self.mdb.num_alloc_blocks as u32 + 2,
            "map_set out-of-range block {block}"
        );
        let value = value & 0x0FFF;
        // Entry for block N is at bit (N - 2) * 12 (index 0 == block 2).
        let bit_off = (block as usize - 2) * 12;
        let byte_off = bit_off / 8;
        if block.is_multiple_of(2) {
            self.map_bytes[byte_off] = (value >> 4) as u8;
            self.map_bytes[byte_off + 1] =
                (self.map_bytes[byte_off + 1] & 0x0F) | (((value & 0x0F) as u8) << 4);
        } else {
            self.map_bytes[byte_off] =
                (self.map_bytes[byte_off] & 0xF0) | ((value >> 8) as u8 & 0x0F);
            self.map_bytes[byte_off + 1] = (value & 0xFF) as u8;
        }
    }

    /// Find `count` free allocation blocks, link them into a chain
    /// (block_i -> block_{i+1}, last block -> 1 = end-of-chain), and
    /// return the first block number. Bumps `mdb.free_blocks` down.
    fn alloc_chain(&mut self, count: u32) -> Result<u16, FilesystemError> {
        if count == 0 {
            return Ok(0);
        }
        if (count as u16) > self.mdb.free_blocks {
            return Err(FilesystemError::InvalidData(format!(
                "out of space: need {count} alloc blocks, have {} free",
                self.mdb.free_blocks
            )));
        }
        // First pass: gather the indices of `count` free blocks.
        let mut picked = Vec::with_capacity(count as usize);
        // Allocation blocks are numbered starting at 2 (blocks 0 and 1
        // reserved by the spec). num_alloc_blocks counts the
        // user-addressable blocks, so valid range is 2 ..= num_alloc_blocks + 1.
        for b in 2..(self.mdb.num_alloc_blocks as u32 + 2) {
            if self.map_get(b as u16) == 0 {
                picked.push(b as u16);
                if picked.len() == count as usize {
                    break;
                }
            }
        }
        if picked.len() < count as usize {
            return Err(FilesystemError::InvalidData(format!(
                "fragmentation: {} free per MDB but only {} blocks found in map",
                self.mdb.free_blocks,
                picked.len()
            )));
        }
        // Second pass: link them.
        for w in picked.windows(2) {
            let cur = w[0];
            let nxt = w[1];
            self.map_set(cur, nxt);
        }
        // Last block: end-of-chain marker (1).
        let last = *picked.last().expect("picked non-empty");
        self.map_set(last, 1);
        self.mdb.free_blocks -= count as u16;
        Ok(picked[0])
    }

    /// Walk an allocation-block chain starting at `first` and mark every
    /// block free (map entry = 0). Bumps `mdb.free_blocks` up by the
    /// number of blocks released.
    fn free_chain(&mut self, first: u16) -> Result<(), FilesystemError> {
        if first == 0 {
            return Ok(());
        }
        let mut block = first;
        let mut visited = std::collections::HashSet::new();
        for _hop in 0..MAX_ALLOC_CHAIN {
            if block < 2 || block as u32 - 2 >= self.mdb.num_alloc_blocks as u32 {
                return Err(FilesystemError::InvalidData(format!(
                    "free_chain hit out-of-range block {block}"
                )));
            }
            if !visited.insert(block) {
                return Err(FilesystemError::InvalidData(format!(
                    "free_chain cycle at block {block}"
                )));
            }
            let next = self.map_get(block);
            self.map_set(block, 0);
            self.mdb.free_blocks += 1;
            if next == 1 || next == 0 {
                return Ok(());
            }
            block = next;
        }
        Err(FilesystemError::InvalidData(
            "free_chain ran past MAX_ALLOC_CHAIN".into(),
        ))
    }

    /// Allocate an allocation-block chain for `bytes` and write it, returning
    /// `(first_block, logical_len)`. An empty fork allocates nothing and returns
    /// `(0, 0)`. Shared by `create_file` (both forks) and `write_resource_fork`.
    fn alloc_and_write_fork(&mut self, bytes: &[u8]) -> Result<(u16, u32), FilesystemError> {
        let bs = self.mdb.alloc_block_size as usize;
        let count = if bytes.is_empty() {
            0
        } else {
            bytes.len().div_ceil(bs) as u32
        };
        let first = self.alloc_chain(count)?;
        if first != 0 {
            self.write_data_chain(first, bytes)?;
        }
        Ok((first, bytes.len() as u32))
    }

    /// Write `data` across the allocation-block chain starting at `first`.
    /// The chain must have been pre-allocated by `alloc_chain`. Each block
    /// holds `mdb.alloc_block_size` bytes; the last block is zero-padded
    /// to its full size.
    fn write_data_chain(&mut self, first: u16, data: &[u8]) -> Result<(), FilesystemError> {
        if first == 0 || data.is_empty() {
            return Ok(());
        }
        let bs = self.mdb.alloc_block_size as usize;
        let mut written = 0usize;
        let mut block = first;
        for _hop in 0..MAX_ALLOC_CHAIN {
            let chunk_off = written;
            let chunk_end = (written + bs).min(data.len());
            let abs = self.partition_offset + self.alloc_block_offset(block);
            self.reader.seek(SeekFrom::Start(abs))?;
            let chunk = &data[chunk_off..chunk_end];
            self.reader.write_all(chunk)?;
            // Zero-pad the rest of the block.
            if chunk.len() < bs {
                let pad = vec![0u8; bs - chunk.len()];
                self.reader.write_all(&pad)?;
            }
            written = chunk_end;
            if written >= data.len() {
                return Ok(());
            }
            let next = self.map_get(block);
            if next == 1 || next == 0 {
                if written < data.len() {
                    return Err(FilesystemError::InvalidData(format!(
                        "write_data_chain short-chained: {} bytes unwritten",
                        data.len() - written
                    )));
                }
                return Ok(());
            }
            block = next;
        }
        Err(FilesystemError::InvalidData(
            "write_data_chain ran past MAX_ALLOC_CHAIN".into(),
        ))
    }

    // --- on-disk write-back -----------------------------------------------

    /// Re-encode the in-memory `entries` Vec into the directory sectors
    /// and write them out. Used by `sync_metadata`.
    fn dir_write_back(&mut self) -> Result<(), FilesystemError> {
        let sector_count = self.mdb.dir_length_sectors as usize;
        let mut packed = vec![vec![0u8; 512]; sector_count];
        let mut sector_idx = 0usize;
        let mut byte_off = 0usize;
        for e in self.entries.iter().filter(|e| e.is_in_use()) {
            let bytes = e.encode(self.mdb.alloc_block_size);
            // If this entry doesn't fit in the remainder of the current
            // sector (after leaving 1 byte for the terminator), advance.
            if byte_off + bytes.len() + 1 > 512 {
                sector_idx += 1;
                byte_off = 0;
                if sector_idx >= sector_count {
                    return Err(FilesystemError::InvalidData(format!(
                        "directory full: {} sectors of {sector_count} can't hold {} entries",
                        sector_count,
                        self.entries.iter().filter(|e| e.is_in_use()).count()
                    )));
                }
            }
            packed[sector_idx][byte_off..byte_off + bytes.len()].copy_from_slice(&bytes);
            byte_off += bytes.len();
        }
        for (i, sec) in packed.into_iter().enumerate() {
            let sector_no = self.mdb.dir_start_sector as u64 + i as u64;
            let off = self.partition_offset + sector_no * 512;
            self.reader.seek(SeekFrom::Start(off))?;
            self.reader.write_all(&sec)?;
        }
        Ok(())
    }

    /// Serialize MDB fields back into a 512-byte buffer and write.
    fn mdb_write_back(&mut self) -> Result<(), FilesystemError> {
        // Re-read the original MDB sector to preserve any spare bytes we
        // don't model (e.g. the post-volume-name volume-map area, which
        // we write separately via `map_write_back`).
        self.reader
            .seek(SeekFrom::Start(self.partition_offset + MDB_OFFSET))?;
        let mut buf = [0u8; 512];
        self.reader.read_exact(&mut buf)?;
        // Re-stamp the fields we own.
        BigEndian::write_u16(&mut buf[0..2], MFS_SIGNATURE);
        BigEndian::write_u32(&mut buf[2..6], self.mdb.create_date);
        BigEndian::write_u32(&mut buf[6..10], self.mdb.last_backup_date);
        BigEndian::write_u16(&mut buf[10..12], self.mdb.volume_attributes);
        BigEndian::write_u16(&mut buf[12..14], self.mdb.num_files);
        BigEndian::write_u16(&mut buf[14..16], self.mdb.dir_start_sector);
        BigEndian::write_u16(&mut buf[16..18], self.mdb.dir_length_sectors);
        BigEndian::write_u16(&mut buf[18..20], self.mdb.num_alloc_blocks);
        BigEndian::write_u32(&mut buf[20..24], self.mdb.alloc_block_size);
        BigEndian::write_u32(&mut buf[24..28], self.mdb.clump_size);
        BigEndian::write_u16(&mut buf[28..30], self.mdb.first_alloc_block_sector);
        BigEndian::write_u32(&mut buf[30..34], self.mdb.next_file_number);
        BigEndian::write_u16(&mut buf[34..36], self.mdb.free_blocks);
        let name_bytes = crate::hfs::utf8_to_mac_roman(&self.mdb.volume_name).unwrap_or_default();
        let name_len = name_bytes.len().min(MFS_MAX_NAME_LEN);
        buf[36] = name_len as u8;
        // Zero the old name area before stamping the new one.
        for b in buf[37..37 + MFS_MAX_NAME_LEN].iter_mut() {
            *b = 0;
        }
        buf[37..37 + name_len].copy_from_slice(&name_bytes[..name_len]);
        self.reader
            .seek(SeekFrom::Start(self.partition_offset + MDB_OFFSET))?;
        self.reader.write_all(&buf)?;
        Ok(())
    }

    /// Write the in-memory `map_bytes` back to its on-disk position
    /// (right after the volume name Pascal string within the MDB sector,
    /// possibly straddling subsequent sectors).
    fn map_write_back(&mut self) -> Result<(), FilesystemError> {
        self.reader
            .seek(SeekFrom::Start(self.partition_offset + self.mdb.map_offset))?;
        let bytes = self.map_bytes.clone();
        self.reader.write_all(&bytes)?;
        Ok(())
    }
}
// ---------------------------------------------------------------------------
// fsck (check) — allocation-map-vs-directory reconciliation
// ---------------------------------------------------------------------------

/// Outcome of recomputing the allocated-block set from the directory. `used`
/// is indexed by allocation-block number (valid entries live at 2..=num_alloc
/// blocks + 1); `broken` lists structural faults (loop, out-of-range link,
/// link into a free block, cross-link) that make the walk incomplete — while
/// it is non-empty a map rewrite is unsafe.
struct MfsWalk {
    used: Vec<bool>,
    files: u32,
    broken: Vec<String>,
}

impl<R: Read + Seek + Send> MfsFilesystem<R> {
    /// Highest addressable allocation block (blocks are numbered from 2).
    fn last_block(&self) -> u16 {
        self.mdb.num_alloc_blocks + 1
    }

    /// Walk one fork's allocation-block chain, marking every block it visits in
    /// `used`. `owner` names the file for diagnostics. Structural faults are
    /// pushed to `broken` (the walk of that fork stops at the fault).
    fn walk_fork(
        &self,
        first: u16,
        owner: &str,
        fork: &str,
        used: &mut [bool],
        broken: &mut Vec<String>,
    ) {
        if first == 0 {
            return;
        }
        let last = self.last_block();
        let mut block = first;
        for _ in 0..MAX_ALLOC_CHAIN {
            if block < 2 || block > last {
                broken.push(format!(
                    "file '{owner}' {fork} fork links to block {block}, outside the volume (2..={last})"
                ));
                return;
            }
            if used[block as usize] {
                broken.push(format!(
                    "block {block} is cross-linked (claimed by '{owner}' {fork} fork and another chain)"
                ));
                return;
            }
            used[block as usize] = true;
            let next = self.map_get(block);
            if next == 1 {
                return; // end-of-chain
            }
            if next == 0 {
                broken.push(format!(
                    "file '{owner}' {fork} fork chain hits a free block after {block}"
                ));
                return;
            }
            block = next;
        }
        broken.push(format!(
            "file '{owner}' {fork} fork chain exceeds {MAX_ALLOC_CHAIN} blocks (runaway)"
        ));
    }

    /// Recompute the allocated-block set from every in-use directory entry's
    /// data + resource fork chain (the CBM/Atari VALIDATE model applied to the
    /// MFS volume-allocation map).
    fn compute_used(&self) -> MfsWalk {
        let mut used = vec![false; self.last_block() as usize + 1];
        let mut broken = Vec::new();
        let mut files = 0u32;
        let entries: Vec<MfsDirEntry> = self
            .entries
            .iter()
            .filter(|e| e.is_in_use())
            .cloned()
            .collect();
        for de in &entries {
            files += 1;
            self.walk_fork(
                de.data_first_block,
                &de.name,
                "data",
                &mut used,
                &mut broken,
            );
            self.walk_fork(
                de.rsrc_first_block,
                &de.name,
                "resource",
                &mut used,
                &mut broken,
            );
        }
        MfsWalk {
            used,
            files,
            broken,
        }
    }

    /// Count allocation blocks currently marked free in the on-disk map.
    fn map_free_count(&self) -> u32 {
        (2..=self.last_block())
            .filter(|&b| self.map_get(b) == 0)
            .count() as u32
    }

    /// MFS integrity check: reconcile the volume allocation-block map, the free
    /// count, and the file count against the directory walk. Repair (freeing
    /// unreachable blocks + fixing the counters) is offered only when the walk
    /// completed without structural damage.
    fn run_fsck(&mut self) -> Result<FsckResult, FilesystemError> {
        let walk = self.compute_used();
        let walk_clean = walk.broken.is_empty();
        let last = self.last_block();

        // Leaked blocks: marked allocated (map entry non-zero) but unreachable
        // from any file's fork chain.
        let mut leaked = 0u32;
        for b in 2..=last {
            if self.map_get(b) != 0 && !walk.used[b as usize] {
                leaked += 1;
            }
        }

        let mut errors = Vec::new();
        for msg in &walk.broken {
            errors.push(FsckIssue {
                code: "MfsBrokenChain".into(),
                message: msg.clone(),
                repairable: false,
                debug: false,
            });
        }
        if leaked > 0 {
            errors.push(FsckIssue {
                code: "MfsLostBlocks".into(),
                message: format!(
                    "{leaked} allocation block(s) marked used but unreachable from any file"
                ),
                repairable: walk_clean,
                debug: false,
            });
        }

        // Free-count reconciliation. The recomputed free count treats leaked
        // blocks as free (they will be after a repair); the on-disk drFreeBks
        // should match the *current* map, which counts them as allocated.
        let map_free = self.map_free_count();
        if self.mdb.free_blocks as u32 != map_free {
            errors.push(FsckIssue {
                code: "MfsFreeCountMismatch".into(),
                message: format!(
                    "MDB free-block count is {} but the allocation map has {map_free} free",
                    self.mdb.free_blocks
                ),
                repairable: walk_clean,
                debug: false,
            });
        }

        // File-count reconciliation.
        if self.mdb.num_files as u32 != walk.files {
            errors.push(FsckIssue {
                code: "MfsFileCountMismatch".into(),
                message: format!(
                    "MDB file count is {} but the directory holds {} file(s)",
                    self.mdb.num_files, walk.files
                ),
                repairable: walk_clean,
                debug: false,
            });
        }

        let repairable = errors.iter().any(|e| e.repairable);
        let free_after = map_free + leaked; // free once leaked blocks are reclaimed
        Ok(FsckResult {
            errors,
            warnings: Vec::new(),
            stats: FsckStats {
                files_checked: walk.files,
                directories_checked: 1,
                extra: vec![
                    (
                        "free blocks".into(),
                        format!("{free_after} / {}", self.mdb.num_alloc_blocks),
                    ),
                    (
                        "allocation map".into(),
                        if leaked == 0 && walk_clean {
                            "consistent".into()
                        } else {
                            "needs rebuild".into()
                        },
                    ),
                ],
            },
            repairable,
            orphaned_entries: Vec::new(),
        })
    }
}

// ---------------------------------------------------------------------------
// fsck (repair) — reclaim leaked blocks + resync the MDB counters
// ---------------------------------------------------------------------------

impl<R: Read + Write + Seek + Send> MfsFilesystem<R> {
    /// Repair the volume allocation map + MDB counters. Leaked (allocated but
    /// unreachable) blocks are freed; the free-block and file counts are reset
    /// to match the directory. Withheld entirely when the walk found structural
    /// damage — the MFS map encodes each file's chain linkage, so a broken
    /// chain could hide live blocks and rewriting would risk data loss.
    fn run_repair(&mut self) -> Result<RepairReport, FilesystemError> {
        let walk = self.compute_used();
        if !walk.broken.is_empty() {
            return Ok(RepairReport {
                fixes_applied: Vec::new(),
                fixes_failed: vec![
                    "structural damage (broken/cross-linked chain) — the allocation map was left \
                     unchanged to avoid losing live blocks"
                        .into(),
                ],
                unrepairable_count: walk.broken.len(),
            });
        }

        let last = self.last_block();
        let mut freed = 0u32;
        for b in 2..=last {
            if self.map_get(b) != 0 && !walk.used[b as usize] {
                self.map_set(b, 0);
                freed += 1;
            }
        }

        let map_free = self.map_free_count();
        let mut fixes = Vec::new();
        if freed > 0 {
            fixes.push(format!(
                "reclaimed {freed} unreachable allocation block(s) into the free map"
            ));
        }
        if self.mdb.free_blocks as u32 != map_free {
            fixes.push(format!("corrected the MDB free-block count to {map_free}"));
            self.mdb.free_blocks = map_free as u16;
        }
        if self.mdb.num_files as u32 != walk.files {
            fixes.push(format!("corrected the MDB file count to {}", walk.files));
            self.mdb.num_files = walk.files as u16;
        }

        if fixes.is_empty() {
            return Ok(RepairReport {
                fixes_applied: Vec::new(),
                fixes_failed: Vec::new(),
                unrepairable_count: 0,
            });
        }

        self.map_write_back()?;
        self.mdb_write_back()?;
        self.reader.flush()?;
        Ok(RepairReport {
            fixes_applied: fixes,
            fixes_failed: Vec::new(),
            unrepairable_count: 0,
        })
    }
}

impl<R: Read + Seek + Send> Filesystem for MfsFilesystem<R> {
    fn root(&mut self) -> Result<FileEntry, FilesystemError> {
        Ok(FileEntry::new_directory("/".into(), "/".into(), 0))
    }

    fn list_directory(&mut self, entry: &FileEntry) -> Result<Vec<FileEntry>, FilesystemError> {
        if entry.path != "/" {
            // MFS is a flat filesystem — only the root has children.
            return Ok(Vec::new());
        }
        let mut out = Vec::with_capacity(self.entries.len());
        for de in &self.entries {
            if !de.is_in_use() {
                continue;
            }
            let path = format!("/{}", de.name);
            let mut fe = FileEntry::new_file(
                de.name.clone(),
                path,
                de.data_logical_length as u64,
                de.file_number as u64,
            );
            fe.type_code = Some(de.finder_info[0..4].try_into().unwrap());
            fe.creator_code = Some(de.finder_info[4..8].try_into().unwrap());
            fe.finder_flags = Some(de.finder_flags());
            if de.rsrc_logical_length > 0 {
                fe.resource_fork_size = Some(de.rsrc_logical_length as u64);
            }
            // MFS dates share HFS's Mac-epoch encoding.
            fe.modified_unix = disk_core::times::mac_local_to_unix(de.modify_date);
            if de.modify_date != 0 || de.create_date != 0 {
                fe.mac_dates = Some((de.create_date, de.modify_date, 0));
                if let Some(s) = crate::hfs_common::format_mac_date(de.modify_date) {
                    fe.modified = Some(s);
                }
            }
            out.push(fe);
        }
        out.sort_by_key(|a| a.name.to_lowercase());
        Ok(out)
    }

    fn read_file(
        &mut self,
        entry: &FileEntry,
        max_bytes: usize,
    ) -> Result<Vec<u8>, FilesystemError> {
        let fnum = entry.location as u32;
        let de = self
            .entry_by_file_number(fnum)
            .ok_or_else(|| FilesystemError::NotFound(format!("file number {fnum} not found")))?
            .clone();
        let mut data = self.read_chain(de.data_first_block, de.data_logical_length)?;
        data.truncate(max_bytes);
        Ok(data)
    }

    fn validate_name(&self, name: &str) -> Result<(), FilesystemError> {
        validate_mfs_name(name).map(|_| ())
    }
    fn fs_type(&self) -> &str {
        "MFS"
    }

    fn volume_label(&self) -> Option<&str> {
        if self.mdb.volume_name.is_empty() {
            None
        } else {
            Some(&self.mdb.volume_name)
        }
    }

    fn total_size(&self) -> u64 {
        self.mdb.num_alloc_blocks as u64 * self.mdb.alloc_block_size as u64
    }

    fn used_size(&self) -> u64 {
        (self.mdb.num_alloc_blocks - self.mdb.free_blocks) as u64 * self.mdb.alloc_block_size as u64
    }

    /// MFS allocates fork storage in fixed-size allocation blocks
    /// (`drAlBlkSiz`), so a fork's real on-disk footprint is its length
    /// rounded up to this unit. Exposing it lets the copy preflight and
    /// `du` model destination consumption exactly instead of falling back
    /// to a 512-byte floor.
    fn allocation_unit(&self) -> Option<u64> {
        if self.mdb.alloc_block_size == 0 {
            None
        } else {
            Some(self.mdb.alloc_block_size as u64)
        }
    }

    /// Stream a file's resource fork. MFS files carry a data + resource fork
    /// like HFS; consumers (`get-binhex`, MacBinary / AppleDouble export, `cp`,
    /// the remote daemon) reach it only through this trait method, so it must
    /// bridge to the inherent [`read_resource_fork`](Self::read_resource_fork)
    /// (which follows the resource fork's own allocation-block chain).
    fn write_resource_fork_to(
        &mut self,
        entry: &FileEntry,
        writer: &mut dyn std::io::Write,
    ) -> Result<u64, FilesystemError> {
        let data = self.read_resource_fork(entry)?;
        writer.write_all(&data)?;
        Ok(data.len() as u64)
    }

    fn resource_fork_size(&mut self, entry: &FileEntry) -> u64 {
        self.entry_by_file_number(entry.location as u32)
            .map(|de| de.rsrc_logical_length as u64)
            .unwrap_or(0)
    }

    fn fsck(&mut self) -> Option<Result<FsckResult, FilesystemError>> {
        Some(self.run_fsck())
    }
}

impl<R: Read + Write + Seek + Send> EditableFilesystem for MfsFilesystem<R> {
    fn as_filesystem(&self) -> &dyn disk_core::filesystem::Filesystem {
        self
    }
    fn as_filesystem_mut(&mut self) -> &mut dyn disk_core::filesystem::Filesystem {
        self
    }
    fn create_file(
        &mut self,
        parent: &FileEntry,
        name: &str,
        data: &mut dyn std::io::Read,
        data_len: u64,
        options: &CreateFileOptions,
    ) -> Result<FileEntry, FilesystemError> {
        if parent.path != "/" {
            return Err(FilesystemError::Unsupported(
                "MFS is flat; only the root directory accepts new files".into(),
            ));
        }
        let _ = validate_mfs_name(name)?;
        // Reject duplicates; the File Manager compares names without case.
        if self
            .entries
            .iter()
            .any(|e| e.is_in_use() && mfs_names_equal(&e.name, name))
        {
            return Err(FilesystemError::InvalidData(format!(
                "MFS file '{name}' already exists"
            )));
        }
        if data_len > u32::MAX as u64 {
            return Err(FilesystemError::InvalidData(
                "MFS file size capped at u32::MAX bytes".into(),
            ));
        }
        // Read all data into memory. MFS volumes top out at 800 KB so
        // this is fine.
        let mut bytes = Vec::with_capacity(data_len as usize);
        data.read_to_end(&mut bytes)?;
        if bytes.len() as u64 != data_len {
            return Err(FilesystemError::InvalidData(format!(
                "data_len {data_len} != actual {} bytes",
                bytes.len()
            )));
        }
        let (first_block, _) = self.alloc_and_write_fork(&bytes)?;

        // Resource fork from CreateFileOptions, if the caller supplied one
        // (put-binhex / put-macbinary / fork-carrying cp). Roll the data
        // allocation back if the resource fork can't fit, so a failed create
        // leaks nothing.
        let rsrc_bytes: Vec<u8> = match &options.resource_fork {
            Some(disk_core::filesystem::ResourceForkSource::Data(d)) => d.clone(),
            Some(disk_core::filesystem::ResourceForkSource::File(p)) => {
                std::fs::read(p).map_err(FilesystemError::Io)?
            }
            None => Vec::new(),
        };
        let (rsrc_first_block, rsrc_logical_length) = match self.alloc_and_write_fork(&rsrc_bytes) {
            Ok(v) => v,
            Err(e) => {
                let _ = self.free_chain(first_block);
                return Err(e);
            }
        };

        let file_number = self.mdb.next_file_number;
        self.mdb.next_file_number += 1;
        self.mdb.num_files += 1;

        // Honor the caller's Mac type/creator, filling any missing or blank half
        // from the extension dictionary. Written into the dir entry's Finder
        // info so the codes actually persist on disk (and the returned entry
        // matches).
        let (type_code, creator_code) = crate::hfs_common::resolve_create_type_creator(
            name,
            options.os_type,
            options.os_creator,
            options.type_code.as_deref(),
            options.creator_code.as_deref(),
        );
        let mut finder_info = [0u8; 16];
        finder_info[0..4].copy_from_slice(&type_code);
        finder_info[4..8].copy_from_slice(&creator_code);

        // Cross-fs import passes the source mtime through options.unix_times;
        // a genuinely new file leaves it None and we stamp `now`. MFS's dir
        // entry carries create + modify dates in Mac-epoch seconds — the same
        // encoding HFS/HFS+ use.
        let mtime_secs = options
            .unix_times
            .map(|t| t.mtime_or_now())
            .unwrap_or_else(disk_core::times::now);
        let stamp = disk_core::times::unix_to_mac_local(mtime_secs);
        let entry = MfsDirEntry {
            flags: 0x80, // in use, not locked
            finder_info,
            file_number,
            data_first_block: first_block,
            data_logical_length: bytes.len() as u32,
            rsrc_first_block,
            rsrc_logical_length,
            create_date: stamp,
            modify_date: stamp,
            name: name.to_string(),
        };
        self.entries.push(entry);
        // Surface a freshly-built FileEntry for the caller, reflecting the
        // type/creator actually written.
        let mut fe = FileEntry::new_file(
            name.to_string(),
            format!("/{name}"),
            bytes.len() as u64,
            file_number as u64,
        );
        fe.type_code = Some(type_code);
        fe.creator_code = Some(creator_code);
        if rsrc_logical_length > 0 {
            fe.resource_fork_size = Some(rsrc_logical_length as u64);
        }
        fe.modified_unix = Some(mtime_secs);
        fe.mac_dates = Some((stamp, stamp, 0));
        Ok(fe)
    }

    fn create_directory(
        &mut self,
        _parent: &FileEntry,
        _name: &str,
        _options: &CreateDirectoryOptions,
    ) -> Result<FileEntry, FilesystemError> {
        Err(FilesystemError::Unsupported(
            "MFS has no directory hierarchy — all files live in the volume root".into(),
        ))
    }

    fn delete_entry(
        &mut self,
        parent: &FileEntry,
        entry: &FileEntry,
    ) -> Result<(), FilesystemError> {
        if parent.path != "/" {
            return Err(FilesystemError::Unsupported(
                "MFS is flat; only files in the root are deletable".into(),
            ));
        }
        if entry.entry_type != EntryType::File {
            return Err(FilesystemError::InvalidData(
                "MFS only stores files; cannot delete a directory".into(),
            ));
        }
        let fnum = entry.location as u32;
        // Snapshot the chain heads before we touch the entries vec.
        let (data_head, rsrc_head) = {
            let de = self
                .entries
                .iter()
                .find(|e| e.is_in_use() && e.file_number == fnum)
                .ok_or_else(|| {
                    FilesystemError::NotFound(format!("file number {fnum} not in directory"))
                })?;
            (de.data_first_block, de.rsrc_first_block)
        };
        self.free_chain(data_head)?;
        self.free_chain(rsrc_head)?;
        // Remove the entry from the in-memory directory.
        self.entries
            .retain(|e| !(e.is_in_use() && e.file_number == fnum));
        self.mdb.num_files = self.mdb.num_files.saturating_sub(1);
        Ok(())
    }

    fn sync_metadata(&mut self) -> Result<(), FilesystemError> {
        self.dir_write_back()?;
        self.map_write_back()?;
        self.mdb_write_back()?;
        self.reader.flush()?;
        Ok(())
    }

    fn free_space(&mut self) -> Result<u64, FilesystemError> {
        Ok(self.mdb.free_blocks as u64 * self.mdb.alloc_block_size as u64)
    }

    fn repair(&mut self) -> Result<RepairReport, FilesystemError> {
        self.run_repair()
    }

    /// Replace a file's resource fork (used by `setrsrc`, the batch archive
    /// importer, and fork-carrying `cp`). Frees the old resource chain, then
    /// allocates + writes the new one and updates the directory entry. Call
    /// `sync_metadata` to persist. Freeing before allocating means a replacement
    /// only needs the *delta* in free space, not room for both copies.
    fn write_resource_fork(
        &mut self,
        entry: &FileEntry,
        data: &mut dyn std::io::Read,
        len: u64,
    ) -> Result<(), FilesystemError> {
        if len > u32::MAX as u64 {
            return Err(FilesystemError::InvalidData(
                "MFS resource fork capped at u32::MAX bytes".into(),
            ));
        }
        let fnum = entry.location as u32;
        let old_head = self
            .entries
            .iter()
            .find(|e| e.is_in_use() && e.file_number == fnum)
            .map(|e| e.rsrc_first_block)
            .ok_or_else(|| {
                FilesystemError::NotFound(format!("file number {fnum} not in directory"))
            })?;
        let mut bytes = Vec::with_capacity(len as usize);
        data.read_to_end(&mut bytes)?;
        self.free_chain(old_head)?;
        let (first, rlen) = self.alloc_and_write_fork(&bytes)?;
        let de = self
            .entries
            .iter_mut()
            .find(|e| e.is_in_use() && e.file_number == fnum)
            .expect("entry present after lookup above");
        de.rsrc_first_block = first;
        de.rsrc_logical_length = rlen;
        Ok(())
    }

    fn set_type_creator(
        &mut self,
        entry: &FileEntry,
        type_code: &str,
        creator_code: &str,
    ) -> Result<(), FilesystemError> {
        if type_code.len() != 4 || creator_code.len() != 4 {
            return Err(FilesystemError::InvalidData(
                "Mac OSType / creator must be exactly 4 chars".into(),
            ));
        }
        let fnum = entry.location as u32;
        let de = self
            .entries
            .iter_mut()
            .find(|e| e.is_in_use() && e.file_number == fnum)
            .ok_or_else(|| {
                FilesystemError::NotFound(format!("file number {fnum} not in directory"))
            })?;
        de.finder_info[0..4].copy_from_slice(type_code.as_bytes());
        de.finder_info[4..8].copy_from_slice(creator_code.as_bytes());
        Ok(())
    }

    fn rename(
        &mut self,
        parent: &FileEntry,
        entry: &FileEntry,
        new_name: &str,
    ) -> Result<(), FilesystemError> {
        if new_name == entry.name {
            return Ok(());
        }
        if parent.path != "/" {
            return Err(FilesystemError::Unsupported(
                "MFS is flat; only files in the root are renamable".into(),
            ));
        }
        if entry.entry_type != EntryType::File {
            return Err(FilesystemError::InvalidData(
                "MFS only stores files; cannot rename a directory".into(),
            ));
        }
        let _ = validate_mfs_name(new_name)?;

        let fnum = entry.location as u32;
        // Reject a collision with a *different* in-use entry; the File Manager
        // compares names without case, so "Doc" and "DOC" are one file.
        if self
            .entries
            .iter()
            .any(|e| e.is_in_use() && e.file_number != fnum && mfs_names_equal(&e.name, new_name))
        {
            return Err(FilesystemError::AlreadyExists(new_name.to_string()));
        }

        // Overwrite only the name; flags, Finder info, file number, fork heads,
        // lengths and dates are untouched, so the file keeps its identity and
        // contents. Persistence happens via sync_metadata -> dir_write_back.
        let de = self
            .entries
            .iter_mut()
            .find(|e| e.is_in_use() && e.file_number == fnum)
            .ok_or_else(|| {
                FilesystemError::NotFound(format!("file number {fnum} not in directory"))
            })?;
        de.name = new_name.to_string();
        Ok(())
    }
}

// ---------------------------------------------------------------------------
// create-blank formatter
// ---------------------------------------------------------------------------

/// Geometry of a freshly formatted MFS volume, in 512-byte logical sectors.
struct MfsBlankGeom {
    total_sectors: u64,
    alloc_block_size: u32,
    num_alloc_blocks: u16,
    dir_start_sector: u16,
    dir_length_sectors: u16,
    first_alloc_block_sector: u16,
}

/// Directory length (in 512-byte sectors) for a blank volume. 12 sectors — the
/// canonical 400 KB MFS directory — is the floor; larger volumes get more so a
/// full floppy's file count isn't artificially capped. The on-disk `drDirLen`
/// field is a u16 count of sectors, so 255 is a comfortable ceiling.
fn blank_dir_sectors(num_alloc_blocks: u32) -> u64 {
    (num_alloc_blocks as u64 / 40).clamp(12, 255)
}

/// Solve the reserved-region layout for a blank MFS volume of `size_bytes`.
///
/// MFS packs one 12-bit allocation-map entry per block, so at most 4094 blocks
/// (0/1 reserved) are addressable; the allocation-block size is grown from
/// 1 KiB in 512-byte steps until the data region fits under that ceiling. The
/// reserved region is boot(2) + MDB/map + directory, solved to a fixed point
/// because the map length depends on the block count, which depends on where
/// the data region starts.
fn mfs_blank_geometry(size_bytes: u64) -> Result<MfsBlankGeom, FilesystemError> {
    const SECTOR: u64 = 512;
    if size_bytes < 32 * SECTOR {
        return Err(FilesystemError::InvalidData(
            "MFS volume must be at least 16 KiB".into(),
        ));
    }
    let total_sectors = size_bytes / SECTOR;

    // Grow the block size (in sectors-per-block) until the block count fits the
    // 12-bit map. spb 128 = 64 KiB blocks → ~256 MB, well past any real MFS.
    for spb in 2..=128u64 {
        let abs = spb * SECTOR;
        let mut first_ab: u64 = 16; // seed with the canonical 400 KB value
        let mut num_ab = 0u64;
        let mut dir_start = 4u64;
        let mut dir_len = 12u64;
        let mut converged = false;
        for _ in 0..16 {
            if total_sectors <= first_ab {
                break;
            }
            num_ab = (total_sectors - first_ab) / spb;
            let map_bytes = (num_ab * 12).div_ceil(8);
            // The MDB sits at sector 2; its allocation map begins 64 bytes in
            // and may straddle into following sectors.
            let mdb_map_sectors = (64 + map_bytes).div_ceil(SECTOR);
            dir_start = 2 + mdb_map_sectors;
            dir_len = blank_dir_sectors(num_ab as u32);
            let next_first = dir_start + dir_len;
            if next_first == first_ab {
                converged = true;
                break;
            }
            first_ab = next_first;
        }
        if !converged || num_ab == 0 {
            continue;
        }
        if num_ab > 4094 {
            continue; // too many blocks for the 12-bit map at this size — grow abs
        }
        return Ok(MfsBlankGeom {
            total_sectors,
            alloc_block_size: abs as u32,
            num_alloc_blocks: num_ab as u16,
            dir_start_sector: dir_start as u16,
            dir_length_sectors: dir_len as u16,
            first_alloc_block_sector: first_ab as u16,
        });
    }
    Err(FilesystemError::InvalidData(
        "MFS volume too large to format (max ~256 MB)".into(),
    ))
}

/// Format a blank MFS volume of `size_bytes` with volume name `name`.
///
/// Produces a bare MFS image: zeroed boot blocks (non-bootable data volume),
/// an MDB describing the geometry, an all-free allocation map, and an empty
/// file directory. The canonical 400 KB / 800 KB floppy sizes format cleanly,
/// as do larger sizes up to the 12-bit-map ceiling. The result round-trips
/// through [`MfsFilesystem::open`] and accepts files via `EditableFilesystem`.
pub fn create_blank_mfs(size_bytes: u64, name: &str) -> Result<Vec<u8>, FilesystemError> {
    let g = mfs_blank_geometry(size_bytes)?;
    let total_bytes = g.total_sectors * 512;
    let mut disk = vec![0u8; total_bytes as usize];

    // Clump size: 8 allocation blocks, capped at the data region so it stays
    // meaningful on tiny volumes. Cosmetic (the allocator works in blocks), but
    // real disks carry a sensible value here.
    let data_bytes = g.num_alloc_blocks as u32 * g.alloc_block_size;
    let clump = (g.alloc_block_size.saturating_mul(8)).min(data_bytes.max(g.alloc_block_size));

    let mdb = &mut disk[MDB_OFFSET as usize..MDB_OFFSET as usize + 512];
    BigEndian::write_u16(&mut mdb[0..2], MFS_SIGNATURE);
    // Create / last-backup dates left 0 (Mac epoch); real Mac OS restamps them.
    BigEndian::write_u16(&mut mdb[10..12], 0); // attributes
    BigEndian::write_u16(&mut mdb[12..14], 0); // num files
    BigEndian::write_u16(&mut mdb[14..16], g.dir_start_sector);
    BigEndian::write_u16(&mut mdb[16..18], g.dir_length_sectors);
    BigEndian::write_u16(&mut mdb[18..20], g.num_alloc_blocks);
    BigEndian::write_u32(&mut mdb[20..24], g.alloc_block_size);
    BigEndian::write_u32(&mut mdb[24..28], clump);
    BigEndian::write_u16(&mut mdb[28..30], g.first_alloc_block_sector);
    BigEndian::write_u32(&mut mdb[30..34], 1); // next file number
    BigEndian::write_u16(&mut mdb[34..36], g.num_alloc_blocks); // all free

    let name_bytes = crate::hfs::utf8_to_mac_roman(name).unwrap_or_default();
    let name_len = name_bytes.len().min(MFS_MAX_NAME_LEN);
    mdb[36] = name_len as u8;
    mdb[37..37 + name_len].copy_from_slice(&name_bytes[..name_len]);

    // The allocation map (byte 64 of the MDB, straddling into later sectors)
    // and the directory sectors are all-free / all-zero, which the surrounding
    // zero-fill already provides.
    Ok(disk)
}

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

    /// Build a minimal valid MFS volume in memory. Two files:
    ///   - "Hello"   data fork = b"hello mfs"      (no resource fork)
    ///   - "Doc"     data fork = b"first line\n"   resource fork = b"RSRC"
    ///
    /// Layout (all 512 B sectors):
    ///   sector 0..1     boot blocks (zero)
    ///   sector 2        MDB + volume name + map
    ///   sector 3..4     file directory (2 sectors)
    ///   sector 5+       allocation blocks (1 KiB each — 2 sectors per block)
    ///
    /// Allocation block size = 1024 B (2 sectors). 8 alloc blocks total →
    /// 8 KiB volume of file data. Plenty for the test files.
    fn build_test_mfs() -> Vec<u8> {
        const SECTOR: usize = 512;
        const NUM_SECTORS: usize = 32; // 16 KiB volume
        const ALLOC_BLOCK_SIZE: u32 = 1024;
        const FIRST_ALLOC_BLOCK_SECTOR: u16 = 5;
        const DIR_START: u16 = 3;
        const DIR_LEN: u16 = 2;
        const NUM_ALLOC_BLOCKS: u16 = 8;

        let mut disk = vec![0u8; NUM_SECTORS * SECTOR];

        // --- MDB ---
        let mdb = &mut disk[1024..1024 + 512];
        BigEndian::write_u16(&mut mdb[0..2], MFS_SIGNATURE);
        BigEndian::write_u32(&mut mdb[2..6], 0); // create date
        BigEndian::write_u32(&mut mdb[6..10], 0); // last backup
        BigEndian::write_u16(&mut mdb[10..12], 0); // attributes
        BigEndian::write_u16(&mut mdb[12..14], 2); // num files
        BigEndian::write_u16(&mut mdb[14..16], DIR_START);
        BigEndian::write_u16(&mut mdb[16..18], DIR_LEN);
        BigEndian::write_u16(&mut mdb[18..20], NUM_ALLOC_BLOCKS);
        BigEndian::write_u32(&mut mdb[20..24], ALLOC_BLOCK_SIZE);
        BigEndian::write_u32(&mut mdb[24..28], ALLOC_BLOCK_SIZE);
        BigEndian::write_u16(&mut mdb[28..30], FIRST_ALLOC_BLOCK_SECTOR);
        BigEndian::write_u32(&mut mdb[30..34], 3); // next file number
        BigEndian::write_u16(&mut mdb[34..36], NUM_ALLOC_BLOCKS - 3); // free blocks
        let vname = b"Tester";
        mdb[36] = vname.len() as u8;
        mdb[37..37 + vname.len()].copy_from_slice(vname);

        // --- Volume map ---
        // Map starts at the fixed offset 1024 + 64 = 1088. 8 alloc blocks × 12
        // bits = 96 bits = 12 bytes. Blocks 0 & 1 reserved; entry index 0 is
        // block 2. Layout:
        //   Block 2 → 1 (end of chain for "Hello")
        //   Block 3 → 1 (end of chain for "Doc" data fork)
        //   Block 4 → 1 (end of chain for "Doc" rsrc fork)
        //   Blocks 5..9 → 0 (free)
        let map_start = 1024 + 64;
        let mut map = vec![0u8; 12];
        write_map_entry(&mut map, 2, 1);
        write_map_entry(&mut map, 3, 1);
        write_map_entry(&mut map, 4, 1);
        disk[map_start..map_start + map.len()].copy_from_slice(&map);

        // --- File directory ---
        // Build two entries in sector 3 (first dir sector).
        let mut dir_sec = vec![0u8; SECTOR];
        let off = encode_dir_entry(
            &mut dir_sec,
            0,
            DirEntryIn {
                flags: 0x80,
                file_number: 1,
                data_first_block: 2,
                data_logical_length: 9, // "hello mfs"
                data_physical_length: ALLOC_BLOCK_SIZE,
                rsrc_first_block: 0,
                rsrc_logical_length: 0,
                rsrc_physical_length: 0,
                type_code: *b"TEXT",
                creator_code: *b"ttxt",
                name: b"Hello",
            },
        );
        let off = encode_dir_entry(
            &mut dir_sec,
            off,
            DirEntryIn {
                flags: 0x80,
                file_number: 2,
                data_first_block: 3,
                data_logical_length: 11, // "first line\n"
                data_physical_length: ALLOC_BLOCK_SIZE,
                rsrc_first_block: 4,
                rsrc_logical_length: 4, // "RSRC"
                rsrc_physical_length: ALLOC_BLOCK_SIZE,
                type_code: *b"TEXT",
                creator_code: *b"ttxt",
                name: b"Doc",
            },
        );
        let _ = off;
        disk[3 * SECTOR..3 * SECTOR + SECTOR].copy_from_slice(&dir_sec);

        // --- File data ---
        let alloc_start = FIRST_ALLOC_BLOCK_SECTOR as usize * SECTOR;
        // Block 2 — "Hello"'s data
        disk[alloc_start..alloc_start + 9].copy_from_slice(b"hello mfs");
        // Block 3 — "Doc"'s data (1 alloc block later)
        let b3 = alloc_start + ALLOC_BLOCK_SIZE as usize;
        disk[b3..b3 + 11].copy_from_slice(b"first line\n");
        // Block 4 — "Doc"'s rsrc
        let b4 = alloc_start + 2 * ALLOC_BLOCK_SIZE as usize;
        disk[b4..b4 + 4].copy_from_slice(b"RSRC");

        disk
    }

    struct DirEntryIn<'a> {
        flags: u8,
        file_number: u32,
        data_first_block: u16,
        data_logical_length: u32,
        data_physical_length: u32,
        rsrc_first_block: u16,
        rsrc_logical_length: u32,
        rsrc_physical_length: u32,
        type_code: [u8; 4],
        creator_code: [u8; 4],
        name: &'a [u8],
    }

    fn encode_dir_entry(buf: &mut [u8], off: usize, e: DirEntryIn) -> usize {
        buf[off] = e.flags;
        buf[off + 1] = 0; // version
        buf[off + 2..off + 6].copy_from_slice(&e.type_code);
        buf[off + 6..off + 10].copy_from_slice(&e.creator_code);
        // finder_info bytes 8..16 zeroed.
        BigEndian::write_u32(&mut buf[off + 18..off + 22], e.file_number);
        BigEndian::write_u16(&mut buf[off + 22..off + 24], e.data_first_block);
        BigEndian::write_u32(&mut buf[off + 24..off + 28], e.data_logical_length);
        BigEndian::write_u32(&mut buf[off + 28..off + 32], e.data_physical_length);
        BigEndian::write_u16(&mut buf[off + 32..off + 34], e.rsrc_first_block);
        BigEndian::write_u32(&mut buf[off + 34..off + 38], e.rsrc_logical_length);
        BigEndian::write_u32(&mut buf[off + 38..off + 42], e.rsrc_physical_length);
        // dates at +42 / +46 — leave zero.
        buf[off + 50] = e.name.len() as u8;
        buf[off + 51..off + 51 + e.name.len()].copy_from_slice(e.name);
        let entry_len = 51 + e.name.len();
        off + entry_len + (entry_len & 1)
    }

    /// Write a 12-bit volume-map entry into the packed map buffer.
    /// Mirrors the high-nibble-first packing used by `map_get`.
    fn write_map_entry(map: &mut [u8], block: u16, value: u16) {
        let value = value & 0x0FFF;
        let bit_off = (block as usize - 2) * 12;
        let byte_off = bit_off / 8;
        if block.is_multiple_of(2) {
            map[byte_off] = (value >> 4) as u8;
            map[byte_off + 1] = (map[byte_off + 1] & 0x0F) | (((value & 0x0F) as u8) << 4);
        } else {
            map[byte_off] = (map[byte_off] & 0xF0) | ((value >> 8) as u8 & 0x0F);
            map[byte_off + 1] = (value & 0xFF) as u8;
        }
    }

    #[test]
    fn parses_mdb_from_synthetic_volume() {
        let disk = build_test_mfs();
        let cur = Cursor::new(disk);
        let fs = MfsFilesystem::open(cur, 0).unwrap();
        assert_eq!(fs.mdb.num_files, 2);
        assert_eq!(fs.mdb.alloc_block_size, 1024);
        assert_eq!(fs.mdb.num_alloc_blocks, 8);
        assert_eq!(fs.mdb.first_alloc_block_sector, 5);
        assert_eq!(fs.volume_label(), Some("Tester"));
        assert_eq!(fs.fs_type(), "MFS");
    }

    #[test]
    fn lists_root_directory() {
        let disk = build_test_mfs();
        let cur = Cursor::new(disk);
        let mut fs = MfsFilesystem::open(cur, 0).unwrap();
        let root = fs.root().unwrap();
        let entries = fs.list_directory(&root).unwrap();
        assert_eq!(entries.len(), 2);
        let names: Vec<&str> = entries.iter().map(|e| e.name.as_str()).collect();
        assert!(names.contains(&"Doc"));
        assert!(names.contains(&"Hello"));
        let doc = entries.iter().find(|e| e.name == "Doc").unwrap();
        assert_eq!(doc.resource_fork_size, Some(4));
        let hello = entries.iter().find(|e| e.name == "Hello").unwrap();
        assert_eq!(hello.resource_fork_size, None);
        assert_eq!(hello.type_code, Some(*b"TEXT"));
        assert_eq!(hello.creator_code, Some(*b"ttxt"));
    }

    #[test]
    fn reads_data_fork() {
        let disk = build_test_mfs();
        let cur = Cursor::new(disk);
        let mut fs = MfsFilesystem::open(cur, 0).unwrap();
        let root = fs.root().unwrap();
        let entries = fs.list_directory(&root).unwrap();
        let hello = entries.iter().find(|e| e.name == "Hello").unwrap();
        let data = fs.read_file(hello, 1024).unwrap();
        assert_eq!(&data, b"hello mfs");
        let doc = entries.iter().find(|e| e.name == "Doc").unwrap();
        let data = fs.read_file(doc, 1024).unwrap();
        assert_eq!(&data, b"first line\n");
    }

    #[test]
    fn reads_resource_fork() {
        let disk = build_test_mfs();
        let cur = Cursor::new(disk);
        let mut fs = MfsFilesystem::open(cur, 0).unwrap();
        let root = fs.root().unwrap();
        let entries = fs.list_directory(&root).unwrap();
        let doc = entries.iter().find(|e| e.name == "Doc").unwrap();
        let rsrc = fs.read_resource_fork(doc).unwrap();
        assert_eq!(&rsrc, b"RSRC");
        let hello = entries.iter().find(|e| e.name == "Hello").unwrap();
        let empty = fs.read_resource_fork(hello).unwrap();
        assert!(empty.is_empty());
    }

    #[test]
    fn resource_fork_via_trait_object() {
        // Regression: every real consumer (get-binhex, MacBinary/AppleDouble
        // export, cp, the remote daemon) holds a `dyn Filesystem` and reaches
        // the resource fork ONLY through the trait's `write_resource_fork_to` /
        // `resource_fork_size` — never the inherent `read_resource_fork`. Before
        // these were wired they defaulted to `Ok(0)` / `0`, silently dropping
        // every MFS resource fork.
        let disk = build_test_mfs();
        let mut fs = MfsFilesystem::open(Cursor::new(disk), 0).unwrap();
        let root = fs.root().unwrap();
        let entries = fs.list_directory(&root).unwrap();
        let doc = entries.iter().find(|e| e.name == "Doc").unwrap().clone();
        let hello = entries.iter().find(|e| e.name == "Hello").unwrap().clone();

        let fsys: &mut dyn Filesystem = &mut fs;
        assert_eq!(fsys.resource_fork_size(&doc), 4);
        let mut buf = Vec::new();
        assert_eq!(fsys.write_resource_fork_to(&doc, &mut buf).unwrap(), 4);
        assert_eq!(&buf, b"RSRC");

        // A fork-less file still yields zero through the trait.
        assert_eq!(fsys.resource_fork_size(&hello), 0);
        let mut empty = Vec::new();
        assert_eq!(fsys.write_resource_fork_to(&hello, &mut empty).unwrap(), 0);
        assert!(empty.is_empty());
    }

    #[test]
    fn resource_fork_survives_real_export_consumer() {
        // End-to-end through the *actual* shared export path used by the browse
        // view's "Extract" and Commander's copy-to-host
        // (fork_export::export_file_with_fork). SeparateRsrc mode writes the raw
        // resource fork to a `<name>.rsrc` sidecar — before the trait wiring this
        // sidecar was empty / never written for MFS files.
        use crate::fork_export::export_file_with_fork;
        use crate::resource_fork::ResourceForkMode;

        let dir = std::env::temp_dir().join(format!("rb_mfs_fork_{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();

        let mut fs = MfsFilesystem::open(Cursor::new(build_test_mfs()), 0).unwrap();
        let root = fs.root().unwrap();
        let doc = fs
            .list_directory(&root)
            .unwrap()
            .into_iter()
            .find(|e| e.name == "Doc")
            .unwrap();

        export_file_with_fork(&mut fs, &doc, &dir, "Doc", ResourceForkMode::SeparateRsrc).unwrap();

        // Data fork under the plain name, plus a NON-EMPTY resource-fork sidecar
        // carrying the real bytes.
        assert_eq!(std::fs::read(dir.join("Doc")).unwrap(), b"first line\n");
        assert_eq!(std::fs::read(dir.join("Doc.rsrc")).unwrap(), b"RSRC");

        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn create_file_with_resource_fork_persists() {
        // The put-binhex / put-macbinary path: create_file with a resource fork
        // in CreateFileOptions. Must allocate + write a second chain and survive
        // sync + reopen — before this, MFS create_file dropped the fork.
        use disk_core::filesystem::ResourceForkSource;
        let mut cur = Cursor::new(build_test_mfs());
        {
            let mut fs = MfsFilesystem::open(&mut cur, 0).unwrap();
            let root = fs.root().unwrap();
            let opts = CreateFileOptions {
                resource_fork: Some(ResourceForkSource::Data(b"NEW-RSRC-BYTES".to_vec())),
                ..Default::default()
            };
            let data = b"data fork content";
            let fe = fs
                .create_file(&root, "Forked", &mut &data[..], data.len() as u64, &opts)
                .unwrap();
            assert_eq!(fe.resource_fork_size, Some(14));
            fs.sync_metadata().unwrap();
        }
        cur.set_position(0);
        let mut fs = MfsFilesystem::open(&mut cur, 0).unwrap();
        let root = fs.root().unwrap();
        let forked = fs
            .list_directory(&root)
            .unwrap()
            .into_iter()
            .find(|e| e.name == "Forked")
            .unwrap();
        assert_eq!(forked.resource_fork_size, Some(14));
        assert_eq!(
            fs.read_file(&forked, usize::MAX).unwrap(),
            b"data fork content"
        );
        // Through the trait, as the export consumers read it back.
        let fsys: &mut dyn Filesystem = &mut fs;
        let mut buf = Vec::new();
        fsys.write_resource_fork_to(&forked, &mut buf).unwrap();
        assert_eq!(&buf, b"NEW-RSRC-BYTES");
    }

    #[test]
    fn write_resource_fork_sets_and_replaces() {
        // The setrsrc / batch path: set a fork on a fork-less file, then replace
        // it with a different-sized one (frees the old chain first).
        let mut cur = Cursor::new(build_test_mfs());
        {
            let mut fs = MfsFilesystem::open(&mut cur, 0).unwrap();
            let root = fs.root().unwrap();
            let fe = fs
                .create_file(
                    &root,
                    "SetR",
                    &mut &b"body"[..],
                    4,
                    &CreateFileOptions::default(),
                )
                .unwrap();
            fs.write_resource_fork(&fe, &mut &b"FIRST"[..], 5).unwrap();
            fs.sync_metadata().unwrap();
        }
        cur.set_position(0);
        {
            let mut fs = MfsFilesystem::open(&mut cur, 0).unwrap();
            let root = fs.root().unwrap();
            let e = fs
                .list_directory(&root)
                .unwrap()
                .into_iter()
                .find(|e| e.name == "SetR")
                .unwrap();
            assert_eq!(fs.read_resource_fork(&e).unwrap(), b"FIRST");
            fs.write_resource_fork(&e, &mut &b"SECOND-and-longer"[..], 17)
                .unwrap();
            fs.sync_metadata().unwrap();
        }
        cur.set_position(0);
        let mut fs = MfsFilesystem::open(&mut cur, 0).unwrap();
        let root = fs.root().unwrap();
        let e = fs
            .list_directory(&root)
            .unwrap()
            .into_iter()
            .find(|e| e.name == "SetR")
            .unwrap();
        assert_eq!(fs.read_resource_fork(&e).unwrap(), b"SECOND-and-longer");
    }

    #[test]
    fn rejects_non_mfs_signature() {
        let mut disk = build_test_mfs();
        disk[1024] = 0xFF;
        disk[1025] = 0xFF;
        let cur = Cursor::new(disk);
        match MfsFilesystem::open(cur, 0) {
            Ok(_) => panic!("expected open to fail on bad signature"),
            Err(FilesystemError::InvalidData(msg)) => {
                assert!(msg.contains("bad MFS signature"), "got: {msg}");
            }
            Err(other) => panic!("expected InvalidData, got {other:?}"),
        }
    }

    // ------------------------------------------------------------------
    // create-blank + fsck
    // ------------------------------------------------------------------

    #[test]
    fn create_blank_400k_round_trips_and_fscks_clean() {
        let img = create_blank_mfs(MFS_400K_BYTES, "Blank400").unwrap();
        assert_eq!(img.len() as u64, MFS_400K_BYTES);
        let mut fs = MfsFilesystem::open(Cursor::new(img), 0).unwrap();
        assert_eq!(fs.fs_type(), "MFS");
        assert_eq!(fs.volume_label(), Some("Blank400"));
        assert_eq!(fs.mdb.num_files, 0);
        assert_eq!(fs.mdb.free_blocks, fs.mdb.num_alloc_blocks);
        let root = fs.root().unwrap();
        assert!(fs.list_directory(&root).unwrap().is_empty());
        let res = fs.fsck().unwrap().unwrap();
        assert!(
            res.is_clean(),
            "blank 400K should fsck clean: {:?}",
            res.errors
        );
    }

    #[test]
    fn create_blank_geometry_valid_across_sizes() {
        for size in [
            MFS_400K_BYTES,
            MFS_800K_BYTES,
            1_474_560, // 1.44 MB
            4 * 1024 * 1024,
            20 * 1024 * 1024,
        ] {
            let img = create_blank_mfs(size, "Vol").unwrap();
            let mut fs = MfsFilesystem::open(Cursor::new(img), 0).unwrap();
            // Data region must fit inside the volume.
            let (first_ab, nab, abs) = (
                fs.mdb.first_alloc_block_sector as u64,
                fs.mdb.num_alloc_blocks as u64,
                fs.mdb.alloc_block_size as u64,
            );
            let last_sector = first_ab + nab * (abs / 512);
            assert!(
                last_sector <= size / 512,
                "size {size}: data region ends at sector {last_sector}, past {}",
                size / 512
            );
            assert!(nab <= 4094, "size {size}: too many blocks");
            let res = fs.fsck().unwrap().unwrap();
            assert!(
                res.is_clean(),
                "size {size} should fsck clean: {:?}",
                res.errors
            );
        }
    }

    #[test]
    fn create_blank_too_small_is_rejected() {
        assert!(create_blank_mfs(8 * 1024, "X").is_err());
    }

    #[test]
    fn blank_volume_accepts_files_and_stays_clean() {
        let img = create_blank_mfs(MFS_400K_BYTES, "Work").unwrap();
        let mut cur = Cursor::new(img);
        {
            let mut fs = MfsFilesystem::open(&mut cur, 0).unwrap();
            let root = fs.root().unwrap();
            fs.create_file(
                &root,
                "ReadMe",
                &mut &b"hello from a blank MFS volume"[..],
                29,
                &CreateFileOptions::default(),
            )
            .unwrap();
            fs.sync_metadata().unwrap();
        }
        cur.set_position(0);
        let mut fs = MfsFilesystem::open(&mut cur, 0).unwrap();
        let root = fs.root().unwrap();
        let entries = fs.list_directory(&root).unwrap();
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].name, "ReadMe");
        assert_eq!(
            fs.read_file(&entries[0], usize::MAX).unwrap(),
            b"hello from a blank MFS volume"
        );
        let res = fs.fsck().unwrap().unwrap();
        assert!(
            res.is_clean(),
            "populated volume should fsck clean: {:?}",
            res.errors
        );
    }

    #[test]
    fn fsck_clean_on_synthetic_volume() {
        let mut fs = MfsFilesystem::open(Cursor::new(build_test_mfs()), 0).unwrap();
        let res = fs.fsck().unwrap().unwrap();
        assert!(res.is_clean(), "expected clean, got {:?}", res.errors);
        assert_eq!(res.stats.files_checked, 2);
    }

    #[test]
    fn fsck_detects_and_repairs_leaked_block() {
        let mut cur = Cursor::new(build_test_mfs());
        {
            let mut fs = MfsFilesystem::open(&mut cur, 0).unwrap();
            // Mark a currently-free block allocated (end-of-chain) without any
            // directory entry referencing it: a leaked block.
            fs.map_set(6, 1);
            let res = fs.fsck().unwrap().unwrap();
            assert!(!res.is_clean());
            assert!(res
                .errors
                .iter()
                .any(|e| e.code == "MfsLostBlocks" && e.repairable));
            assert!(res.repairable);
            let report = fs.repair().unwrap();
            assert_eq!(report.unrepairable_count, 0);
            assert!(!report.fixes_applied.is_empty());
            fs.reader.flush().unwrap();
        }
        // Reopen from disk: the reclaimed block is now free and fsck is clean.
        cur.set_position(0);
        let mut fs = MfsFilesystem::open(&mut cur, 0).unwrap();
        assert_eq!(fs.map_get(6), 0, "block 6 reclaimed");
        let res = fs.fsck().unwrap().unwrap();
        assert!(
            res.is_clean(),
            "post-repair should be clean: {:?}",
            res.errors
        );
    }

    #[test]
    fn fsck_detects_and_repairs_file_count() {
        let mut cur = Cursor::new(build_test_mfs());
        {
            let mut fs = MfsFilesystem::open(&mut cur, 0).unwrap();
            fs.mdb.num_files = 9; // wrong (actual: 2)
            let res = fs.fsck().unwrap().unwrap();
            assert!(res
                .errors
                .iter()
                .any(|e| e.code == "MfsFileCountMismatch" && e.repairable));
            fs.repair().unwrap();
            fs.reader.flush().unwrap();
        }
        cur.set_position(0);
        let mut fs = MfsFilesystem::open(&mut cur, 0).unwrap();
        assert_eq!(fs.mdb.num_files, 2);
        assert!(fs.fsck().unwrap().unwrap().is_clean());
    }

    #[test]
    fn fsck_withholds_repair_on_broken_chain() {
        let mut fs = MfsFilesystem::open(Cursor::new(build_test_mfs()), 0).unwrap();
        // Point a file's data fork past the end of the volume.
        fs.entries[0].data_first_block = 50; // last valid block is 9
        let res = fs.fsck().unwrap().unwrap();
        assert!(res.errors.iter().any(|e| e.code == "MfsBrokenChain"));
        assert!(!res.repairable, "a broken chain must not be repairable");
        let report = fs.repair().unwrap();
        assert!(report.fixes_applied.is_empty());
        assert!(report.unrepairable_count >= 1);
    }

    #[test]
    fn map_get_round_trip() {
        // Confirm our 12-bit packing round-trips through `MfsFilesystem::map_get`.
        let disk = build_test_mfs();
        let cur = Cursor::new(disk);
        let fs = MfsFilesystem::open(cur, 0).unwrap();
        assert_eq!(fs.map_get(2), 1, "block 2 marked end-of-chain");
        assert_eq!(fs.map_get(3), 1);
        assert_eq!(fs.map_get(4), 1);
        assert_eq!(fs.map_get(5), 0, "block 5 marked free");
        assert_eq!(fs.map_get(0), 0, "reserved block 0");
        assert_eq!(fs.map_get(1), 0, "reserved block 1");
    }

    #[test]
    fn total_and_used_size_reflect_mdb_counts() {
        let disk = build_test_mfs();
        let cur = Cursor::new(disk);
        let fs = MfsFilesystem::open(cur, 0).unwrap();
        assert_eq!(fs.total_size(), 8 * 1024);
        // 3 allocation blocks used (Hello data, Doc data, Doc rsrc).
        assert_eq!(fs.used_size(), 3 * 1024);
    }

    // ------------------------------------------------------------------
    // EditableFilesystem — create / delete / round-trip
    // ------------------------------------------------------------------

    /// Build a fresh test volume already inside a `Cursor<Vec<u8>>`. The
    /// cursor is the in-memory backing store the edit tests mutate
    /// through `EditableFilesystem`, then reopen for read-side
    /// verification.
    fn edit_fixture() -> Cursor<Vec<u8>> {
        Cursor::new(build_test_mfs())
    }

    #[test]
    fn create_file_writes_data_and_round_trips_through_sync() {
        let mut fs = MfsFilesystem::open(edit_fixture(), 0).unwrap();
        let root = fs.root().unwrap();
        let before_free = EditableFilesystem::free_space(&mut fs).unwrap();
        let payload = b"freshly-created via EditableFilesystem".to_vec();
        let mut src = Cursor::new(payload.clone());
        let opts = CreateFileOptions::default();
        let fe = fs
            .create_file(&root, "NewFile", &mut src, payload.len() as u64, &opts)
            .unwrap();
        assert_eq!(fe.name, "NewFile");
        assert_eq!(fe.size, payload.len() as u64);

        fs.sync_metadata().unwrap();
        // Reopen and prove the file persisted across a fresh parse.
        let inner = fs.reader.clone();
        let mut fs2 = MfsFilesystem::open(inner, 0).unwrap();
        let root2 = fs2.root().unwrap();
        let entries = fs2.list_directory(&root2).unwrap();
        let new = entries.iter().find(|e| e.name == "NewFile").unwrap();
        let read_back = fs2.read_file(new, 4096).unwrap();
        assert_eq!(read_back, payload);

        // Free-space accounting: one alloc-block consumed (payload < 1024 B).
        let after_free = EditableFilesystem::free_space(&mut fs2).unwrap();
        assert_eq!(after_free, before_free - 1024);
    }

    #[test]
    fn delete_entry_releases_blocks_and_clears_directory() {
        let mut fs = MfsFilesystem::open(edit_fixture(), 0).unwrap();
        let root = fs.root().unwrap();
        let before_free = EditableFilesystem::free_space(&mut fs).unwrap();
        let entries = fs.list_directory(&root).unwrap();
        let doc = entries.iter().find(|e| e.name == "Doc").unwrap().clone();

        fs.delete_entry(&root, &doc).unwrap();
        fs.sync_metadata().unwrap();

        let inner = fs.reader.clone();
        let mut fs2 = MfsFilesystem::open(inner, 0).unwrap();
        let root2 = fs2.root().unwrap();
        let entries = fs2.list_directory(&root2).unwrap();
        assert!(
            entries.iter().all(|e| e.name != "Doc"),
            "Doc should be gone after delete"
        );

        // "Doc" used 2 blocks (data fork + resource fork) at 1024 B each.
        let after_free = EditableFilesystem::free_space(&mut fs2).unwrap();
        assert_eq!(after_free, before_free + 2 * 1024);
    }

    #[test]
    fn rename_in_place_round_trips_through_sync() {
        let mut fs = MfsFilesystem::open(edit_fixture(), 0).unwrap();
        let root = fs.root().unwrap();
        let entries = fs.list_directory(&root).unwrap();
        let doc = entries.iter().find(|e| e.name == "Doc").unwrap().clone();
        let fnum = doc.location;

        fs.rename(&root, &doc, "Report").unwrap();
        fs.sync_metadata().unwrap();

        // Reopen and prove the rename persisted with identity + contents intact.
        let inner = fs.reader.clone();
        let mut fs2 = MfsFilesystem::open(inner, 0).unwrap();
        let root2 = fs2.root().unwrap();
        let entries2 = fs2.list_directory(&root2).unwrap();
        let names: Vec<&str> = entries2.iter().map(|e| e.name.as_str()).collect();
        assert!(names.contains(&"Report"));
        assert!(!names.contains(&"Doc"));

        let renamed = entries2.iter().find(|e| e.name == "Report").unwrap();
        // Same file number (identity); both forks + resource size preserved.
        assert_eq!(renamed.location, fnum);
        assert_eq!(renamed.resource_fork_size, Some(4));
        assert_eq!(fs2.read_file(renamed, 1024).unwrap(), b"first line\n");
        assert_eq!(fs2.read_resource_fork(renamed).unwrap(), b"RSRC");
    }

    /// H12: duplicate detection compared bytes, so "hello" could be created
    /// beside "Hello" and the Finder then saw two files it could not tell apart.
    #[test]
    fn names_differing_only_in_case_are_the_same_file() {
        let mut fs = MfsFilesystem::open(edit_fixture(), 0).unwrap();
        let root = fs.root().unwrap();
        let err = fs
            .create_file(
                &root,
                "hello",
                &mut &b"x"[..],
                1,
                &CreateFileOptions::default(),
            )
            .unwrap_err();
        assert!(format!("{err}").contains("already exists"), "{err}");
        let entries = fs.list_directory(&root).unwrap();
        let doc = entries.iter().find(|e| e.name == "Doc").unwrap().clone();
        let err = fs.rename(&root, &doc, "HELLO").unwrap_err();
        assert!(matches!(err, FilesystemError::AlreadyExists(_)));
        // A file may still change its own capitalisation.
        fs.rename(&root, &doc, "DOC").unwrap();
    }

    #[test]
    fn rename_rejects_collision() {
        let mut fs = MfsFilesystem::open(edit_fixture(), 0).unwrap();
        let root = fs.root().unwrap();
        let entries = fs.list_directory(&root).unwrap();
        let doc = entries.iter().find(|e| e.name == "Doc").unwrap().clone();
        // "Hello" already exists; renaming "Doc" onto it must be rejected.
        let err = fs.rename(&root, &doc, "Hello").unwrap_err();
        assert!(matches!(err, FilesystemError::AlreadyExists(_)));
    }

    #[test]
    fn create_file_rejects_duplicate_names() {
        let mut fs = MfsFilesystem::open(edit_fixture(), 0).unwrap();
        let root = fs.root().unwrap();
        let mut src = Cursor::new(b"x".to_vec());
        let err = fs
            .create_file(&root, "Hello", &mut src, 1, &CreateFileOptions::default())
            .unwrap_err();
        assert!(matches!(err, FilesystemError::InvalidData(_)));
    }

    #[test]
    fn create_file_rejects_oversize_data() {
        let mut fs = MfsFilesystem::open(edit_fixture(), 0).unwrap();
        let root = fs.root().unwrap();
        // The fixture has 5 free blocks of 1024 B each = 5 KiB free.
        // Try to write 8 KiB — must fail with InvalidData.
        let huge = vec![0u8; 8 * 1024];
        let mut src = Cursor::new(huge);
        let err = fs
            .create_file(
                &root,
                "TooBig",
                &mut src,
                8 * 1024,
                &CreateFileOptions::default(),
            )
            .unwrap_err();
        assert!(matches!(err, FilesystemError::InvalidData(_)));
    }

    #[test]
    fn create_then_delete_returns_to_original_free_count() {
        let mut fs = MfsFilesystem::open(edit_fixture(), 0).unwrap();
        let root = fs.root().unwrap();
        let before = EditableFilesystem::free_space(&mut fs).unwrap();
        let mut src = Cursor::new(b"abc".to_vec());
        let fe = fs
            .create_file(&root, "Tmp", &mut src, 3, &CreateFileOptions::default())
            .unwrap();
        let mid = EditableFilesystem::free_space(&mut fs).unwrap();
        assert_eq!(mid, before - 1024);
        // delete_entry needs a parent + the synthesized FileEntry from create.
        fs.delete_entry(&root, &fe).unwrap();
        let after = EditableFilesystem::free_space(&mut fs).unwrap();
        assert_eq!(after, before, "free count must return after create+delete");
    }

    #[test]
    fn create_directory_is_unsupported() {
        let mut fs = MfsFilesystem::open(edit_fixture(), 0).unwrap();
        let root = fs.root().unwrap();
        let err = fs
            .create_directory(&root, "subdir", &CreateDirectoryOptions::default())
            .unwrap_err();
        assert!(matches!(err, FilesystemError::Unsupported(_)));
    }

    #[test]
    fn set_type_creator_updates_finder_info_and_persists() {
        let mut fs = MfsFilesystem::open(edit_fixture(), 0).unwrap();
        let root = fs.root().unwrap();
        let entries = fs.list_directory(&root).unwrap();
        let hello = entries.iter().find(|e| e.name == "Hello").unwrap().clone();
        fs.set_type_creator(&hello, "PICT", "8BIM").unwrap();
        fs.sync_metadata().unwrap();

        let inner = fs.reader.clone();
        let mut fs2 = MfsFilesystem::open(inner, 0).unwrap();
        let root2 = fs2.root().unwrap();
        let entries = fs2.list_directory(&root2).unwrap();
        let hello2 = entries.iter().find(|e| e.name == "Hello").unwrap();
        assert_eq!(hello2.type_code, Some(*b"PICT"));
        assert_eq!(hello2.creator_code, Some(*b"8BIM"));
    }
}

#[cfg(test)]
mod physical_length_tests {
    use super::*;
    use disk_core::filesystem::{CreateFileOptions, Filesystem};
    use std::io::Cursor;

    /// H6: flPyLen / flRPyLen were written as the logical lengths; Mac OS
    /// expects the allocated size, whole allocation blocks.
    #[test]
    fn physical_lengths_are_whole_allocation_blocks() {
        let img = create_blank_mfs(400 * 1024, "T").unwrap();
        let mut fs = MfsFilesystem::open(Cursor::new(img), 0).unwrap();
        let root = fs.root().unwrap();
        let mut data = Cursor::new(vec![0x5Au8; 100]);
        fs.create_file(&root, "tiny", &mut data, 100, &CreateFileOptions::default())
            .unwrap();
        fs.sync_metadata().unwrap();
        let abs = fs.mdb.alloc_block_size;
        let off = fs.partition_offset + fs.mdb.dir_start_sector as u64 * 512;
        fs.reader.seek(SeekFrom::Start(off)).unwrap();
        let mut sector = [0u8; 512];
        fs.reader.read_exact(&mut sector).unwrap();
        assert_ne!(sector[0] & 0x80, 0, "first directory entry is in use");
        assert_eq!(
            BigEndian::read_u32(&sector[24..28]),
            100,
            "logical data length"
        );
        assert_eq!(
            BigEndian::read_u32(&sector[28..32]),
            abs,
            "physical data length"
        );
        assert_eq!(BigEndian::read_u32(&sector[38..42]), 0, "no resource fork");
    }
}