hadris-fat 1.1.2

A library for working with FAT filesystems (FAT12/FAT16/FAT32/exFAT)
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
//! Tests for write operations.
//!
//! These tests require the "write" feature.

#![cfg(feature = "write")]

use hadris_fat::file::ShortFileName;

#[test]
fn test_short_filename_from_long_name_simple() {
    let sfn = ShortFileName::from_long_name("test.txt", 0).unwrap();
    assert_eq!(sfn.as_str(), "TEST    .TXT");
}

#[test]
fn test_short_filename_from_long_name_with_suffix() {
    let sfn = ShortFileName::from_long_name("test.txt", 1).unwrap();
    assert!(sfn.as_str().contains("~1"));
}

#[test]
fn test_short_filename_from_long_name_no_extension() {
    let sfn = ShortFileName::from_long_name("README", 0).unwrap();
    assert!(sfn.as_str().starts_with("README"));
}

#[test]
fn test_short_filename_from_long_name_long_base() {
    let sfn = ShortFileName::from_long_name("verylongfilename.txt", 1).unwrap();
    // Should truncate to 6 chars + ~1
    assert!(sfn.as_str().starts_with("VERYLO~1"));
}

#[test]
fn test_short_filename_from_long_name_lowercase() {
    let sfn = ShortFileName::from_long_name("lowercase.dat", 0).unwrap();
    // Should be converted to uppercase
    assert_eq!(sfn.as_str(), "LOWERCAS.DAT");
}

#[test]
fn test_short_filename_from_long_name_special_chars() {
    let sfn = ShortFileName::from_long_name("my file.txt", 0).unwrap();
    // Spaces should be stripped
    assert!(!sfn.as_str().contains(' ') || sfn.as_str().chars().filter(|c| *c == ' ').count() <= 3);
}

#[cfg(feature = "std")]
mod datetime_tests {
    use hadris_fat::FatDateTime;

    #[test]
    fn test_fat_datetime_now() {
        let dt = FatDateTime::now();
        // Date should be non-zero (after 1980)
        assert!(dt.date > 0);
    }

    #[test]
    fn test_fat_datetime_new() {
        let dt = FatDateTime::new(2024, 6, 15, 14, 30, 45);
        let (date, time, _) = dt.to_raw();

        // Decode date: (year-1980)<<9 | month<<5 | day
        let year = ((date >> 9) & 0x7F) + 1980;
        let month = (date >> 5) & 0x0F;
        let day = date & 0x1F;

        assert_eq!(year, 2024);
        assert_eq!(month, 6);
        assert_eq!(day, 15);

        // Decode time: hour<<11 | minute<<5 | (second/2)
        let hour = (time >> 11) & 0x1F;
        let minute = (time >> 5) & 0x3F;
        let second = (time & 0x1F) * 2;

        assert_eq!(hour, 14);
        assert_eq!(minute, 30);
        // Second is stored with 2-second granularity
        assert!(second == 44 || second == 46);
    }
}

/// Helper module to create FAT32 images in memory for testing
#[cfg(feature = "std")]
mod fat32_image {
    use std::io::Cursor;

    /// Sector size in bytes
    const SECTOR_SIZE: usize = 512;
    /// Sectors per cluster
    const SECTORS_PER_CLUSTER: u8 = 1;
    /// Cluster size in bytes
    const CLUSTER_SIZE: usize = SECTOR_SIZE * SECTORS_PER_CLUSTER as usize;
    /// Reserved sectors (including boot and FSInfo)
    const RESERVED_SECTORS: u16 = 32;
    /// Number of FAT copies
    const FAT_COUNT: u8 = 2;
    /// Sectors per FAT (enough for our small test image)
    const SECTORS_PER_FAT: u32 = 128;
    /// Root directory cluster
    const ROOT_CLUSTER: u32 = 2;

    /// FSInfo signature constants
    const FSINFO_LEAD_SIG: u32 = 0x41615252;
    const FSINFO_STRUC_SIG: u32 = 0x61417272;
    const FSINFO_TRAIL_SIG: u32 = 0xAA550000;

    /// Create a minimal FAT32 image in memory.
    ///
    /// The image has:
    /// - 512 byte sectors
    /// - 1 sector per cluster
    /// - 32 reserved sectors
    /// - 2 FATs, each 128 sectors
    /// - Root directory at cluster 2
    /// - Total size: ~150KB
    pub fn create_fat32_image() -> Cursor<Vec<u8>> {
        // Calculate total size
        let data_start_sector = RESERVED_SECTORS as u32 + FAT_COUNT as u32 * SECTORS_PER_FAT;
        let total_data_clusters: u32 = 256; // Enough for testing
        let total_sectors = data_start_sector + total_data_clusters;
        let total_size = total_sectors as usize * SECTOR_SIZE;

        let mut image = vec![0u8; total_size];

        // Write boot sector (sector 0)
        write_boot_sector(&mut image);

        // Write FSInfo sector (sector 1)
        write_fsinfo_sector(&mut image, total_data_clusters - 1);

        // Write FAT tables
        let fat_start = RESERVED_SECTORS as usize * SECTOR_SIZE;
        write_fat_table(&mut image, fat_start);
        // Second FAT copy
        let fat2_start = fat_start + SECTORS_PER_FAT as usize * SECTOR_SIZE;
        write_fat_table(&mut image, fat2_start);

        // Initialize root directory cluster (cluster 2) - already zeroed

        Cursor::new(image)
    }

    fn write_boot_sector(image: &mut [u8]) {
        // Jump instruction
        image[0] = 0xEB;
        image[1] = 0x58;
        image[2] = 0x90;

        // OEM name
        image[3..11].copy_from_slice(b"HADRISFT");

        // BPB_BytsPerSec
        image[11..13].copy_from_slice(&(SECTOR_SIZE as u16).to_le_bytes());

        // BPB_SecPerClus
        image[13] = SECTORS_PER_CLUSTER;

        // BPB_RsvdSecCnt
        image[14..16].copy_from_slice(&RESERVED_SECTORS.to_le_bytes());

        // BPB_NumFATs
        image[16] = FAT_COUNT;

        // BPB_RootEntCnt (must be 0 for FAT32)
        image[17..19].copy_from_slice(&0u16.to_le_bytes());

        // BPB_TotSec16 (must be 0 for FAT32)
        image[19..21].copy_from_slice(&0u16.to_le_bytes());

        // BPB_Media (0xF8 = fixed disk)
        image[21] = 0xF8;

        // BPB_FATSz16 (must be 0 for FAT32)
        image[22..24].copy_from_slice(&0u16.to_le_bytes());

        // BPB_SecPerTrk
        image[24..26].copy_from_slice(&63u16.to_le_bytes());

        // BPB_NumHeads
        image[26..28].copy_from_slice(&255u16.to_le_bytes());

        // BPB_HiddSec
        image[28..32].copy_from_slice(&0u32.to_le_bytes());

        // BPB_TotSec32
        let total_sectors = RESERVED_SECTORS as u32 + FAT_COUNT as u32 * SECTORS_PER_FAT + 256;
        image[32..36].copy_from_slice(&total_sectors.to_le_bytes());

        // FAT32 extended fields (offset 36)
        // BPB_FATSz32
        image[36..40].copy_from_slice(&SECTORS_PER_FAT.to_le_bytes());

        // BPB_ExtFlags (mirror FATs)
        image[40..42].copy_from_slice(&0u16.to_le_bytes());

        // BPB_FSVer
        image[42..44].copy_from_slice(&0u16.to_le_bytes());

        // BPB_RootClus
        image[44..48].copy_from_slice(&ROOT_CLUSTER.to_le_bytes());

        // BPB_FSInfo (sector 1)
        image[48..50].copy_from_slice(&1u16.to_le_bytes());

        // BPB_BkBootSec (sector 6)
        image[50..52].copy_from_slice(&6u16.to_le_bytes());

        // Reserved (52-63)
        // Already zeroed

        // BS_DrvNum
        image[64] = 0x80;

        // BS_Reserved1
        image[65] = 0;

        // BS_BootSig
        image[66] = 0x29;

        // BS_VolID
        image[67..71].copy_from_slice(&0x12345678u32.to_le_bytes());

        // BS_VolLab
        image[71..82].copy_from_slice(b"TEST       ");

        // BS_FilSysType
        image[82..90].copy_from_slice(b"FAT32   ");

        // Boot signature at 510-511
        image[510] = 0x55;
        image[511] = 0xAA;
    }

    fn write_fsinfo_sector(image: &mut [u8], free_clusters: u32) {
        let offset = SECTOR_SIZE; // Sector 1

        // FSI_LeadSig
        image[offset..offset + 4].copy_from_slice(&FSINFO_LEAD_SIG.to_le_bytes());

        // Reserved (4-483) - already zeroed

        // FSI_StrucSig (offset 484)
        image[offset + 484..offset + 488].copy_from_slice(&FSINFO_STRUC_SIG.to_le_bytes());

        // FSI_Free_Count
        image[offset + 488..offset + 492].copy_from_slice(&free_clusters.to_le_bytes());

        // FSI_Nxt_Free (start search at cluster 3, since 2 is root)
        image[offset + 492..offset + 496].copy_from_slice(&3u32.to_le_bytes());

        // Reserved (496-507) - already zeroed

        // FSI_TrailSig
        image[offset + 508..offset + 512].copy_from_slice(&FSINFO_TRAIL_SIG.to_le_bytes());
    }

    fn write_fat_table(image: &mut [u8], fat_start: usize) {
        // Entry 0: Media type in low byte, 0xFF in rest
        image[fat_start..fat_start + 4].copy_from_slice(&0x0FFFFFF8u32.to_le_bytes());

        // Entry 1: End of chain marker (clean shutdown)
        image[fat_start + 4..fat_start + 8].copy_from_slice(&0x0FFFFFFFu32.to_le_bytes());

        // Entry 2: End of chain for root directory (single cluster)
        image[fat_start + 8..fat_start + 12].copy_from_slice(&0x0FFFFFF8u32.to_le_bytes());

        // Rest of FAT entries are 0 (free clusters)
    }

    /// Get cluster size for the test image
    pub const fn cluster_size() -> usize {
        CLUSTER_SIZE
    }
}

/// Helper module to create FAT16 images in memory for testing
#[cfg(feature = "std")]
mod fat16_image {
    use std::io::Cursor;

    /// Sector size in bytes
    const SECTOR_SIZE: usize = 512;
    /// Sectors per cluster
    const SECTORS_PER_CLUSTER: u8 = 1;
    /// Cluster size in bytes
    const CLUSTER_SIZE: usize = SECTOR_SIZE * SECTORS_PER_CLUSTER as usize;
    /// Reserved sectors (just boot sector for FAT16)
    const RESERVED_SECTORS: u16 = 1;
    /// Number of FAT copies
    const FAT_COUNT: u8 = 2;
    /// Sectors per FAT (enough for our small test image)
    const SECTORS_PER_FAT: u16 = 32;
    /// Root directory entry count
    const ROOT_ENTRY_COUNT: u16 = 512;

    /// Create a minimal FAT16 image in memory.
    ///
    /// The image has:
    /// - 512 byte sectors
    /// - 1 sector per cluster
    /// - 1 reserved sector
    /// - 2 FATs, each 32 sectors
    /// - 512 root directory entries (32 sectors)
    /// - Total size: ~2MB (enough clusters to be detected as FAT16)
    pub fn create_fat16_image() -> Cursor<Vec<u8>> {
        // Calculate layout
        let root_dir_sectors = (ROOT_ENTRY_COUNT as usize * 32 + SECTOR_SIZE - 1) / SECTOR_SIZE;
        let data_start_sector = RESERVED_SECTORS as usize
            + FAT_COUNT as usize * SECTORS_PER_FAT as usize
            + root_dir_sectors;

        // Need enough clusters to be FAT16 (>= 4085 clusters)
        let total_data_clusters: usize = 8192; // Well into FAT16 range
        let total_sectors = data_start_sector + total_data_clusters;
        let total_size = total_sectors * SECTOR_SIZE;

        let mut image = vec![0u8; total_size];

        // Write boot sector (sector 0)
        write_boot_sector(&mut image, total_sectors as u32);

        // Write FAT tables
        let fat_start = RESERVED_SECTORS as usize * SECTOR_SIZE;
        write_fat_table(&mut image, fat_start);
        // Second FAT copy
        let fat2_start = fat_start + SECTORS_PER_FAT as usize * SECTOR_SIZE;
        write_fat_table(&mut image, fat2_start);

        // Root directory is initially empty (zeroed)

        Cursor::new(image)
    }

    fn write_boot_sector(image: &mut [u8], total_sectors: u32) {
        // Jump instruction
        image[0] = 0xEB;
        image[1] = 0x3C;
        image[2] = 0x90;

        // OEM name
        image[3..11].copy_from_slice(b"HADRISFT");

        // BPB_BytsPerSec
        image[11..13].copy_from_slice(&(SECTOR_SIZE as u16).to_le_bytes());

        // BPB_SecPerClus
        image[13] = SECTORS_PER_CLUSTER;

        // BPB_RsvdSecCnt
        image[14..16].copy_from_slice(&RESERVED_SECTORS.to_le_bytes());

        // BPB_NumFATs
        image[16] = FAT_COUNT;

        // BPB_RootEntCnt (non-zero for FAT16)
        image[17..19].copy_from_slice(&ROOT_ENTRY_COUNT.to_le_bytes());

        // BPB_TotSec16 (0 if > 65535)
        if total_sectors <= 65535 {
            image[19..21].copy_from_slice(&(total_sectors as u16).to_le_bytes());
        } else {
            image[19..21].copy_from_slice(&0u16.to_le_bytes());
        }

        // BPB_Media (0xF8 = fixed disk)
        image[21] = 0xF8;

        // BPB_FATSz16 (non-zero for FAT16)
        image[22..24].copy_from_slice(&SECTORS_PER_FAT.to_le_bytes());

        // BPB_SecPerTrk
        image[24..26].copy_from_slice(&63u16.to_le_bytes());

        // BPB_NumHeads
        image[26..28].copy_from_slice(&255u16.to_le_bytes());

        // BPB_HiddSec
        image[28..32].copy_from_slice(&0u32.to_le_bytes());

        // BPB_TotSec32
        if total_sectors > 65535 {
            image[32..36].copy_from_slice(&total_sectors.to_le_bytes());
        } else {
            image[32..36].copy_from_slice(&0u32.to_le_bytes());
        }

        // FAT16 extended fields (offset 36)
        // BS_DrvNum
        image[36] = 0x80;

        // BS_Reserved1
        image[37] = 0;

        // BS_BootSig
        image[38] = 0x29;

        // BS_VolID
        image[39..43].copy_from_slice(&0x12345678u32.to_le_bytes());

        // BS_VolLab
        image[43..54].copy_from_slice(b"TEST       ");

        // BS_FilSysType
        image[54..62].copy_from_slice(b"FAT16   ");

        // Boot signature at 510-511
        image[510] = 0x55;
        image[511] = 0xAA;
    }

    fn write_fat_table(image: &mut [u8], fat_start: usize) {
        // Entry 0: Media type in low byte
        image[fat_start..fat_start + 2].copy_from_slice(&0xFFF8u16.to_le_bytes());

        // Entry 1: End of chain marker (clean shutdown)
        image[fat_start + 2..fat_start + 4].copy_from_slice(&0xFFFFu16.to_le_bytes());

        // Rest of FAT entries are 0 (free clusters)
    }

    /// Get cluster size for the test image
    pub const fn cluster_size() -> usize {
        CLUSTER_SIZE
    }
}

/// Helper module to create FAT12 images in memory for testing
#[cfg(feature = "std")]
mod fat12_image {
    use std::io::Cursor;

    /// Sector size in bytes
    const SECTOR_SIZE: usize = 512;
    /// Sectors per cluster
    const SECTORS_PER_CLUSTER: u8 = 1;
    /// Cluster size in bytes
    const CLUSTER_SIZE: usize = SECTOR_SIZE * SECTORS_PER_CLUSTER as usize;
    /// Reserved sectors (just boot sector for FAT12)
    const RESERVED_SECTORS: u16 = 1;
    /// Number of FAT copies
    const FAT_COUNT: u8 = 2;
    /// Sectors per FAT
    const SECTORS_PER_FAT: u16 = 9;
    /// Root directory entry count (224 is typical for 1.44MB floppy)
    const ROOT_ENTRY_COUNT: u16 = 224;

    /// Create a minimal FAT12 image in memory (1.44MB floppy-like).
    ///
    /// The image has:
    /// - 512 byte sectors
    /// - 1 sector per cluster
    /// - 1 reserved sector
    /// - 2 FATs, each 9 sectors
    /// - 224 root directory entries (14 sectors)
    /// - ~2880 total sectors (1.44MB)
    /// - Cluster count < 4085 (FAT12 range)
    pub fn create_fat12_image() -> Cursor<Vec<u8>> {
        // Calculate layout
        let root_dir_sectors = (ROOT_ENTRY_COUNT as usize * 32 + SECTOR_SIZE - 1) / SECTOR_SIZE;
        let _data_start_sector = RESERVED_SECTORS as usize
            + FAT_COUNT as usize * SECTORS_PER_FAT as usize
            + root_dir_sectors;

        // Use 2880 sectors total (1.44MB floppy size) - results in ~2847 clusters (FAT12)
        let total_sectors: usize = 2880;
        let total_size = total_sectors * SECTOR_SIZE;

        let mut image = vec![0u8; total_size];

        // Write boot sector (sector 0)
        write_boot_sector(&mut image, total_sectors as u16);

        // Write FAT tables
        let fat_start = RESERVED_SECTORS as usize * SECTOR_SIZE;
        write_fat_table(&mut image, fat_start);
        // Second FAT copy
        let fat2_start = fat_start + SECTORS_PER_FAT as usize * SECTOR_SIZE;
        write_fat_table(&mut image, fat2_start);

        // Root directory is initially empty (zeroed)

        Cursor::new(image)
    }

    fn write_boot_sector(image: &mut [u8], total_sectors: u16) {
        // Jump instruction
        image[0] = 0xEB;
        image[1] = 0x3C;
        image[2] = 0x90;

        // OEM name
        image[3..11].copy_from_slice(b"HADRISFT");

        // BPB_BytsPerSec
        image[11..13].copy_from_slice(&(SECTOR_SIZE as u16).to_le_bytes());

        // BPB_SecPerClus
        image[13] = SECTORS_PER_CLUSTER;

        // BPB_RsvdSecCnt
        image[14..16].copy_from_slice(&RESERVED_SECTORS.to_le_bytes());

        // BPB_NumFATs
        image[16] = FAT_COUNT;

        // BPB_RootEntCnt (non-zero for FAT12)
        image[17..19].copy_from_slice(&ROOT_ENTRY_COUNT.to_le_bytes());

        // BPB_TotSec16
        image[19..21].copy_from_slice(&total_sectors.to_le_bytes());

        // BPB_Media (0xF0 = removable media for floppy)
        image[21] = 0xF0;

        // BPB_FATSz16 (non-zero for FAT12)
        image[22..24].copy_from_slice(&SECTORS_PER_FAT.to_le_bytes());

        // BPB_SecPerTrk (18 for 1.44MB floppy)
        image[24..26].copy_from_slice(&18u16.to_le_bytes());

        // BPB_NumHeads (2 for floppy)
        image[26..28].copy_from_slice(&2u16.to_le_bytes());

        // BPB_HiddSec
        image[28..32].copy_from_slice(&0u32.to_le_bytes());

        // BPB_TotSec32 (0 for small volumes)
        image[32..36].copy_from_slice(&0u32.to_le_bytes());

        // FAT12/16 extended fields (offset 36)
        // BS_DrvNum
        image[36] = 0x00; // Floppy

        // BS_Reserved1
        image[37] = 0;

        // BS_BootSig
        image[38] = 0x29;

        // BS_VolID
        image[39..43].copy_from_slice(&0x12345678u32.to_le_bytes());

        // BS_VolLab
        image[43..54].copy_from_slice(b"TEST       ");

        // BS_FilSysType
        image[54..62].copy_from_slice(b"FAT12   ");

        // Boot signature at 510-511
        image[510] = 0x55;
        image[511] = 0xAA;
    }

    fn write_fat_table(image: &mut [u8], fat_start: usize) {
        // FAT12 packs 2 entries into 3 bytes
        // Entry 0 and 1: media type and end of chain marker

        // Entries 0, 1: 0xFF0, 0xFFF (packed as: F0 FF FF)
        image[fat_start] = 0xF0; // Low 8 bits of entry 0
        image[fat_start + 1] = 0xFF; // High 4 bits of entry 0 (0xF) + Low 4 bits of entry 1 (0xF)
        image[fat_start + 2] = 0xFF; // High 8 bits of entry 1

        // Rest of FAT entries are 0 (free clusters)
    }

    /// Get cluster size for the test image
    pub const fn cluster_size() -> usize {
        CLUSTER_SIZE
    }
}

/// Integration tests using in-memory FAT32 images
#[cfg(feature = "std")]
mod integration_tests {
    use super::fat32_image::{cluster_size, create_fat32_image};
    use hadris_fat::{FatError, FatFs, FatFsWriteExt};

    #[test]
    fn test_open_fat32_image() {
        let image = create_fat32_image();
        let fs = FatFs::open(image).expect("Failed to open FAT32 image");

        // Should be able to get root directory
        let root = fs.root_dir();
        let entries: Vec<_> = root.entries().collect();
        // Root directory should be empty initially
        assert!(entries.is_empty(), "Root directory should be empty");
    }

    #[test]
    fn test_create_file() {
        let image = create_fat32_image();
        let fs = FatFs::open(image).expect("Failed to open FAT32 image");

        let root = fs.root_dir();

        // Create a new file
        let entry = fs
            .create_file(&root, "TEST.TXT")
            .expect("Failed to create file");

        assert!(entry.is_file());
        assert_eq!(entry.size(), 0);

        // Verify file appears in directory listing
        let root = fs.root_dir();
        let found = root.find("TEST.TXT").expect("Find failed");
        assert!(found.is_some(), "File should be found in directory");
    }

    #[test]
    fn test_create_file_already_exists() {
        let image = create_fat32_image();
        let fs = FatFs::open(image).expect("Failed to open FAT32 image");

        let root = fs.root_dir();

        // Create a file
        fs.create_file(&root, "TEST.TXT")
            .expect("Failed to create file");

        // Try to create again - should fail
        let result = fs.create_file(&root, "TEST.TXT");
        match result {
            Err(FatError::AlreadyExists) => {}
            _ => panic!("Expected AlreadyExists error"),
        }
    }

    #[test]
    fn test_write_file_content() {
        let image = create_fat32_image();
        let fs = FatFs::open(image).expect("Failed to open FAT32 image");

        let root = fs.root_dir();

        // Create a file
        let entry = fs
            .create_file(&root, "HELLO.TXT")
            .expect("Failed to create file");

        // Write content
        let content = b"Hello, FAT32 World!";
        {
            let mut writer = fs.write_file(&entry).expect("Failed to get writer");
            writer.write(content).expect("Failed to write");
            writer.finish().expect("Failed to finish");
        }

        // Re-find the file to get updated size
        let root = fs.root_dir();
        let entry = root
            .find("HELLO.TXT")
            .expect("Find failed")
            .expect("File not found");
        assert_eq!(entry.size(), content.len());

        // Read back the content
        use hadris_fat::FatFsReadExt;
        let mut reader = fs.read_file(&entry).expect("Failed to get reader");
        let mut buf = vec![0u8; content.len()];
        let mut total = 0;
        while total < buf.len() {
            let n = reader.read(&mut buf[total..]).expect("Read failed");
            if n == 0 {
                break;
            }
            total += n;
        }
        assert_eq!(&buf[..total], content);
    }

    #[test]
    fn test_write_file_multiple_clusters() {
        let image = create_fat32_image();
        let fs = FatFs::open(image).expect("Failed to open FAT32 image");

        let root = fs.root_dir();

        // Create a file
        let entry = fs
            .create_file(&root, "BIG.DAT")
            .expect("Failed to create file");

        // Write content larger than one cluster
        let cluster_sz = cluster_size();
        let content: Vec<u8> = (0..cluster_sz * 3).map(|i| (i % 256) as u8).collect();

        {
            let mut writer = fs.write_file(&entry).expect("Failed to get writer");
            writer.write(&content).expect("Failed to write");
            writer.finish().expect("Failed to finish");
        }

        // Read back and verify
        let root = fs.root_dir();
        let entry = root
            .find("BIG.DAT")
            .expect("Find failed")
            .expect("File not found");
        assert_eq!(entry.size(), content.len());

        use hadris_fat::FatFsReadExt;
        let mut reader = fs.read_file(&entry).expect("Failed to get reader");
        let read_content = reader.read_to_vec().expect("Read failed");
        assert_eq!(read_content, content);
    }

    #[test]
    fn test_create_directory() {
        let image = create_fat32_image();
        let fs = FatFs::open(image).expect("Failed to open FAT32 image");

        let root = fs.root_dir();

        // Create a directory
        let subdir = fs
            .create_dir(&root, "SUBDIR")
            .expect("Failed to create directory");

        // Verify . and .. entries exist
        let entries: Vec<_> = subdir.entries().collect();
        let names: Vec<_> = entries
            .iter()
            .filter_map(|e| e.as_ref().ok())
            .map(|e| e.name().trim_end_matches(' ').to_string())
            .collect();

        assert!(
            names.iter().any(|n| n.starts_with('.')),
            "Directory should have . entry: {:?}",
            names
        );
        assert!(
            names.iter().any(|n| n.starts_with("..")),
            "Directory should have .. entry: {:?}",
            names
        );
    }

    #[test]
    fn test_create_file_in_subdirectory() {
        let image = create_fat32_image();
        let fs = FatFs::open(image).expect("Failed to open FAT32 image");

        let root = fs.root_dir();

        // Create a directory
        let subdir = fs
            .create_dir(&root, "MYDIR")
            .expect("Failed to create directory");

        // Create a file in the subdirectory
        let entry = fs
            .create_file(&subdir, "FILE.TXT")
            .expect("Failed to create file");
        assert!(entry.is_file());

        // Verify file exists in subdirectory
        let found = subdir.find("FILE.TXT").expect("Find failed");
        assert!(found.is_some());

        // Verify file does NOT exist in root
        let root = fs.root_dir();
        let found_in_root = root.find("FILE.TXT").expect("Find failed");
        assert!(found_in_root.is_none());
    }

    #[test]
    fn test_delete_file() {
        let image = create_fat32_image();
        let fs = FatFs::open(image).expect("Failed to open FAT32 image");

        let root = fs.root_dir();

        // Create and write a file
        let entry = fs
            .create_file(&root, "DELETE.ME")
            .expect("Failed to create file");
        {
            let mut writer = fs.write_file(&entry).expect("Failed to get writer");
            writer.write(b"temporary data").expect("Failed to write");
            writer.finish().expect("Failed to finish");
        }

        // Re-find and delete
        let root = fs.root_dir();
        let entry = root
            .find("DELETE.ME")
            .expect("Find failed")
            .expect("File not found");
        fs.delete(&entry).expect("Failed to delete");

        // Verify file no longer exists
        let root = fs.root_dir();
        let found = root.find("DELETE.ME").expect("Find failed");
        assert!(found.is_none(), "File should be deleted");
    }

    #[test]
    fn test_delete_empty_directory() {
        let image = create_fat32_image();
        let fs = FatFs::open(image).expect("Failed to open FAT32 image");

        let root = fs.root_dir();

        // Create a directory
        let _subdir = fs
            .create_dir(&root, "EMPTYDIR")
            .expect("Failed to create directory");

        // Find and delete it
        let root = fs.root_dir();
        let entry = root
            .find("EMPTYDIR")
            .expect("Find failed")
            .expect("Dir not found");
        fs.delete(&entry).expect("Failed to delete empty directory");

        // Verify directory no longer exists
        let root = fs.root_dir();
        let found = root.find("EMPTYDIR").expect("Find failed");
        assert!(found.is_none(), "Directory should be deleted");
    }

    #[test]
    fn test_delete_non_empty_directory_fails() {
        let image = create_fat32_image();
        let fs = FatFs::open(image).expect("Failed to open FAT32 image");

        let root = fs.root_dir();

        // Create a directory with a file inside
        let subdir = fs
            .create_dir(&root, "HASFILE")
            .expect("Failed to create directory");
        fs.create_file(&subdir, "INSIDE.TXT")
            .expect("Failed to create file");

        // Try to delete the directory - should fail
        let root = fs.root_dir();
        let entry = root
            .find("HASFILE")
            .expect("Find failed")
            .expect("Dir not found");
        let result = fs.delete(&entry);

        match result {
            Err(FatError::DirectoryNotEmpty) => {}
            _ => panic!("Expected DirectoryNotEmpty error"),
        }
    }

    #[test]
    fn test_create_multiple_files() {
        let image = create_fat32_image();
        let fs = FatFs::open(image).expect("Failed to open FAT32 image");

        let root = fs.root_dir();

        // Create several files
        for i in 0..10 {
            let name = format!("FILE{}.TXT", i);
            // Need to truncate/pad to 8.3 format for the find
            fs.create_file(&root, &name).expect("Failed to create file");
        }

        // Verify all files exist
        let root = fs.root_dir();
        let entries: Vec<_> = root.entries().collect();
        assert_eq!(entries.len(), 10, "Should have 10 files");
    }

    #[test]
    fn test_case_insensitive_find() {
        let image = create_fat32_image();
        let fs = FatFs::open(image).expect("Failed to open FAT32 image");

        let root = fs.root_dir();

        // Create a file
        fs.create_file(&root, "MYFILE.TXT")
            .expect("Failed to create file");

        // Should find it with different cases
        let root = fs.root_dir();
        assert!(root.find("MYFILE.TXT").expect("Find failed").is_some());
        assert!(root.find("myfile.txt").expect("Find failed").is_some());
        assert!(root.find("MyFile.Txt").expect("Find failed").is_some());
    }

    #[test]
    fn test_write_then_append() {
        let image = create_fat32_image();
        let fs = FatFs::open(image).expect("Failed to open FAT32 image");

        let root = fs.root_dir();

        // Create and write initial content
        let entry = fs
            .create_file(&root, "APPEND.TXT")
            .expect("Failed to create file");
        {
            let mut writer = fs.write_file(&entry).expect("Failed to get writer");
            writer.write(b"First part. ").expect("Failed to write");
            writer.finish().expect("Failed to finish");
        }

        // Note: Currently the write implementation overwrites from the beginning.
        // A proper append would need to seek to the end first.
        // For now, we just verify the basic write/read cycle works.

        let root = fs.root_dir();
        let entry = root
            .find("APPEND.TXT")
            .expect("Find failed")
            .expect("File not found");

        use hadris_fat::FatFsReadExt;
        let mut reader = fs.read_file(&entry).expect("Failed to get reader");
        let content = reader.read_to_vec().expect("Read failed");
        assert_eq!(&content, b"First part. ");
    }
}

/// Integration tests using in-memory FAT16 images
#[cfg(feature = "std")]
mod fat16_integration_tests {
    use super::fat16_image::{cluster_size, create_fat16_image};
    use hadris_fat::{FatError, FatFs, FatFsWriteExt, FatType};

    #[test]
    fn test_open_fat16_image() {
        let image = create_fat16_image();
        let fs = FatFs::open(image).expect("Failed to open FAT16 image");

        // Verify FAT type is FAT16
        assert!(
            matches!(fs.fat_type(), FatType::Fat16),
            "Expected FAT16, got {:?}",
            fs.fat_type()
        );

        // Should be able to get root directory
        let root = fs.root_dir();
        let entries: Vec<_> = root.entries().collect();
        // Root directory should be empty initially
        assert!(entries.is_empty(), "Root directory should be empty");
    }

    #[test]
    fn test_fat16_create_file() {
        let image = create_fat16_image();
        let fs = FatFs::open(image).expect("Failed to open FAT16 image");

        let root = fs.root_dir();

        // Create a new file
        let entry = fs
            .create_file(&root, "TEST.TXT")
            .expect("Failed to create file");

        assert!(entry.is_file());
        assert_eq!(entry.size(), 0);

        // Verify file appears in directory listing
        let root = fs.root_dir();
        let found = root.find("TEST.TXT").expect("Find failed");
        assert!(found.is_some(), "File should be found in directory");
    }

    #[test]
    fn test_fat16_write_file_content() {
        let image = create_fat16_image();
        let fs = FatFs::open(image).expect("Failed to open FAT16 image");

        let root = fs.root_dir();

        // Create a file
        let entry = fs
            .create_file(&root, "HELLO.TXT")
            .expect("Failed to create file");

        // Write content
        let content = b"Hello, FAT16 World!";
        {
            let mut writer = fs.write_file(&entry).expect("Failed to get writer");
            writer.write(content).expect("Failed to write");
            writer.finish().expect("Failed to finish");
        }

        // Re-find the file to get updated size
        let root = fs.root_dir();
        let entry = root
            .find("HELLO.TXT")
            .expect("Find failed")
            .expect("File not found");
        assert_eq!(entry.size(), content.len());

        // Read back the content
        use hadris_fat::FatFsReadExt;
        let mut reader = fs.read_file(&entry).expect("Failed to get reader");
        let mut buf = vec![0u8; content.len()];
        let mut total = 0;
        while total < buf.len() {
            let n = reader.read(&mut buf[total..]).expect("Read failed");
            if n == 0 {
                break;
            }
            total += n;
        }
        assert_eq!(&buf[..total], content);
    }

    #[test]
    fn test_fat16_write_file_multiple_clusters() {
        let image = create_fat16_image();
        let fs = FatFs::open(image).expect("Failed to open FAT16 image");

        let root = fs.root_dir();

        // Create a file
        let entry = fs
            .create_file(&root, "BIG.DAT")
            .expect("Failed to create file");

        // Write content larger than one cluster
        let cluster_sz = cluster_size();
        let content: Vec<u8> = (0..cluster_sz * 3).map(|i| (i % 256) as u8).collect();

        {
            let mut writer = fs.write_file(&entry).expect("Failed to get writer");
            writer.write(&content).expect("Failed to write");
            writer.finish().expect("Failed to finish");
        }

        // Read back and verify
        let root = fs.root_dir();
        let entry = root
            .find("BIG.DAT")
            .expect("Find failed")
            .expect("File not found");
        assert_eq!(entry.size(), content.len());

        use hadris_fat::FatFsReadExt;
        let mut reader = fs.read_file(&entry).expect("Failed to get reader");
        let read_content = reader.read_to_vec().expect("Read failed");
        assert_eq!(read_content, content);
    }

    #[test]
    fn test_fat16_create_directory() {
        let image = create_fat16_image();
        let fs = FatFs::open(image).expect("Failed to open FAT16 image");

        let root = fs.root_dir();

        // Create a directory
        let subdir = fs
            .create_dir(&root, "SUBDIR")
            .expect("Failed to create directory");

        // Verify . and .. entries exist
        let entries: Vec<_> = subdir.entries().collect();
        let names: Vec<_> = entries
            .iter()
            .filter_map(|e| e.as_ref().ok())
            .map(|e| e.name().trim_end_matches(' ').to_string())
            .collect();

        assert!(
            names.iter().any(|n| n.starts_with('.')),
            "Directory should have . entry: {:?}",
            names
        );
        assert!(
            names.iter().any(|n| n.starts_with("..")),
            "Directory should have .. entry: {:?}",
            names
        );
    }

    #[test]
    fn test_fat16_create_file_in_subdirectory() {
        let image = create_fat16_image();
        let fs = FatFs::open(image).expect("Failed to open FAT16 image");

        let root = fs.root_dir();

        // Create a directory
        let subdir = fs
            .create_dir(&root, "MYDIR")
            .expect("Failed to create directory");

        // Create a file in the subdirectory
        let entry = fs
            .create_file(&subdir, "FILE.TXT")
            .expect("Failed to create file");
        assert!(entry.is_file());

        // Verify file exists in subdirectory
        let found = subdir.find("FILE.TXT").expect("Find failed");
        assert!(found.is_some());

        // Verify file does NOT exist in root
        let root = fs.root_dir();
        let found_in_root = root.find("FILE.TXT").expect("Find failed");
        assert!(found_in_root.is_none());
    }

    #[test]
    fn test_fat16_delete_file() {
        let image = create_fat16_image();
        let fs = FatFs::open(image).expect("Failed to open FAT16 image");

        let root = fs.root_dir();

        // Create and write a file
        let entry = fs
            .create_file(&root, "DELETE.ME")
            .expect("Failed to create file");
        {
            let mut writer = fs.write_file(&entry).expect("Failed to get writer");
            writer.write(b"temporary data").expect("Failed to write");
            writer.finish().expect("Failed to finish");
        }

        // Re-find and delete
        let root = fs.root_dir();
        let entry = root
            .find("DELETE.ME")
            .expect("Find failed")
            .expect("File not found");
        fs.delete(&entry).expect("Failed to delete");

        // Verify file no longer exists
        let root = fs.root_dir();
        let found = root.find("DELETE.ME").expect("Find failed");
        assert!(found.is_none(), "File should be deleted");
    }

    #[test]
    fn test_fat16_create_multiple_files() {
        let image = create_fat16_image();
        let fs = FatFs::open(image).expect("Failed to open FAT16 image");

        let root = fs.root_dir();

        // Create several files
        for i in 0..10 {
            let name = format!("FILE{}.TXT", i);
            fs.create_file(&root, &name).expect("Failed to create file");
        }

        // Verify all files exist
        let root = fs.root_dir();
        let entries: Vec<_> = root.entries().collect();
        assert_eq!(entries.len(), 10, "Should have 10 files");
    }

    #[test]
    fn test_fat16_file_already_exists() {
        let image = create_fat16_image();
        let fs = FatFs::open(image).expect("Failed to open FAT16 image");

        let root = fs.root_dir();

        // Create a file
        fs.create_file(&root, "TEST.TXT")
            .expect("Failed to create file");

        // Try to create again - should fail
        let result = fs.create_file(&root, "TEST.TXT");
        match result {
            Err(FatError::AlreadyExists) => {}
            _ => panic!("Expected AlreadyExists error"),
        }
    }
}

/// Integration tests using in-memory FAT12 images
#[cfg(feature = "std")]
mod fat12_integration_tests {
    use super::fat12_image::{cluster_size, create_fat12_image};
    use hadris_fat::{FatError, FatFs, FatFsWriteExt, FatType};

    #[test]
    fn test_open_fat12_image() {
        let image = create_fat12_image();
        let fs = FatFs::open(image).expect("Failed to open FAT12 image");

        // Verify FAT type is FAT12
        assert!(
            matches!(fs.fat_type(), FatType::Fat12),
            "Expected FAT12, got {:?}",
            fs.fat_type()
        );

        // Should be able to get root directory
        let root = fs.root_dir();
        let entries: Vec<_> = root.entries().collect();
        // Root directory should be empty initially
        assert!(entries.is_empty(), "Root directory should be empty");
    }

    #[test]
    fn test_fat12_create_file() {
        let image = create_fat12_image();
        let fs = FatFs::open(image).expect("Failed to open FAT12 image");

        let root = fs.root_dir();

        // Create a new file
        let entry = fs
            .create_file(&root, "TEST.TXT")
            .expect("Failed to create file");

        assert!(entry.is_file());
        assert_eq!(entry.size(), 0);

        // Verify file appears in directory listing
        let root = fs.root_dir();
        let found = root.find("TEST.TXT").expect("Find failed");
        assert!(found.is_some(), "File should be found in directory");
    }

    #[test]
    fn test_fat12_write_file_content() {
        let image = create_fat12_image();
        let fs = FatFs::open(image).expect("Failed to open FAT12 image");

        let root = fs.root_dir();

        // Create a file
        let entry = fs
            .create_file(&root, "HELLO.TXT")
            .expect("Failed to create file");

        // Write content
        let content = b"Hello, FAT12 World!";
        {
            let mut writer = fs.write_file(&entry).expect("Failed to get writer");
            writer.write(content).expect("Failed to write");
            writer.finish().expect("Failed to finish");
        }

        // Re-find the file to get updated size
        let root = fs.root_dir();
        let entry = root
            .find("HELLO.TXT")
            .expect("Find failed")
            .expect("File not found");
        assert_eq!(entry.size(), content.len());

        // Read back the content
        use hadris_fat::FatFsReadExt;
        let mut reader = fs.read_file(&entry).expect("Failed to get reader");
        let mut buf = vec![0u8; content.len()];
        let mut total = 0;
        while total < buf.len() {
            let n = reader.read(&mut buf[total..]).expect("Read failed");
            if n == 0 {
                break;
            }
            total += n;
        }
        assert_eq!(&buf[..total], content);
    }

    #[test]
    fn test_fat12_write_file_multiple_clusters() {
        let image = create_fat12_image();
        let fs = FatFs::open(image).expect("Failed to open FAT12 image");

        let root = fs.root_dir();

        // Create a file
        let entry = fs
            .create_file(&root, "BIG.DAT")
            .expect("Failed to create file");

        // Write content larger than one cluster
        let cluster_sz = cluster_size();
        let content: Vec<u8> = (0..cluster_sz * 3).map(|i| (i % 256) as u8).collect();

        {
            let mut writer = fs.write_file(&entry).expect("Failed to get writer");
            writer.write(&content).expect("Failed to write");
            writer.finish().expect("Failed to finish");
        }

        // Read back and verify
        let root = fs.root_dir();
        let entry = root
            .find("BIG.DAT")
            .expect("Find failed")
            .expect("File not found");
        assert_eq!(entry.size(), content.len());

        use hadris_fat::FatFsReadExt;
        let mut reader = fs.read_file(&entry).expect("Failed to get reader");
        let read_content = reader.read_to_vec().expect("Read failed");
        assert_eq!(read_content, content);
    }

    #[test]
    fn test_fat12_create_directory() {
        let image = create_fat12_image();
        let fs = FatFs::open(image).expect("Failed to open FAT12 image");

        let root = fs.root_dir();

        // Create a directory
        let subdir = fs
            .create_dir(&root, "SUBDIR")
            .expect("Failed to create directory");

        // Verify . and .. entries exist
        let entries: Vec<_> = subdir.entries().collect();
        let names: Vec<_> = entries
            .iter()
            .filter_map(|e| e.as_ref().ok())
            .map(|e| e.name().trim_end_matches(' ').to_string())
            .collect();

        assert!(
            names.iter().any(|n| n.starts_with('.')),
            "Directory should have . entry: {:?}",
            names
        );
        assert!(
            names.iter().any(|n| n.starts_with("..")),
            "Directory should have .. entry: {:?}",
            names
        );
    }

    #[test]
    fn test_fat12_create_file_in_subdirectory() {
        let image = create_fat12_image();
        let fs = FatFs::open(image).expect("Failed to open FAT12 image");

        let root = fs.root_dir();

        // Create a directory
        let subdir = fs
            .create_dir(&root, "MYDIR")
            .expect("Failed to create directory");

        // Create a file in the subdirectory
        let entry = fs
            .create_file(&subdir, "FILE.TXT")
            .expect("Failed to create file");
        assert!(entry.is_file());

        // Verify file exists in subdirectory
        let found = subdir.find("FILE.TXT").expect("Find failed");
        assert!(found.is_some());

        // Verify file does NOT exist in root
        let root = fs.root_dir();
        let found_in_root = root.find("FILE.TXT").expect("Find failed");
        assert!(found_in_root.is_none());
    }

    #[test]
    fn test_fat12_delete_file() {
        let image = create_fat12_image();
        let fs = FatFs::open(image).expect("Failed to open FAT12 image");

        let root = fs.root_dir();

        // Create and write a file
        let entry = fs
            .create_file(&root, "DELETE.ME")
            .expect("Failed to create file");
        {
            let mut writer = fs.write_file(&entry).expect("Failed to get writer");
            writer.write(b"temporary data").expect("Failed to write");
            writer.finish().expect("Failed to finish");
        }

        // Re-find and delete
        let root = fs.root_dir();
        let entry = root
            .find("DELETE.ME")
            .expect("Find failed")
            .expect("File not found");
        fs.delete(&entry).expect("Failed to delete");

        // Verify file no longer exists
        let root = fs.root_dir();
        let found = root.find("DELETE.ME").expect("Find failed");
        assert!(found.is_none(), "File should be deleted");
    }

    #[test]
    fn test_fat12_create_multiple_files() {
        let image = create_fat12_image();
        let fs = FatFs::open(image).expect("Failed to open FAT12 image");

        let root = fs.root_dir();

        // Create several files
        for i in 0..10 {
            let name = format!("FILE{}.TXT", i);
            fs.create_file(&root, &name).expect("Failed to create file");
        }

        // Verify all files exist
        let root = fs.root_dir();
        let entries: Vec<_> = root.entries().collect();
        assert_eq!(entries.len(), 10, "Should have 10 files");
    }

    #[test]
    fn test_fat12_file_already_exists() {
        let image = create_fat12_image();
        let fs = FatFs::open(image).expect("Failed to open FAT12 image");

        let root = fs.root_dir();

        // Create a file
        fs.create_file(&root, "TEST.TXT")
            .expect("Failed to create file");

        // Try to create again - should fail
        let result = fs.create_file(&root, "TEST.TXT");
        match result {
            Err(FatError::AlreadyExists) => {}
            _ => panic!("Expected AlreadyExists error"),
        }
    }

    /// Test FAT12 specific: 12-bit entry encoding edge cases
    #[test]
    fn test_fat12_cluster_chain() {
        let image = create_fat12_image();
        let fs = FatFs::open(image).expect("Failed to open FAT12 image");

        let root = fs.root_dir();

        // Create a file that spans multiple clusters to test FAT12 cluster chain traversal
        let cluster_sz = cluster_size();
        // Use 5 clusters to test both even and odd cluster number handling
        let content: Vec<u8> = (0..cluster_sz * 5).map(|i| (i % 256) as u8).collect();

        let entry = fs
            .create_file(&root, "CHAIN.DAT")
            .expect("Failed to create file");
        {
            let mut writer = fs.write_file(&entry).expect("Failed to get writer");
            writer.write(&content).expect("Failed to write");
            writer.finish().expect("Failed to finish");
        }

        // Read back and verify
        let root = fs.root_dir();
        let entry = root
            .find("CHAIN.DAT")
            .expect("Find failed")
            .expect("File not found");
        assert_eq!(entry.size(), content.len());

        use hadris_fat::FatFsReadExt;
        let mut reader = fs.read_file(&entry).expect("Failed to get reader");
        let read_content = reader.read_to_vec().expect("Read failed");
        assert_eq!(read_content, content, "FAT12 cluster chain read mismatch");
    }
}