shadowforge 0.3.3

Quantum-resistant steganography toolkit for journalists and whistleblowers
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
//! Steganography technique adapters implementing `EmbedTechnique` port.

use crate::domain::errors::{DeniableError, StegoError};
use crate::domain::ports::{DeniableEmbedder, EmbedTechnique, ExtractTechnique};
use crate::domain::types::{
    Capacity, CoverMedia, CoverMediaKind, DeniableKeySet, DeniablePayloadPair, Payload,
    StegoTechnique,
};
use rand::seq::SliceRandom;
use rand_chacha::ChaCha20Rng;
use rand_core::SeedableRng;
use sha2::{Digest, Sha256};

/// LSB image steganography adapter for PNG/BMP.
///
/// Embeds payload in the least significant bits of RGB channels only
/// (alpha channel is untouched). Header encodes 32-bit big-endian payload length.
#[derive(Debug, Default)]
pub struct LsbImage;

impl LsbImage {
    /// Create a new LSB image embedder.
    #[must_use]
    pub const fn new() -> Self {
        Self
    }
}

impl EmbedTechnique for LsbImage {
    fn technique(&self) -> StegoTechnique {
        StegoTechnique::LsbImage
    }

    fn capacity(&self, cover: &CoverMedia) -> Result<Capacity, StegoError> {
        // Only PNG and BMP are supported
        match cover.kind {
            CoverMediaKind::PngImage | CoverMediaKind::BmpImage => {}
            _ => {
                return Err(StegoError::UnsupportedCoverType {
                    reason: format!("LSB image requires PNG or BMP, got {:?}", cover.kind),
                });
            }
        }

        // Parse dimensions from metadata
        let width: u32 = cover
            .metadata
            .get("width")
            .ok_or_else(|| StegoError::MalformedCoverData {
                reason: "missing width metadata".to_string(),
            })?
            .parse()
            .map_err(
                |e: std::num::ParseIntError| StegoError::MalformedCoverData {
                    reason: format!("invalid width: {e}"),
                },
            )?;

        let height: u32 = cover
            .metadata
            .get("height")
            .ok_or_else(|| StegoError::MalformedCoverData {
                reason: "missing height metadata".to_string(),
            })?
            .parse()
            .map_err(
                |e: std::num::ParseIntError| StegoError::MalformedCoverData {
                    reason: format!("invalid height: {e}"),
                },
            )?;

        let pixel_count =
            width
                .checked_mul(height)
                .ok_or_else(|| StegoError::MalformedCoverData {
                    reason: "pixel count overflow".to_string(),
                })?;

        // Capacity: 3 bits per pixel (R, G, B), minus 32 bits for header
        // = (pixel_count * 3 - 32) / 8 bytes
        let bits = pixel_count
            .checked_mul(3)
            .and_then(|b| b.checked_sub(32))
            .ok_or_else(|| StegoError::MalformedCoverData {
                reason: "capacity calculation overflow".to_string(),
            })?;

        let bytes = u64::from(bits / 8);

        Ok(Capacity {
            bytes,
            technique: StegoTechnique::LsbImage,
        })
    }

    fn embed(&self, mut cover: CoverMedia, payload: &Payload) -> Result<CoverMedia, StegoError> {
        // Check cover type
        match cover.kind {
            CoverMediaKind::PngImage | CoverMediaKind::BmpImage => {}
            _ => {
                return Err(StegoError::UnsupportedCoverType {
                    reason: format!("LSB image requires PNG or BMP, got {:?}", cover.kind),
                });
            }
        }

        // Check capacity
        let cap = self.capacity(&cover)?;
        let payload_len = payload.as_bytes().len() as u64;
        if payload_len > cap.bytes {
            return Err(StegoError::PayloadTooLarge {
                needed: payload_len,
                available: cap.bytes,
            });
        }

        // Check that payload length fits in 32-bit header
        if payload_len > u64::from(u32::MAX) {
            return Err(StegoError::PayloadTooLarge {
                needed: payload_len,
                available: u64::from(u32::MAX),
            });
        }

        // Get mutable access to pixel data
        let data = cover.data.to_vec();
        let mut pixels = data;

        // Embed 32-bit big-endian payload length in first 32 LSBs
        #[expect(
            clippy::cast_possible_truncation,
            reason = "checked above: payload_len <= u32::MAX"
        )]
        let len_bytes = (payload_len as u32).to_be_bytes();
        for (byte_idx, byte) in len_bytes.iter().enumerate() {
            for bit_idx in 0..8 {
                let bit = (byte >> (7 - bit_idx)) & 1;
                let pixel_idx = byte_idx * 8 + bit_idx;

                // RGB only, skip alpha (every 4th byte)
                let channel_idx = pixel_idx / 3;
                let rgb_offset = pixel_idx % 3;
                let byte_pos = channel_idx * 4 + rgb_offset;

                let pixel =
                    pixels
                        .get_mut(byte_pos)
                        .ok_or_else(|| StegoError::MalformedCoverData {
                            reason: "pixel index out of bounds".to_string(),
                        })?;
                *pixel = (*pixel & 0xFE) | bit;
            }
        }

        // Embed payload bits starting after header (32 bits)
        let payload_bytes = payload.as_bytes();
        for (byte_idx, byte) in payload_bytes.iter().enumerate() {
            for bit_idx in 0..8 {
                let bit = (byte >> (7 - bit_idx)) & 1;
                let pixel_idx = 32 + byte_idx * 8 + bit_idx;

                // RGB only, skip alpha
                let channel_idx = pixel_idx / 3;
                let rgb_offset = pixel_idx % 3;
                let byte_pos = channel_idx * 4 + rgb_offset;

                let pixel =
                    pixels
                        .get_mut(byte_pos)
                        .ok_or_else(|| StegoError::MalformedCoverData {
                            reason: "pixel index out of bounds".to_string(),
                        })?;
                *pixel = (*pixel & 0xFE) | bit;
            }
        }

        cover.data = pixels.into();
        Ok(cover)
    }
}

impl ExtractTechnique for LsbImage {
    fn technique(&self) -> StegoTechnique {
        StegoTechnique::LsbImage
    }

    fn extract(&self, cover: &CoverMedia) -> Result<Payload, StegoError> {
        // Check cover type
        match cover.kind {
            CoverMediaKind::PngImage | CoverMediaKind::BmpImage => {}
            _ => {
                return Err(StegoError::UnsupportedCoverType {
                    reason: format!("LSB image requires PNG or BMP, got {:?}", cover.kind),
                });
            }
        }

        let pixels = cover.data.as_ref();

        // Extract 32-bit big-endian payload length from first 32 LSBs
        let mut len_bytes = [0u8; 4];
        for (byte_idx, len_byte) in len_bytes.iter_mut().enumerate() {
            for bit_idx in 0..8 {
                let pixel_idx = byte_idx * 8 + bit_idx;

                // RGB only, skip alpha
                let channel_idx = pixel_idx / 3;
                let rgb_offset = pixel_idx % 3;
                let byte_pos = channel_idx * 4 + rgb_offset;

                let bit = pixels
                    .get(byte_pos)
                    .ok_or_else(|| StegoError::MalformedCoverData {
                        reason: "pixel index out of bounds".to_string(),
                    })?
                    & 1;
                *len_byte |= bit << (7 - bit_idx);
            }
        }

        let payload_len = u32::from_be_bytes(len_bytes) as usize;

        // Extract payload bits
        let mut payload_bytes = vec![0u8; payload_len];
        for (byte_idx, payload_byte) in payload_bytes.iter_mut().enumerate() {
            for bit_idx in 0..8 {
                let pixel_idx = 32 + byte_idx * 8 + bit_idx;

                // RGB only, skip alpha
                let channel_idx = pixel_idx / 3;
                let rgb_offset = pixel_idx % 3;
                let byte_pos = channel_idx * 4 + rgb_offset;

                let bit = pixels
                    .get(byte_pos)
                    .ok_or_else(|| StegoError::MalformedCoverData {
                        reason: "pixel index out of bounds".to_string(),
                    })?
                    & 1;
                *payload_byte |= bit << (7 - bit_idx);
            }
        }

        Ok(Payload::from_bytes(payload_bytes))
    }
}

/// DCT-based JPEG steganography adapter (STUB).
///
/// **NOT YET IMPLEMENTED**: Requires a pure-Rust JPEG library that exposes
/// DCT coefficients without unsafe code. Current Rust JPEG libraries either:
/// - Decode to pixels only (jpeg-decoder, image crate)
/// - Require unsafe bindings (mozjpeg-sys, libjpeg-turbo-sys)
///
/// TODO(T12): Implement DCT coefficient access and modification:
/// - Parse JPEG to access non-zero AC DCT coefficients
/// - Embed payload in LSBs of coefficients (skip DC and zeros)
/// - Preserve quantization and Huffman tables
/// - Re-encode JPEG with modified coefficients
#[derive(Debug, Default)]
pub struct DctJpeg;

impl DctJpeg {
    /// Create a new DCT JPEG embedder.
    #[must_use]
    pub const fn new() -> Self {
        Self
    }
}

impl EmbedTechnique for DctJpeg {
    fn technique(&self) -> StegoTechnique {
        StegoTechnique::DctJpeg
    }

    fn capacity(&self, _cover: &CoverMedia) -> Result<Capacity, StegoError> {
        Err(StegoError::UnsupportedCoverType {
            reason: "DCT JPEG steganography not yet implemented (requires DCT coefficient access)"
                .to_string(),
        })
    }

    fn embed(&self, _cover: CoverMedia, _payload: &Payload) -> Result<CoverMedia, StegoError> {
        Err(StegoError::UnsupportedCoverType {
            reason: "DCT JPEG steganography not yet implemented (requires DCT coefficient access)"
                .to_string(),
        })
    }
}

impl ExtractTechnique for DctJpeg {
    fn technique(&self) -> StegoTechnique {
        StegoTechnique::DctJpeg
    }

    fn extract(&self, _cover: &CoverMedia) -> Result<Payload, StegoError> {
        Err(StegoError::UnsupportedCoverType {
            reason: "DCT JPEG steganography not yet implemented (requires DCT coefficient access)"
                .to_string(),
        })
    }
}

/// Palette-based steganography adapter for GIF/PNG indexed images (STUB).
///
/// **NOT YET IMPLEMENTED**: Requires palette extraction from indexed color images.
/// The `image` crate converts all images to RGBA8, losing original palette data.
///
/// TODO(T13): Implement palette steganography:
/// - Extract palette data from GIF/PNG indexed color images
/// - Store palette as bytes in `CoverMedia.metadata["palette"]`
/// - Embed payload in LSBs of palette R/G/B bytes
/// - Capacity: (`palette_size` * 3) / 8 bytes
/// - Re-encode image with modified palette (pixel indices unchanged)
/// - Requires format-specific handling (GIF vs indexed PNG)
#[derive(Debug, Default)]
pub struct PaletteStego;

impl PaletteStego {
    /// Create a new palette steganography embedder.
    #[must_use]
    pub const fn new() -> Self {
        Self
    }
}

impl EmbedTechnique for PaletteStego {
    fn technique(&self) -> StegoTechnique {
        StegoTechnique::Palette
    }

    fn capacity(&self, _cover: &CoverMedia) -> Result<Capacity, StegoError> {
        Err(StegoError::UnsupportedCoverType {
            reason: "Palette steganography not yet implemented (requires palette extraction)"
                .to_string(),
        })
    }

    fn embed(&self, _cover: CoverMedia, _payload: &Payload) -> Result<CoverMedia, StegoError> {
        Err(StegoError::UnsupportedCoverType {
            reason: "Palette steganography not yet implemented (requires palette extraction)"
                .to_string(),
        })
    }
}

impl ExtractTechnique for PaletteStego {
    fn technique(&self) -> StegoTechnique {
        StegoTechnique::Palette
    }

    fn extract(&self, _cover: &CoverMedia) -> Result<Payload, StegoError> {
        Err(StegoError::UnsupportedCoverType {
            reason: "Palette steganography not yet implemented (requires palette extraction)"
                .to_string(),
        })
    }
}

/// LSB audio steganography adapter for WAV files.
///
/// Embeds payload in the least significant bits of i16 audio samples.
/// Header encodes 32-bit big-endian payload length in first 32 sample LSBs.
#[derive(Debug, Default)]
pub struct LsbAudio;

impl LsbAudio {
    /// Create a new LSB audio embedder.
    #[must_use]
    pub const fn new() -> Self {
        Self
    }
}

impl EmbedTechnique for LsbAudio {
    fn technique(&self) -> StegoTechnique {
        StegoTechnique::LsbAudio
    }

    fn capacity(&self, cover: &CoverMedia) -> Result<Capacity, StegoError> {
        // Only WAV audio is supported
        if cover.kind != CoverMediaKind::WavAudio {
            return Err(StegoError::UnsupportedCoverType {
                reason: format!("LSB audio requires WAV, got {:?}", cover.kind),
            });
        }

        // Sample count is data length / 2 (i16 = 2 bytes)
        let sample_count = cover.data.len() / 2;

        // Need at least 32 samples for header
        if sample_count < 32 {
            return Err(StegoError::MalformedCoverData {
                reason: "audio too short for LSB embedding (need at least 32 samples)".to_string(),
            });
        }

        // Capacity: (sample_count - 32) / 8 bytes
        let capacity_bits =
            sample_count
                .checked_sub(32)
                .ok_or_else(|| StegoError::MalformedCoverData {
                    reason: "capacity calculation underflow".to_string(),
                })?;

        let bytes = (capacity_bits / 8) as u64;

        Ok(Capacity {
            bytes,
            technique: StegoTechnique::LsbAudio,
        })
    }

    fn embed(&self, mut cover: CoverMedia, payload: &Payload) -> Result<CoverMedia, StegoError> {
        // Check cover type
        if cover.kind != CoverMediaKind::WavAudio {
            return Err(StegoError::UnsupportedCoverType {
                reason: format!("LSB audio requires WAV, got {:?}", cover.kind),
            });
        }

        // Check capacity
        let cap = self.capacity(&cover)?;
        let payload_len = payload.as_bytes().len() as u64;
        if payload_len > cap.bytes {
            return Err(StegoError::PayloadTooLarge {
                needed: payload_len,
                available: cap.bytes,
            });
        }

        // Check that payload length fits in 32-bit header
        if payload_len > u64::from(u32::MAX) {
            return Err(StegoError::PayloadTooLarge {
                needed: payload_len,
                available: u64::from(u32::MAX),
            });
        }

        // Get mutable access to sample data (i16 little-endian)
        let mut samples = cover.data.to_vec();

        // Embed 32-bit big-endian payload length in first 32 sample LSBs
        #[expect(
            clippy::cast_possible_truncation,
            reason = "checked above: payload_len <= u32::MAX"
        )]
        let len_bytes = (payload_len as u32).to_be_bytes();
        for (byte_idx, byte) in len_bytes.iter().enumerate() {
            for bit_idx in 0..8 {
                let bit = (byte >> (7 - bit_idx)) & 1;
                let sample_idx = byte_idx * 8 + bit_idx;

                // Modify LSB of i16 sample (little-endian)
                let byte_pos = sample_idx * 2; // i16 = 2 bytes
                let sample =
                    samples
                        .get_mut(byte_pos)
                        .ok_or_else(|| StegoError::MalformedCoverData {
                            reason: "sample index out of bounds".to_string(),
                        })?;
                *sample = (*sample & 0xFE) | bit;
            }
        }

        // Embed payload bits starting after header (32 samples)
        let payload_bytes = payload.as_bytes();
        for (byte_idx, byte) in payload_bytes.iter().enumerate() {
            for bit_idx in 0..8 {
                let bit = (byte >> (7 - bit_idx)) & 1;
                let sample_idx = 32 + byte_idx * 8 + bit_idx;

                let byte_pos = sample_idx * 2;
                let sample =
                    samples
                        .get_mut(byte_pos)
                        .ok_or_else(|| StegoError::MalformedCoverData {
                            reason: "sample index out of bounds".to_string(),
                        })?;
                *sample = (*sample & 0xFE) | bit;
            }
        }

        cover.data = samples.into();
        Ok(cover)
    }
}

impl ExtractTechnique for LsbAudio {
    fn technique(&self) -> StegoTechnique {
        StegoTechnique::LsbAudio
    }

    fn extract(&self, cover: &CoverMedia) -> Result<Payload, StegoError> {
        // Check cover type
        if cover.kind != CoverMediaKind::WavAudio {
            return Err(StegoError::UnsupportedCoverType {
                reason: format!("LSB audio requires WAV, got {:?}", cover.kind),
            });
        }

        let samples = cover.data.as_ref();

        // Need at least 32 samples for header
        if samples.len() < 64 {
            // 32 samples * 2 bytes
            return Err(StegoError::MalformedCoverData {
                reason: "audio too short to extract payload".to_string(),
            });
        }

        // Extract 32-bit big-endian payload length from first 32 sample LSBs
        let mut len_bytes = [0u8; 4];
        for (byte_idx, len_byte) in len_bytes.iter_mut().enumerate() {
            for bit_idx in 0..8 {
                let sample_idx = byte_idx * 8 + bit_idx;
                let byte_pos = sample_idx * 2;

                let bit = samples
                    .get(byte_pos)
                    .ok_or_else(|| StegoError::MalformedCoverData {
                        reason: "sample index out of bounds".to_string(),
                    })?
                    & 1;
                *len_byte |= bit << (7 - bit_idx);
            }
        }

        let payload_len = u32::from_be_bytes(len_bytes) as usize;

        // Sanity check payload length
        let max_samples = samples.len() / 2;
        if payload_len > (max_samples.saturating_sub(32)) / 8 {
            return Err(StegoError::MalformedCoverData {
                reason: format!("invalid payload length: {payload_len}"),
            });
        }

        // Extract payload bits
        let mut payload_bytes = vec![0u8; payload_len];
        for (byte_idx, payload_byte) in payload_bytes.iter_mut().enumerate() {
            for bit_idx in 0..8 {
                let sample_idx = 32 + byte_idx * 8 + bit_idx;
                let byte_pos = sample_idx * 2;

                let bit = samples
                    .get(byte_pos)
                    .ok_or_else(|| StegoError::MalformedCoverData {
                        reason: "sample index out of bounds".to_string(),
                    })?
                    & 1;
                *payload_byte |= bit << (7 - bit_idx);
            }
        }

        Ok(Payload::from_bytes(payload_bytes))
    }
}

/// Phase encoding (DSSS) audio steganography adapter (STUB).
///
/// **NOT YET IMPLEMENTED**: Requires FFT/IFFT and phase manipulation.
///
/// TODO(T14): Implement phase encoding:
/// - Segment audio into blocks
/// - Apply FFT to each segment
/// - Embed one bit per segment by phase shift
/// - Adaptive alpha: scale shift by segment energy
/// - Apply IFFT to reconstruct samples
/// - Requires audio DSP library (rustfft or similar)
#[derive(Debug, Default)]
pub struct PhaseEncoding;

impl PhaseEncoding {
    /// Create a new phase encoding embedder.
    #[must_use]
    pub const fn new() -> Self {
        Self
    }
}

impl EmbedTechnique for PhaseEncoding {
    fn technique(&self) -> StegoTechnique {
        StegoTechnique::PhaseEncoding
    }

    fn capacity(&self, _cover: &CoverMedia) -> Result<Capacity, StegoError> {
        Err(StegoError::UnsupportedCoverType {
            reason: "Phase encoding not yet implemented (requires FFT/phase manipulation)"
                .to_string(),
        })
    }

    fn embed(&self, _cover: CoverMedia, _payload: &Payload) -> Result<CoverMedia, StegoError> {
        Err(StegoError::UnsupportedCoverType {
            reason: "Phase encoding not yet implemented (requires FFT/phase manipulation)"
                .to_string(),
        })
    }
}

impl ExtractTechnique for PhaseEncoding {
    fn technique(&self) -> StegoTechnique {
        StegoTechnique::PhaseEncoding
    }

    fn extract(&self, _cover: &CoverMedia) -> Result<Payload, StegoError> {
        Err(StegoError::UnsupportedCoverType {
            reason: "Phase encoding not yet implemented (requires FFT/phase manipulation)"
                .to_string(),
        })
    }
}

/// Echo hiding audio steganography adapter (STUB).
///
/// **NOT YET IMPLEMENTED**: Requires echo synthesis and autocorrelation.
///
/// TODO(T14): Implement echo hiding:
/// - Two echo delays (d0, d1) for bit 0/1
/// - Embed by adding delayed echo to audio
/// - Extract via autocorrelation peak detection
/// - Use `array_windows` for autocorrelation computation
/// - Requires audio DSP operations
#[derive(Debug, Default)]
pub struct EchoHiding;

impl EchoHiding {
    /// Create a new echo hiding embedder.
    #[must_use]
    pub const fn new() -> Self {
        Self
    }
}

impl EmbedTechnique for EchoHiding {
    fn technique(&self) -> StegoTechnique {
        StegoTechnique::EchoHiding
    }

    fn capacity(&self, _cover: &CoverMedia) -> Result<Capacity, StegoError> {
        Err(StegoError::UnsupportedCoverType {
            reason: "Echo hiding not yet implemented (requires echo synthesis and autocorrelation)"
                .to_string(),
        })
    }

    fn embed(&self, _cover: CoverMedia, _payload: &Payload) -> Result<CoverMedia, StegoError> {
        Err(StegoError::UnsupportedCoverType {
            reason: "Echo hiding not yet implemented (requires echo synthesis and autocorrelation)"
                .to_string(),
        })
    }
}

impl ExtractTechnique for EchoHiding {
    fn technique(&self) -> StegoTechnique {
        StegoTechnique::EchoHiding
    }

    fn extract(&self, _cover: &CoverMedia) -> Result<Payload, StegoError> {
        Err(StegoError::UnsupportedCoverType {
            reason: "Echo hiding not yet implemented (requires echo synthesis and autocorrelation)"
                .to_string(),
        })
    }
}

/// Zero-width character text steganography adapter (STUB).
///
/// **NOT YET IMPLEMENTED**: Zero-width Unicode characters (ZWSP, ZWNJ, ZWJ, etc.)
/// have complex grapheme clustering rules that make reliable embedding/extraction
/// difficult. Format characters can be combined with adjacent characters by the
/// Unicode grapheme segmentation algorithm in context-dependent ways.
///
/// TODO(T15): Implement zero-width text steganography:
/// - Research Unicode-safe zero-width character pairs that remain separate graphemes
/// - Consider alternative approaches (variation selectors, combining marks)
/// - Extensive testing with all Unicode scripts (Arabic, Thai, Devanagari, emoji ZWJ sequences)
/// - Validate grapheme-cluster safety across all contexts
#[derive(Debug, Default)]
pub struct ZeroWidthText;

impl ZeroWidthText {
    /// Create a new zero-width text embedder.
    #[must_use]
    pub const fn new() -> Self {
        Self
    }
}

impl EmbedTechnique for ZeroWidthText {
    fn technique(&self) -> StegoTechnique {
        StegoTechnique::ZeroWidthText
    }

    fn capacity(&self, _cover: &CoverMedia) -> Result<Capacity, StegoError> {
        Err(StegoError::UnsupportedCoverType {
            reason: "Zero-width text steganography not yet implemented (Unicode grapheme segmentation complexity)".to_string(),
        })
    }

    fn embed(&self, _cover: CoverMedia, _payload: &Payload) -> Result<CoverMedia, StegoError> {
        Err(StegoError::UnsupportedCoverType {
            reason: "Zero-width text steganography not yet implemented (Unicode grapheme segmentation complexity)".to_string(),
        })
    }
}

impl ExtractTechnique for ZeroWidthText {
    fn technique(&self) -> StegoTechnique {
        StegoTechnique::ZeroWidthText
    }

    fn extract(&self, _cover: &CoverMedia) -> Result<Payload, StegoError> {
        Err(StegoError::UnsupportedCoverType {
            reason: "Zero-width text steganography not yet implemented (Unicode grapheme segmentation complexity)".to_string(),
        })
    }
}

// ─── Dual-Payload Deniable Steganography ─────────────────────────────────────

/// Dual-payload deniable steganography adapter.
///
/// Embeds two independent payloads (real and decoy) into a single cover using
/// key-derived pseudo-random patterns. Each key produces a deterministic but
/// non-overlapping set of embedding positions, ensuring that:
///
/// - Extracting with the primary key yields the real payload
/// - Extracting with the decoy key yields the decoy payload
/// - No observer can prove which payload is "real" vs "decoy"
///
/// The implementation uses `ChaCha20` PRNG seeded with SHA-256 hashes of the keys
/// to generate reproducible embedding patterns.
pub struct DualPayloadEmbedder;

impl Default for DualPayloadEmbedder {
    fn default() -> Self {
        Self
    }
}

impl DualPayloadEmbedder {
    /// Create a new dual-payload embedder.
    #[must_use]
    pub const fn new() -> Self {
        Self
    }

    /// Derive a 32-byte seed from a key and channel using SHA-256.
    ///
    /// The channel tag ensures different seeds for primary (channel 0) and decoy (channel 1),
    /// preventing pattern overlap.
    fn derive_seed_with_channel(key: &[u8], channel: u8) -> [u8; 32] {
        let mut hasher = Sha256::new();
        hasher.update(key);
        hasher.update([channel]);
        hasher.finalize().into()
    }

    /// Generate a pseudo-random permutation of indices for embedding.
    ///
    /// Returns a vector of `count` indices in the range `[0, total)`, shuffled
    /// deterministically based on the `seed`. The indices are NOT sorted, preserving
    /// the pseudo-random access pattern for better security.
    fn generate_pattern(seed: [u8; 32], total: usize, count: usize) -> Vec<usize> {
        let mut rng = ChaCha20Rng::from_seed(seed);
        let mut indices: Vec<usize> = (0..total).collect();
        indices.shuffle(&mut rng);
        indices.truncate(count);
        indices
    }

    /// Embed a single payload into the cover at specified bit positions.
    fn embed_at_positions(
        cover_data: &mut [u8],
        payload: &[u8],
        positions: &[usize],
    ) -> Result<(), DeniableError> {
        let payload_bits = payload.len() * 8;

        if payload_bits > positions.len() {
            return Err(DeniableError::InsufficientCapacity);
        }

        // Embed each bit of the payload at its designated position
        for (bit_idx, &pos) in positions.iter().enumerate().take(payload_bits) {
            let payload_byte_idx = bit_idx / 8;
            let payload_bit_idx = 7 - (bit_idx % 8); // MSB-first
            let payload_byte = payload
                .get(payload_byte_idx)
                .ok_or(DeniableError::InsufficientCapacity)?;
            let payload_bit = (payload_byte >> payload_bit_idx) & 1;

            let cover_byte_idx = pos / 8;
            let cover_bit_idx = pos % 8;

            // Set the LSB at this position
            let byte = cover_data
                .get_mut(cover_byte_idx)
                .ok_or(DeniableError::InsufficientCapacity)?;
            if payload_bit == 1 {
                *byte |= 1 << cover_bit_idx;
            } else {
                *byte &= !(1 << cover_bit_idx);
            }
        }

        Ok(())
    }

    /// Extract a payload from the cover at specified bit positions.
    fn extract_from_positions(
        cover_data: &[u8],
        positions: &[usize],
        payload_len: usize,
    ) -> Result<Vec<u8>, DeniableError> {
        let payload_bits = payload_len * 8;

        if payload_bits > positions.len() {
            return Err(DeniableError::ExtractionFailed {
                reason: "insufficient embedding positions for expected payload length".to_string(),
            });
        }

        let mut payload = vec![0u8; payload_len];

        for (bit_idx, &pos) in positions.iter().enumerate().take(payload_bits) {
            let cover_byte_idx = pos / 8;
            let cover_bit_idx = pos % 8;
            let cover_byte =
                cover_data
                    .get(cover_byte_idx)
                    .ok_or_else(|| DeniableError::ExtractionFailed {
                        reason: "cover byte index out of bounds".to_string(),
                    })?;
            let cover_bit = (cover_byte >> cover_bit_idx) & 1;

            let payload_byte_idx = bit_idx / 8;
            let payload_bit_idx = 7 - (bit_idx % 8); // MSB-first

            if cover_bit == 1 {
                let byte = payload.get_mut(payload_byte_idx).ok_or_else(|| {
                    DeniableError::ExtractionFailed {
                        reason: "payload byte index out of bounds".to_string(),
                    }
                })?;
                *byte |= 1 << payload_bit_idx;
            }
        }

        Ok(payload)
    }
}

impl DeniableEmbedder for DualPayloadEmbedder {
    fn embed_dual(
        &self,
        mut cover: CoverMedia,
        pair: &DeniablePayloadPair,
        keys: &DeniableKeySet,
        _embedder: &dyn EmbedTechnique,
    ) -> Result<CoverMedia, DeniableError> {
        let cover_bytes = cover.data.len();
        let cover_bits = cover_bytes * 8;

        // Split cover into two non-overlapping channels to avoid interference
        // Channel 0: even bit indices (0, 2, 4, ...)
        // Channel 1: odd bit indices (1, 3, 5, ...)
        let channel_capacity = cover_bits / 2;

        // Calculate required capacity (both payloads + length headers)
        // Header: 4 bytes (32 bits) for each payload length
        let real_total_bits = (pair.real_payload.len() + 4) * 8;
        let decoy_total_bits = (pair.decoy_payload.len() + 4) * 8;

        if real_total_bits > channel_capacity || decoy_total_bits > channel_capacity {
            return Err(DeniableError::InsufficientCapacity);
        }

        // Derive channel-tagged seeds
        // Primary key uses channel 0 (even bits)
        // Decoy key uses channel 1 (odd bits)
        let primary_seed = Self::derive_seed_with_channel(&keys.primary_key, 0);
        let decoy_seed = Self::derive_seed_with_channel(&keys.decoy_key, 1);

        // Generate patterns within each channel
        // Channel 0: select from even-indexed bits
        let primary_positions =
            Self::generate_pattern(primary_seed, channel_capacity, real_total_bits)
                .into_iter()
                .map(|i| i * 2) // Map to even indices
                .collect::<Vec<_>>();

        // Channel 1: select from odd-indexed bits
        let decoy_positions =
            Self::generate_pattern(decoy_seed, channel_capacity, decoy_total_bits)
                .into_iter()
                .map(|i| i * 2 + 1) // Map to odd indices
                .collect::<Vec<_>>();

        // Prepare payloads with length headers (32-bit big-endian)
        let real_len = pair.real_payload.len();
        let decoy_len = pair.decoy_payload.len();

        #[expect(
            clippy::cast_possible_truncation,
            reason = "payload size checked against u32::MAX in capacity validation"
        )]
        let mut real_with_header = (real_len as u32).to_be_bytes().to_vec();
        real_with_header.extend_from_slice(&pair.real_payload);

        #[expect(
            clippy::cast_possible_truncation,
            reason = "payload size checked against u32::MAX in capacity validation"
        )]
        let mut decoy_with_header = (decoy_len as u32).to_be_bytes().to_vec();
        decoy_with_header.extend_from_slice(&pair.decoy_payload);

        // Get mutable access to cover data
        let mut cover_data = cover.data.to_vec();

        // Embed both payloads (guaranteed non-overlapping due to channel separation)
        Self::embed_at_positions(&mut cover_data, &real_with_header, &primary_positions).map_err(
            |e| DeniableError::EmbedFailed {
                reason: format!("real payload embed failed: {e}"),
            },
        )?;

        Self::embed_at_positions(&mut cover_data, &decoy_with_header, &decoy_positions).map_err(
            |e| DeniableError::EmbedFailed {
                reason: format!("decoy payload embed failed: {e}"),
            },
        )?;

        cover.data = cover_data.into();
        Ok(cover)
    }

    fn extract_with_key(
        &self,
        stego: &CoverMedia,
        key: &[u8],
        _extractor: &dyn ExtractTechnique,
    ) -> Result<Payload, DeniableError> {
        let cover_bytes = stego.data.len();
        let cover_bits = cover_bytes * 8;
        let channel_capacity = cover_bits / 2;

        // Try both channels - we don't know which one was used for this key
        // Channel 0: even bits
        // Channel 1: odd bits

        for channel in 0..2 {
            let seed = Self::derive_seed_with_channel(key, channel);

            // Generate pattern for header extraction
            let header_bits = 32;
            let header_positions = Self::generate_pattern(seed, channel_capacity, header_bits)
                .into_iter()
                .map(|i| i * 2 + channel as usize) // Map to channel's bit indices
                .collect::<Vec<_>>();

            if header_positions.len() < header_bits {
                continue; // Try next channel
            }

            // Extract length header
            let Ok(header_bytes) =
                Self::extract_from_positions(stego.data.as_ref(), &header_positions, 4)
            else {
                continue; // Try next channel
            };

            let Ok(header_arr) = <[u8; 4]>::try_from(header_bytes.as_slice()) else {
                continue;
            };
            let payload_len = u32::from_be_bytes(header_arr) as usize;

            // Validate payload length is reasonable
            // Reject 0-length payloads (likely garbage from wrong channel)
            if payload_len == 0 {
                continue; // Try next channel
            }

            let max_payload_len = channel_capacity / 8;
            if payload_len > max_payload_len {
                continue; // Try next channel
            }

            // Generate full pattern including header + payload
            let total_bits = (payload_len + 4) * 8;
            if total_bits > channel_capacity {
                continue; // Try next channel
            }

            let positions = Self::generate_pattern(seed, channel_capacity, total_bits)
                .into_iter()
                .map(|i| i * 2 + channel as usize)
                .collect::<Vec<_>>();

            // Extract full payload
            let Ok(with_header) =
                Self::extract_from_positions(stego.data.as_ref(), &positions, payload_len + 4)
            else {
                continue; // Try next channel
            };

            // Verify header matches
            let Ok(extracted_arr) = <[u8; 4]>::try_from(with_header.get(..4).unwrap_or_default())
            else {
                continue;
            };
            let extracted_header = u32::from_be_bytes(extracted_arr) as usize;

            if extracted_header == payload_len {
                // Success! Return payload without header
                let payload_data = with_header.get(4..).unwrap_or_default();
                return Ok(Payload::from_bytes(payload_data.to_vec()));
            }
        }

        // Failed to extract from both channels
        Err(DeniableError::ExtractionFailed {
            reason: "failed to extract valid payload from either channel".to_string(),
        })
    }
}

// TODO(T11): Implement PdfPageStegoService after LsbImage is available
// This service will:
// - Render PDF pages to PNG images
// - RS-encode payload into N shards (N = page count)
// - Embed one shard per page using LsbImage
// - Rebuild PDF from stego pages

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

    type TestResult = Result<(), Box<dyn std::error::Error>>;

    #[test]
    fn test_lsb_image_roundtrip_256x256() -> TestResult {
        let embedder = LsbImage::new();

        // Create 256x256 white RGBA image
        let width = 256_u32;
        let height = 256_u32;
        let pixel_count = width * height;
        let data = vec![255u8; (pixel_count * 4) as usize]; // RGBA

        let mut metadata = std::collections::HashMap::new();
        metadata.insert("width".to_string(), width.to_string());
        metadata.insert("height".to_string(), height.to_string());

        let cover = CoverMedia {
            kind: CoverMediaKind::PngImage,
            data: data.into(),
            metadata,
        };

        // 64-byte payload
        let payload = Payload::from_bytes(vec![0xAB; 64]);

        // Embed
        let stego = embedder.embed(cover.clone(), &payload)?;

        // Verify pixel changes are ±1
        let orig_pixels = cover.data.as_ref();
        let stego_pixels = stego.data.as_ref();
        for (i, (orig, stego_val)) in orig_pixels.iter().zip(stego_pixels.iter()).enumerate() {
            let diff = orig.abs_diff(*stego_val);
            assert!(
                diff <= 1,
                "pixel at index {i} changed by more than 1: {orig} -> {stego_val}"
            );
        }

        // Extract
        let extracted = embedder.extract(&stego)?;
        assert_eq!(extracted.as_bytes(), payload.as_bytes());
        Ok(())
    }

    #[test]
    fn test_lsb_image_capacity_10x10() -> TestResult {
        let embedder = LsbImage::new();

        let width = 10_u32;
        let height = 10_u32;
        let pixel_count = width * height;
        let data = vec![0u8; (pixel_count * 4) as usize];

        let mut metadata = std::collections::HashMap::new();
        metadata.insert("width".to_string(), width.to_string());
        metadata.insert("height".to_string(), height.to_string());

        let cover = CoverMedia {
            kind: CoverMediaKind::PngImage,
            data: data.into(),
            metadata,
        };

        let cap = embedder.capacity(&cover)?;

        // 10x10 = 100 pixels
        // 100 * 3 = 300 bits
        // 300 - 32 (header) = 268 bits
        // 268 / 8 = 33 bytes
        assert_eq!(cap.bytes, 33);
        assert_eq!(cap.technique, StegoTechnique::LsbImage);
        Ok(())
    }

    #[test]
    fn test_lsb_image_insufficient_capacity() {
        let embedder = LsbImage::new();

        let width = 10_u32;
        let height = 10_u32;
        let pixel_count = width * height;
        let data = vec![0u8; (pixel_count * 4) as usize];

        let mut metadata = std::collections::HashMap::new();
        metadata.insert("width".to_string(), width.to_string());
        metadata.insert("height".to_string(), height.to_string());

        let cover = CoverMedia {
            kind: CoverMediaKind::PngImage,
            data: data.into(),
            metadata,
        };

        // Try to embed 100 bytes (capacity is only 33)
        let payload = Payload::from_bytes(vec![0xAB; 100]);

        let result = embedder.embed(cover, &payload);
        assert!(matches!(result, Err(StegoError::PayloadTooLarge { .. })));
    }

    #[test]
    fn test_lsb_image_bmp_support() -> TestResult {
        let embedder = LsbImage::new();

        let width = 100_u32;
        let height = 100_u32;
        let pixel_count = width * height;
        let data = vec![128u8; (pixel_count * 4) as usize];

        let mut metadata = std::collections::HashMap::new();
        metadata.insert("width".to_string(), width.to_string());
        metadata.insert("height".to_string(), height.to_string());

        let cover = CoverMedia {
            kind: CoverMediaKind::BmpImage,
            data: data.into(),
            metadata,
        };

        let payload = Payload::from_bytes(vec![1, 2, 3, 4, 5]);

        // Embed
        let stego = embedder.embed(cover, &payload)?;

        // Extract
        let extracted = embedder.extract(&stego)?;
        assert_eq!(extracted.as_bytes(), payload.as_bytes());
        Ok(())
    }

    #[test]
    fn test_dct_jpeg_stub_returns_not_implemented() {
        let embedder = DctJpeg::new();

        let cover = CoverMedia {
            kind: CoverMediaKind::JpegImage,
            data: vec![].into(),
            metadata: std::collections::HashMap::new(),
        };

        let payload = Payload::from_bytes(vec![1, 2, 3]);

        // Should return UnsupportedCoverType error indicating not implemented
        let result = embedder.embed(cover.clone(), &payload);
        assert!(matches!(
            result,
            Err(StegoError::UnsupportedCoverType { .. })
        ));

        let result = embedder.extract(&cover);
        assert!(matches!(
            result,
            Err(StegoError::UnsupportedCoverType { .. })
        ));

        let result = embedder.capacity(&cover);
        assert!(matches!(
            result,
            Err(StegoError::UnsupportedCoverType { .. })
        ));
    }

    #[test]
    fn test_palette_stego_stub_returns_not_implemented() {
        let embedder = PaletteStego::new();

        let cover = CoverMedia {
            kind: CoverMediaKind::GifImage,
            data: vec![].into(),
            metadata: std::collections::HashMap::new(),
        };

        let payload = Payload::from_bytes(vec![1, 2, 3]);

        // Should return UnsupportedCoverType error indicating not implemented
        let result = embedder.embed(cover.clone(), &payload);
        assert!(matches!(
            result,
            Err(StegoError::UnsupportedCoverType { .. })
        ));

        let result = embedder.extract(&cover);
        assert!(matches!(
            result,
            Err(StegoError::UnsupportedCoverType { .. })
        ));

        let result = embedder.capacity(&cover);
        assert!(matches!(
            result,
            Err(StegoError::UnsupportedCoverType { .. })
        ));
    }

    #[test]
    fn test_lsb_audio_roundtrip() -> TestResult {
        let embedder = LsbAudio::new();

        // Create 1s of 44100 Hz 16-bit mono silence (44100 samples)
        let sample_rate = 44100;
        let sample_count = sample_rate; // 1 second
        let mut data = Vec::new();
        for _ in 0..sample_count {
            data.extend_from_slice(&0_i16.to_le_bytes());
        }

        let mut metadata = std::collections::HashMap::new();
        metadata.insert("sample_rate".to_string(), sample_rate.to_string());
        metadata.insert("channels".to_string(), "1".to_string());
        metadata.insert("bits_per_sample".to_string(), "16".to_string());

        let cover = CoverMedia {
            kind: CoverMediaKind::WavAudio,
            data: data.into(),
            metadata,
        };

        // 512-byte payload
        let payload = Payload::from_bytes(vec![0xAB; 512]);

        // Embed
        let stego = embedder.embed(cover, &payload)?;

        // Extract
        let extracted = embedder.extract(&stego)?;
        assert_eq!(extracted.as_bytes(), payload.as_bytes());
        Ok(())
    }

    #[test]
    fn test_lsb_audio_capacity() -> TestResult {
        let embedder = LsbAudio::new();

        // 1000 samples
        let sample_count = 1000;
        let mut data = Vec::new();
        for _ in 0..sample_count {
            data.extend_from_slice(&0_i16.to_le_bytes());
        }

        let mut metadata = std::collections::HashMap::new();
        metadata.insert("sample_rate".to_string(), "44100".to_string());
        metadata.insert("channels".to_string(), "1".to_string());
        metadata.insert("bits_per_sample".to_string(), "16".to_string());

        let cover = CoverMedia {
            kind: CoverMediaKind::WavAudio,
            data: data.into(),
            metadata,
        };

        let cap = embedder.capacity(&cover)?;

        // 1000 samples - 32 (header) = 968 bits / 8 = 121 bytes
        assert_eq!(cap.bytes, 121);
        assert_eq!(cap.technique, StegoTechnique::LsbAudio);
        Ok(())
    }

    #[test]
    fn test_lsb_audio_insufficient_capacity() {
        let embedder = LsbAudio::new();

        // 100 samples (very short audio)
        let sample_count = 100;
        let mut data = Vec::new();
        for _ in 0..sample_count {
            data.extend_from_slice(&0_i16.to_le_bytes());
        }

        let mut metadata = std::collections::HashMap::new();
        metadata.insert("sample_rate".to_string(), "44100".to_string());
        metadata.insert("channels".to_string(), "1".to_string());
        metadata.insert("bits_per_sample".to_string(), "16".to_string());

        let cover = CoverMedia {
            kind: CoverMediaKind::WavAudio,
            data: data.into(),
            metadata,
        };

        // Try to embed 100 bytes (capacity is only 8 bytes)
        let payload = Payload::from_bytes(vec![0xAB; 100]);

        let result = embedder.embed(cover, &payload);
        assert!(matches!(result, Err(StegoError::PayloadTooLarge { .. })));
    }

    #[test]
    fn test_phase_encoding_stub_returns_not_implemented() {
        let embedder = PhaseEncoding::new();

        let mut metadata = std::collections::HashMap::new();
        metadata.insert("sample_rate".to_string(), "44100".to_string());
        metadata.insert("channels".to_string(), "1".to_string());
        metadata.insert("bits_per_sample".to_string(), "16".to_string());

        let cover = CoverMedia {
            kind: CoverMediaKind::WavAudio,
            data: vec![0; 1000].into(),
            metadata,
        };

        let payload = Payload::from_bytes(vec![1, 2, 3]);

        let result = embedder.embed(cover.clone(), &payload);
        assert!(matches!(
            result,
            Err(StegoError::UnsupportedCoverType { .. })
        ));

        let result = embedder.extract(&cover);
        assert!(matches!(
            result,
            Err(StegoError::UnsupportedCoverType { .. })
        ));

        let result = embedder.capacity(&cover);
        assert!(matches!(
            result,
            Err(StegoError::UnsupportedCoverType { .. })
        ));
    }

    #[test]
    fn test_echo_hiding_stub_returns_not_implemented() {
        let embedder = EchoHiding::new();

        let mut metadata = std::collections::HashMap::new();
        metadata.insert("sample_rate".to_string(), "44100".to_string());
        metadata.insert("channels".to_string(), "1".to_string());
        metadata.insert("bits_per_sample".to_string(), "16".to_string());

        let cover = CoverMedia {
            kind: CoverMediaKind::WavAudio,
            data: vec![0; 1000].into(),
            metadata,
        };

        let payload = Payload::from_bytes(vec![1, 2, 3]);

        let result = embedder.embed(cover.clone(), &payload);
        assert!(matches!(
            result,
            Err(StegoError::UnsupportedCoverType { .. })
        ));

        let result = embedder.extract(&cover);
        assert!(matches!(
            result,
            Err(StegoError::UnsupportedCoverType { .. })
        ));

        let result = embedder.capacity(&cover);
        assert!(matches!(
            result,
            Err(StegoError::UnsupportedCoverType { .. })
        ));
    }

    #[test]
    fn test_zero_width_text_stub_returns_not_implemented() {
        let embedder = ZeroWidthText::new();

        let cover = CoverMedia {
            kind: CoverMediaKind::PlainText,
            data: b"Hello, world!".to_vec().into(),
            metadata: std::collections::HashMap::new(),
        };

        let payload = Payload::from_bytes(vec![1, 2, 3]);

        let result = embedder.embed(cover.clone(), &payload);
        assert!(matches!(
            result,
            Err(StegoError::UnsupportedCoverType { .. })
        ));

        let result = embedder.extract(&cover);
        assert!(matches!(
            result,
            Err(StegoError::UnsupportedCoverType { .. })
        ));

        let result = embedder.capacity(&cover);
        assert!(matches!(
            result,
            Err(StegoError::UnsupportedCoverType { .. })
        ));
    }

    #[test]
    fn test_dual_payload_roundtrip() -> TestResult {
        let embedder = DualPayloadEmbedder::new();
        let lsb_image = LsbImage::new();

        // Create a 100x100 pixel RGB image (30000 bytes)
        let width = 100u32;
        let height = 100u32;
        let pixel_count = (width * height) as usize;
        let data = vec![0u8; pixel_count * 3]; // RGB

        let mut metadata = std::collections::HashMap::new();
        metadata.insert("width".to_string(), width.to_string());
        metadata.insert("height".to_string(), height.to_string());
        metadata.insert("channels".to_string(), "3".to_string());

        let cover = CoverMedia {
            kind: CoverMediaKind::PngImage,
            data: data.into(),
            metadata,
        };

        // Create payload pair
        let real_payload = b"This is the REAL secret message".to_vec();
        let decoy_payload = b"This is just a decoy".to_vec();

        let pair = DeniablePayloadPair {
            real_payload: real_payload.clone(),
            decoy_payload: decoy_payload.clone(),
        };

        // Create key set
        let keys = DeniableKeySet {
            primary_key: b"primary_key_12345".to_vec(),
            decoy_key: b"decoy_key_67890".to_vec(),
        };

        // Embed dual payloads
        let stego = embedder.embed_dual(cover, &pair, &keys, &lsb_image)?;

        // Extract with primary key
        let extracted_real = embedder.extract_with_key(&stego, &keys.primary_key, &lsb_image)?;
        assert_eq!(extracted_real.as_bytes(), &real_payload);

        // Extract with decoy key
        let extracted_decoy = embedder.extract_with_key(&stego, &keys.decoy_key, &lsb_image)?;
        assert_eq!(extracted_decoy.as_bytes(), &decoy_payload);
        Ok(())
    }

    #[test]
    fn test_dual_payload_insufficient_capacity() {
        let embedder = DualPayloadEmbedder::new();
        let lsb_image = LsbImage::new();

        // Create a very small cover (10x10 pixels = 300 bytes)
        let width = 10u32;
        let height = 10u32;
        let pixel_count = (width * height) as usize;
        let data = vec![0u8; pixel_count * 3];

        let mut metadata = std::collections::HashMap::new();
        metadata.insert("width".to_string(), width.to_string());
        metadata.insert("height".to_string(), height.to_string());
        metadata.insert("channels".to_string(), "3".to_string());

        let cover = CoverMedia {
            kind: CoverMediaKind::PngImage,
            data: data.into(),
            metadata,
        };

        // Create large payloads that won't fit
        let real_payload = vec![0u8; 200];
        let decoy_payload = vec![0u8; 200];

        let pair = DeniablePayloadPair {
            real_payload,
            decoy_payload,
        };

        let keys = DeniableKeySet {
            primary_key: b"primary_key".to_vec(),
            decoy_key: b"decoy_key".to_vec(),
        };

        // Should fail with InsufficientCapacity
        let result = embedder.embed_dual(cover, &pair, &keys, &lsb_image);
        assert!(matches!(result, Err(DeniableError::InsufficientCapacity)));
    }

    #[test]
    fn test_dual_payload_different_keys_produce_different_results() -> TestResult {
        let embedder = DualPayloadEmbedder::new();
        let lsb_image = LsbImage::new();

        // Create cover
        let width = 100u32;
        let height = 100u32;
        let pixel_count = (width * height) as usize;
        let data = vec![0u8; pixel_count * 3];

        let mut metadata = std::collections::HashMap::new();
        metadata.insert("width".to_string(), width.to_string());
        metadata.insert("height".to_string(), height.to_string());
        metadata.insert("channels".to_string(), "3".to_string());

        let cover = CoverMedia {
            kind: CoverMediaKind::PngImage,
            data: data.into(),
            metadata,
        };

        let real_payload = b"Real secret".to_vec();
        let decoy_payload = b"Fake data".to_vec();

        let pair = DeniablePayloadPair {
            real_payload: real_payload.clone(),
            decoy_payload: decoy_payload.clone(),
        };

        let keys = DeniableKeySet {
            primary_key: b"key1".to_vec(),
            decoy_key: b"key2".to_vec(),
        };

        let stego = embedder.embed_dual(cover, &pair, &keys, &lsb_image)?;

        // Extract with primary key
        let extracted1 = embedder.extract_with_key(&stego, &keys.primary_key, &lsb_image)?;

        // Extract with decoy key
        let extracted2 = embedder.extract_with_key(&stego, &keys.decoy_key, &lsb_image)?;

        // Should be different
        assert_ne!(extracted1.as_bytes(), extracted2.as_bytes());
        assert_eq!(extracted1.as_bytes(), &real_payload);
        assert_eq!(extracted2.as_bytes(), &decoy_payload);
        Ok(())
    }

    #[test]
    fn test_dual_payload_wrong_key_produces_garbage() -> TestResult {
        let embedder = DualPayloadEmbedder::new();
        let lsb_image = LsbImage::new();

        // Create cover
        let width = 100u32;
        let height = 100u32;
        let pixel_count = (width * height) as usize;
        let data = vec![0u8; pixel_count * 3];

        let mut metadata = std::collections::HashMap::new();
        metadata.insert("width".to_string(), width.to_string());
        metadata.insert("height".to_string(), height.to_string());
        metadata.insert("channels".to_string(), "3".to_string());

        let cover = CoverMedia {
            kind: CoverMediaKind::PngImage,
            data: data.into(),
            metadata,
        };

        let real_payload = b"Real secret message".to_vec();
        let decoy_payload = b"Decoy message".to_vec();

        let pair = DeniablePayloadPair {
            real_payload: real_payload.clone(),
            decoy_payload: decoy_payload.clone(),
        };

        let keys = DeniableKeySet {
            primary_key: b"correct_primary".to_vec(),
            decoy_key: b"correct_decoy".to_vec(),
        };

        let stego = embedder.embed_dual(cover, &pair, &keys, &lsb_image)?;

        // Try extracting with a wrong key
        let wrong_key = b"wrong_key";
        let result = embedder.extract_with_key(&stego, wrong_key, &lsb_image);

        // Extraction may succeed but produce garbage, or may fail with ExtractionFailed
        // depending on what the garbage header decodes to
        match result {
            Ok(extracted) => {
                // If it succeeds, the extracted data should not match either payload
                assert_ne!(extracted.as_bytes(), &real_payload);
                assert_ne!(extracted.as_bytes(), &decoy_payload);
            }
            Err(DeniableError::ExtractionFailed { .. }) => {
                // This is also acceptable - garbage header caused extraction to fail
            }
            Err(e) => return Err(e.into()),
        }
        Ok(())
    }

    // ─── Additional edge-case stego tests ─────────────────────────────────

    #[test]
    fn test_lsb_image_wrong_cover_type_embed() {
        let embedder = LsbImage::new();
        let cover = CoverMedia {
            kind: CoverMediaKind::WavAudio,
            data: vec![0u8; 100].into(),
            metadata: std::collections::HashMap::new(),
        };
        let payload = Payload::from_bytes(vec![1, 2, 3]);
        let result = embedder.embed(cover, &payload);
        assert!(matches!(
            result,
            Err(StegoError::UnsupportedCoverType { .. })
        ));
    }

    #[test]
    fn test_lsb_image_wrong_cover_type_extract() {
        let embedder = LsbImage::new();
        let cover = CoverMedia {
            kind: CoverMediaKind::JpegImage,
            data: vec![0u8; 100].into(),
            metadata: std::collections::HashMap::new(),
        };
        let result = embedder.extract(&cover);
        assert!(matches!(
            result,
            Err(StegoError::UnsupportedCoverType { .. })
        ));
    }

    #[test]
    fn test_lsb_image_missing_width_metadata() {
        let embedder = LsbImage::new();
        let mut metadata = std::collections::HashMap::new();
        metadata.insert("height".to_string(), "100".to_string());
        metadata.insert("channels".to_string(), "3".to_string());
        let cover = CoverMedia {
            kind: CoverMediaKind::PngImage,
            data: vec![0u8; 30000].into(),
            metadata,
        };
        let result = embedder.capacity(&cover);
        assert!(matches!(result, Err(StegoError::MalformedCoverData { .. })));
    }

    #[test]
    fn test_lsb_image_missing_height_metadata() {
        let embedder = LsbImage::new();
        let mut metadata = std::collections::HashMap::new();
        metadata.insert("width".to_string(), "100".to_string());
        metadata.insert("channels".to_string(), "3".to_string());
        let cover = CoverMedia {
            kind: CoverMediaKind::PngImage,
            data: vec![0u8; 30000].into(),
            metadata,
        };
        let result = embedder.capacity(&cover);
        assert!(matches!(result, Err(StegoError::MalformedCoverData { .. })));
    }

    #[test]
    fn test_lsb_image_invalid_width_metadata() {
        let embedder = LsbImage::new();
        let mut metadata = std::collections::HashMap::new();
        metadata.insert("width".to_string(), "not_a_number".to_string());
        metadata.insert("height".to_string(), "100".to_string());
        metadata.insert("channels".to_string(), "3".to_string());
        let cover = CoverMedia {
            kind: CoverMediaKind::PngImage,
            data: vec![0u8; 30000].into(),
            metadata,
        };
        let result = embedder.capacity(&cover);
        assert!(matches!(result, Err(StegoError::MalformedCoverData { .. })));
    }

    #[test]
    fn test_lsb_image_wrong_cover_type_capacity() {
        let embedder = LsbImage::new();
        let cover = CoverMedia {
            kind: CoverMediaKind::GifImage,
            data: vec![0u8; 100].into(),
            metadata: std::collections::HashMap::new(),
        };
        let result = embedder.capacity(&cover);
        assert!(matches!(
            result,
            Err(StegoError::UnsupportedCoverType { .. })
        ));
    }

    #[test]
    fn test_lsb_audio_wrong_cover_type() {
        let embedder = LsbAudio::new();
        let cover = CoverMedia {
            kind: CoverMediaKind::PngImage,
            data: vec![0u8; 1000].into(),
            metadata: std::collections::HashMap::new(),
        };
        let payload = Payload::from_bytes(vec![1, 2, 3]);
        let result = embedder.embed(cover, &payload);
        assert!(matches!(
            result,
            Err(StegoError::UnsupportedCoverType { .. })
        ));
    }

    #[test]
    fn test_lsb_audio_wrong_cover_type_extract() {
        let embedder = LsbAudio::new();
        let cover = CoverMedia {
            kind: CoverMediaKind::PngImage,
            data: vec![0u8; 1000].into(),
            metadata: std::collections::HashMap::new(),
        };
        let result = embedder.extract(&cover);
        assert!(matches!(
            result,
            Err(StegoError::UnsupportedCoverType { .. })
        ));
    }

    #[test]
    fn test_lsb_audio_wrong_cover_type_capacity() {
        let embedder = LsbAudio::new();
        let cover = CoverMedia {
            kind: CoverMediaKind::PngImage,
            data: vec![0u8; 1000].into(),
            metadata: std::collections::HashMap::new(),
        };
        let result = embedder.capacity(&cover);
        assert!(matches!(
            result,
            Err(StegoError::UnsupportedCoverType { .. })
        ));
    }

    // ─── Stub technique tests ─────────────────────────────────────────────

    fn dummy_cover() -> CoverMedia {
        CoverMedia {
            kind: CoverMediaKind::PngImage,
            data: vec![0u8; 64].into(),
            metadata: std::collections::HashMap::new(),
        }
    }

    #[test]
    fn dct_jpeg_stub_capacity_returns_error() {
        let dct = DctJpeg::new();
        assert!(dct.capacity(&dummy_cover()).is_err());
        assert_eq!(EmbedTechnique::technique(&dct), StegoTechnique::DctJpeg);
    }

    #[test]
    fn dct_jpeg_stub_embed_returns_error() {
        let dct = DctJpeg::new();
        let result = dct.embed(dummy_cover(), &Payload::from_bytes(vec![1]));
        assert!(matches!(
            result,
            Err(StegoError::UnsupportedCoverType { .. })
        ));
    }

    #[test]
    fn dct_jpeg_stub_extract_returns_error() {
        let dct = DctJpeg::new();
        let result = dct.extract(&dummy_cover());
        assert!(matches!(
            result,
            Err(StegoError::UnsupportedCoverType { .. })
        ));
        assert_eq!(ExtractTechnique::technique(&dct), StegoTechnique::DctJpeg);
    }

    #[test]
    fn palette_stego_stub_capacity_returns_error() {
        let pal = PaletteStego::new();
        assert!(pal.capacity(&dummy_cover()).is_err());
        assert_eq!(EmbedTechnique::technique(&pal), StegoTechnique::Palette);
    }

    #[test]
    fn palette_stego_stub_embed_returns_error() {
        let pal = PaletteStego::new();
        let result = pal.embed(dummy_cover(), &Payload::from_bytes(vec![1]));
        assert!(matches!(
            result,
            Err(StegoError::UnsupportedCoverType { .. })
        ));
    }

    #[test]
    fn palette_stego_stub_extract_returns_error() {
        let pal = PaletteStego::new();
        let result = pal.extract(&dummy_cover());
        assert!(matches!(
            result,
            Err(StegoError::UnsupportedCoverType { .. })
        ));
        assert_eq!(ExtractTechnique::technique(&pal), StegoTechnique::Palette);
    }

    #[test]
    fn phase_encoding_stub_capacity_returns_error() {
        let pe = PhaseEncoding::new();
        assert!(pe.capacity(&dummy_cover()).is_err());
        assert_eq!(
            EmbedTechnique::technique(&pe),
            StegoTechnique::PhaseEncoding
        );
    }

    #[test]
    fn phase_encoding_stub_embed_returns_error() {
        let pe = PhaseEncoding::new();
        let result = pe.embed(dummy_cover(), &Payload::from_bytes(vec![1]));
        assert!(matches!(
            result,
            Err(StegoError::UnsupportedCoverType { .. })
        ));
    }

    #[test]
    fn phase_encoding_stub_extract_returns_error() {
        let pe = PhaseEncoding::new();
        let result = pe.extract(&dummy_cover());
        assert!(matches!(
            result,
            Err(StegoError::UnsupportedCoverType { .. })
        ));
        assert_eq!(
            ExtractTechnique::technique(&pe),
            StegoTechnique::PhaseEncoding
        );
    }

    #[test]
    fn echo_hiding_stub_capacity_returns_error() {
        let eh = EchoHiding::new();
        assert!(eh.capacity(&dummy_cover()).is_err());
        assert_eq!(EmbedTechnique::technique(&eh), StegoTechnique::EchoHiding);
    }

    #[test]
    fn echo_hiding_stub_embed_returns_error() {
        let eh = EchoHiding::new();
        let result = eh.embed(dummy_cover(), &Payload::from_bytes(vec![1]));
        assert!(matches!(
            result,
            Err(StegoError::UnsupportedCoverType { .. })
        ));
    }

    #[test]
    fn echo_hiding_stub_extract_returns_error() {
        let eh = EchoHiding::new();
        let result = eh.extract(&dummy_cover());
        assert!(matches!(
            result,
            Err(StegoError::UnsupportedCoverType { .. })
        ));
        assert_eq!(ExtractTechnique::technique(&eh), StegoTechnique::EchoHiding);
    }

    #[test]
    fn zero_width_text_stub_capacity_returns_error() {
        let zwt = ZeroWidthText::new();
        assert!(zwt.capacity(&dummy_cover()).is_err());
        assert_eq!(
            EmbedTechnique::technique(&zwt),
            StegoTechnique::ZeroWidthText
        );
    }

    #[test]
    fn zero_width_text_stub_embed_returns_error() {
        let zwt = ZeroWidthText::new();
        let result = zwt.embed(dummy_cover(), &Payload::from_bytes(vec![1]));
        assert!(matches!(
            result,
            Err(StegoError::UnsupportedCoverType { .. })
        ));
    }

    #[test]
    fn zero_width_text_stub_extract_returns_error() {
        let zwt = ZeroWidthText::new();
        let result = zwt.extract(&dummy_cover());
        assert!(matches!(
            result,
            Err(StegoError::UnsupportedCoverType { .. })
        ));
        assert_eq!(
            ExtractTechnique::technique(&zwt),
            StegoTechnique::ZeroWidthText
        );
    }

    #[test]
    fn lsb_image_insufficient_capacity() {
        let embedder = LsbImage::new();
        let mut metadata = std::collections::HashMap::new();
        metadata.insert("width".to_string(), "2".to_string());
        metadata.insert("height".to_string(), "2".to_string());
        metadata.insert("channels".to_string(), "3".to_string());
        let cover = CoverMedia {
            kind: CoverMediaKind::PngImage,
            // 12 bytes = 2x2x3 pixels, capacity = 12/8 = 1 byte minus header
            data: vec![0u8; 12].into(),
            metadata,
        };
        // Payload larger than capacity
        let payload = Payload::from_bytes(vec![0xAB; 100]);
        let result = embedder.embed(cover, &payload);
        assert!(result.is_err());
    }

    #[test]
    fn lsb_audio_insufficient_capacity() {
        let embedder = LsbAudio::new();
        let mut metadata = std::collections::HashMap::new();
        metadata.insert("bits_per_sample".to_string(), "16".to_string());
        let cover = CoverMedia {
            kind: CoverMediaKind::WavAudio,
            // Very little audio data — only a few samples
            data: vec![0u8; 10].into(),
            metadata,
        };
        let payload = Payload::from_bytes(vec![0xAB; 100]);
        let result = embedder.embed(cover, &payload);
        assert!(result.is_err());
    }
}