stegoeggo 0.2.0

Image protection through steganographic watermarking and metadata injection for legal deterrence
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
//! Image protection library for legal deterrence against unauthorized AI training.
//!
//! Protects images through steganographic payload embedding and metadata injection,
//! providing evidence of protection and legal warnings that survive casual modification.
//!
//! # Protection Levels
//!
//! - `Disabled`: No protection applied
//! - `Light`: Metadata injection only (tEXt chunks for PNG, COM markers for JPEG)
//! - `Standard`: Steganography + metadata injection
//!
//! # Protection Layers
//!
//! Each protection level applies one or more layers:
//! 1. **Steganography** - Hidden LSB payload (PNG, lossless WebP) or DCT perturbation (JPEG). Lossy WebP is not supported.
//! 2. **Metadata Injection** - Visible anti-scraping markers (XMP, IPTC, EXIF)
//!
//! # JPEG Limitations
//!
//! JPEG's lossy compression inherently limits steganographic robustness. For JPEG,
//! the library can store a seed in quantization tables when those tables are preserved
//! and uses F5-style DCT coefficient embedding for baseline JPEGs. However,
//! pixel-based stego payloads may not survive JPEG re-compression.
//! **For maximum verifiability, use PNG output format.**
//!
//! Verification priority for JPEG: metadata seed extraction > DCT quantization table
//! seed > DCT coefficient extraction > pixel-based extraction.
//!
//! # JPEG-in/JPEG-out Fast Path
//!
//! When using `process_image_bytes` with JPEG input and JPEG output, the library
//! takes a byte-only fast path that operates directly on DCT coefficients, avoiding
//! decode/encode cycles. This path applies DCT steganography (F5 embedding) and
//! metadata injection. For progressive JPEGs, the progressive encoding is preserved.
//!
//! # Security Considerations
//!
//! For production use, always set a MAC key via `with_mac_key()` — the default
//! checksum provides no cryptographic integrity.
//!
//! **Without a MAC key**, steganographic payload verification uses a non-cryptographic
//! CRC32 checksum. An attacker can trivially forge valid-looking payloads.
//! This is suitable for accidental corruption detection and legal deterrence
//! (visible metadata markers prove intent), but **not** for adversarial settings.
//!
//! **With a MAC key**, the library uses HMAC-SHA256 for cryptographic payload
//! verification. Always set a MAC key in production:
//!
//! ```ignore
//! use stegoeggo::{ProtectionContext, ProtectionLevel};
//!
//! let ctx = ProtectionContext::default()
//!     .with_mac_key(b"your-secret-key".to_vec());
//! ```
//!
//! The primary deterrence mechanism is **visible metadata injection** (XMP, IPTC,
//! EXIF markers) — not the steganographic layer. Even if an attacker strips the
//! stego payload, the visible metadata markers remain as evidence of protection
//! and legal warnings.
//!
//! # WAF-Optimized Usage
//!
//! ```ignore
//! use stegoeggo::{process_image_bytes, ProtectionContext, ProtectionLevel, ImageOutputFormat};
//!
//! let ctx = ProtectionContext::new(0.5, 42)
//!     .with_format(ImageOutputFormat::Png)
//!     .with_mac_key(b"shared-verification-key".to_vec())
//!     .with_stego_redundancy(2)      // Lower = faster
//!     .with_jpeg_quality(85)        // Lower = smaller files
//!     .with_progressive_jpeg(true); // Progressive rendering for web
//!
//! let input_bytes = std::fs::read("image.png")?;
//! let (protected, warnings) =
//!     stegoeggo::process_image_bytes_with_warnings(&input_bytes, ProtectionLevel::Standard, &ctx)?;
//! // Reverse proxies should log or enforce warnings before serving.
//! ```
//!
//! Legal Metadata
//!
//! Embed copyright and usage restrictions in images for IP protection.
//!
//! ```rust
//! use stegoeggo::{ProtectionContext, LegalMetadata, ProtectionLevel};
//!
//! let ctx = ProtectionContext::default()
//!     .with_legal_metadata(
//!         LegalMetadata::new()
//!             .with_copyright_holder("Example Corp")
//!             .with_contact_email("legal@example.com")
//!             .with_usage_terms("All Rights Reserved. No AI training permitted.")
//!     )
//!     .with_legal_claims(true);
//! ```
//!
//! # Feature Flags
//!
//! | Feature | Description |
//! |---------|-------------|
//! | `async` | Enables Tokio-based async wrappers (`process_image_async`, etc.) for WAF/CDN integration |
//! | `test-seeds` | Enables fallback seed guessing during verification (tries common test/dev seeds). Used by the CLI; not recommended for library consumers |
//! | `fuzz` | Exposes internal JPEG parser for fuzz harnesses. Not part of the stable API |
//!
//! # Tiled Steganography
//!
//! For crop-resistant protection, enable tiled mode. The full payload is embedded
//! in each `tile_size × tile_size` tile independently, so any crop containing at
//! least one intact tile is recoverable:
//!
//! ```ignore
//! use stegoeggo::{ProtectionContext, ProtectionLevel};
//!
//! let ctx = ProtectionContext::new(0.5, 42)
//!     .with_tile_size(64);          // 64×64 tiles
//!
//! let protected = stegoeggo::process_image_bytes(&img_bytes, ProtectionLevel::Standard, &ctx)?;
//! ```
//!
//! # Async API
//!
//! For Tokio-based services (WAFs, CDN edge workers), use the async variants:
//!
//! ```ignore
//! use stegoeggo::{process_image_bytes_async, ProtectionContext, ProtectionLevel};
//!
//! let ctx = ProtectionContext::new(0.5, 42);
//! let protected = process_image_bytes_async(&img_bytes, ProtectionLevel::Standard, &ctx).await?;
//! ```
//!
//! # Parallel Batch Processing
//!
//! Process multiple images concurrently using Rayon:
//!
//! ```ignore
//! use stegoeggo::{process_images_parallel, ProtectionContext, ProtectionLevel};
//!
//! let images: Vec<image::DynamicImage> = vec![ /* ... */ ];
//! let ctx = ProtectionContext::default();
//! let results = process_images_parallel(&images, ProtectionLevel::Standard, &ctx)?;
//! ```
//!
//! # Warnings API
//!
//! `process_image_bytes_with_warnings` returns both the protected bytes and
//! any warnings about the protection process (e.g., progressive JPEG fallback,
//! insufficient DCT capacity):
//!
//! ```ignore
//! use stegoeggo::{process_image_bytes_with_warnings, ProtectionContext, ProtectionLevel};
//!
//! let ctx = ProtectionContext::new(0.5, 42);
//! let (protected, warnings) =
//!     process_image_bytes_with_warnings(&img_bytes, ProtectionLevel::Standard, &ctx)?;
//!
//! for w in &warnings {
//!     eprintln!("Warning: {w}");
//! }
//! ```

#![forbid(unsafe_code)]
#![warn(missing_docs)]

pub mod error;
pub mod traits;
/// Core types: protection levels, configuration, legal metadata, and verification results.
pub mod types;

pub(crate) mod jpeg_transcoder;
pub(crate) mod protected;
pub(crate) mod util;

#[cfg(feature = "async")]
pub mod async_api;

pub use error::{Error, Result};
pub use types::{
    DmiValue, ImageOutputFormat, LegalMetadata, ProtectionConfig, ProtectionContext,
    ProtectionLevel, ProtectionWarning, VerificationResult, VerificationStatus,
    DEFAULT_OUTPUT_FORMAT,
};

pub use traits::Protector;

pub use protected::metadata_trap::MetadataTrapProtector;
pub use protected::passthrough::PassthroughProtector;
pub use protected::steganography::{SteganographyProtector, StegoPayload};

pub use jpeg_transcoder::is_progressive_jpeg;

/// Parse JPEG header and decode DCT coefficients from raw bytes.
///
/// This function is exposed for fuzzing the internal JPEG parser. It parses
/// the JPEG header and decodes the entropy-coded scan data into DCT coefficients.
///
/// Returns `Ok((header, coefficients))` on success, or `Err` if the JPEG
/// is invalid, progressive, or otherwise unsupported.
#[cfg(feature = "fuzz")]
pub fn parse_jpeg_for_fuzz(
    data: &[u8],
) -> std::result::Result<
    (jpeg_transcoder::JpegHeader, jpeg_transcoder::Coefficients),
    jpeg_transcoder::TranscoderError,
> {
    jpeg_transcoder::JpegTranscoder::decode_coefficients(data)
}

pub use util::image::{
    compute_image_hash, detect_image_format, encode_image, encode_image_with_options,
    load_image_from_bytes,
};

pub use util::iscc::{
    compute_iscc, compute_iscc_from_bytes, compute_iscc_from_bytes_with_metadata,
    compute_iscc_with_metadata, Iscc,
};
pub use util::seed::generate_random_seed;

#[cfg(feature = "async")]
pub use async_api::{
    process_image_async, process_image_bytes_async, process_image_bytes_with_warnings_async,
    process_images_bytes_parallel_async, process_images_parallel_async, verify_image_bytes_async,
};

use image::DynamicImage;
use image::GenericImageView;
use std::borrow::Cow;
use std::sync::Arc;
use std::sync::LazyLock;

static DEFAULT_PIPELINE: LazyLock<ProtectionPipeline> = LazyLock::new(ProtectionPipeline::new);

/// Main pipeline for applying protection to images.
///
/// Coordinates between different protector implementations based on the
/// selected protection level. Create one via [`ProtectionPipeline::new`]
/// or use the convenience functions ([`process_image`], [`process_image_bytes`]).
#[non_exhaustive]
pub struct ProtectionPipeline {
    passthrough: Arc<PassthroughProtector>,
    metadata_trap: Arc<MetadataTrapProtector>,
    steganography: Arc<SteganographyProtector>,
}

impl ProtectionPipeline {
    /// Create a new ProtectionPipeline with default protectors.
    pub fn new() -> Self {
        Self {
            passthrough: Arc::new(PassthroughProtector::new()),
            metadata_trap: Arc::new(MetadataTrapProtector::new()),
            steganography: Arc::new(SteganographyProtector::new()),
        }
    }

    fn validate_dimensions(img: &DynamicImage, max_dim: Option<u32>) -> Result<()> {
        if let Some(max) = max_dim {
            let (width, height) = img.dimensions();
            if width > max || height > max {
                return Err(Error::ImageDecode(format!(
                    "Image dimensions {}x{} exceed maximum allowed {}",
                    width, height, max
                )));
            }
        }
        Ok(())
    }

    /// Process an image with the specified protection level.
    pub fn process<'a>(
        &'a self,
        img: &'a DynamicImage,
        level: ProtectionLevel,
        ctx: &ProtectionContext,
    ) -> Result<Cow<'a, DynamicImage>> {
        Self::validate_dimensions(img, ctx.max_dimension())?;

        let mut ctx_with_level = ctx.clone();
        ctx_with_level.set_protection_level(level);
        let ctx = &ctx_with_level;

        match level {
            ProtectionLevel::Disabled => self.passthrough.apply(img, ctx),
            ProtectionLevel::Light => self.apply_light_bytes(img, ctx).map(Cow::Owned),
            ProtectionLevel::Standard => self.apply_standard_pipeline(img, ctx).map(Cow::Owned),
        }
    }

    /// Standard pipeline: stego → encode → metadata injection.
    fn apply_standard_pipeline(
        &self,
        img: &DynamicImage,
        ctx: &ProtectionContext,
    ) -> Result<DynamicImage> {
        let output_format = ctx
            .output_format()
            .or(ctx.input_format())
            .unwrap_or(crate::types::DEFAULT_OUTPUT_FORMAT);

        let final_bytes = self.apply_pipeline_bytes(img, ctx, output_format)?;
        Ok(image::load_from_memory(&final_bytes)?)
    }

    /// Shared pipeline: stego → encode → metadata injection.
    /// Used by both `apply_standard_pipeline` and `apply_bytes_pipeline`.
    fn apply_pipeline_bytes(
        &self,
        img: &DynamicImage,
        ctx: &ProtectionContext,
        output_format: crate::types::ImageOutputFormat,
    ) -> Result<Vec<u8>> {
        // JPEG output: encode first, then apply DCT stego to the JPEG bytes
        if output_format == crate::types::ImageOutputFormat::Jpeg {
            let jpeg_bytes = crate::util::image::encode_image_with_options(
                img,
                Some(output_format),
                ctx.progressive_jpeg(),
                ctx.jpeg_quality(),
            )?;
            let with_stego = self.steganography.apply_dct_stego_bytes(&jpeg_bytes, ctx)?;
            return self.metadata_trap.inject_bytes(&with_stego, ctx);
        }

        // Non-JPEG output: pixel stego then encode
        let with_stego = self.steganography.apply(img, ctx)?;
        let encoded = crate::util::image::encode_image_with_options(
            &with_stego,
            Some(output_format),
            ctx.progressive_jpeg(),
            ctx.jpeg_quality(),
        )?;
        self.metadata_trap.inject_bytes(&encoded, ctx)
    }

    /// Light level: metadata injection + minimal steganographic seed marker.
    /// For JPEG, stores the seed in quantization tables when those tables are preserved.
    /// For PNG/WebP, embeds a minimal LSB payload with redundancy=1,
    /// then injects metadata (so tEXt chunks survive the re-encode).
    /// Encodes to bytes, applies minimal stego, injects metadata,
    /// then decodes back to `DynamicImage`.
    fn apply_light_bytes(
        &self,
        img: &DynamicImage,
        ctx: &ProtectionContext,
    ) -> Result<DynamicImage> {
        let output_format = ctx
            .output_format()
            .or(ctx.input_format())
            .unwrap_or(crate::types::DEFAULT_OUTPUT_FORMAT);

        match output_format {
            crate::types::ImageOutputFormat::Jpeg => {
                let encoded =
                    crate::util::image::encode_image(img, output_format.to_image_format())?;
                let with_metadata = self.metadata_trap.inject_bytes(&encoded, ctx)?;
                let with_stego = self
                    .steganography
                    .apply_qtable_seed_bytes(&with_metadata, ctx.seed())?;
                Ok(image::load_from_memory(&with_stego)?)
            }
            _ => {
                let mut minimal_ctx = ctx.clone();
                minimal_ctx.set_protection_level(crate::types::ProtectionLevel::Light);
                let stego_img = self.steganography.embed_lsb_minimal(img, &minimal_ctx);
                let encoded =
                    crate::util::image::encode_image(&stego_img, output_format.to_image_format())?;
                let with_metadata = self.metadata_trap.inject_bytes(&encoded, ctx)?;
                Ok(image::load_from_memory(&with_metadata)?)
            }
        }
    }

    /// Process image bytes with the specified protection level.
    ///
    /// For JPEG-in/JPEG-out, uses the byte-only fast path (DCT stego + metadata,
    /// no pixel decode). For other formats, decodes to pixels, applies the full
    /// pipeline, and re-encodes.
    pub fn process_bytes(
        &self,
        img_bytes: &[u8],
        level: ProtectionLevel,
        ctx: &ProtectionContext,
    ) -> Result<Vec<u8>> {
        let mut ctx_with_level = ctx.clone();
        ctx_with_level.set_protection_level(level);

        match level {
            ProtectionLevel::Disabled => Ok(img_bytes.to_vec()),
            ProtectionLevel::Light => {
                let format = ctx_with_level
                    .output_format()
                    .or(ctx_with_level.input_format())
                    .unwrap_or_else(|| {
                        crate::types::ImageOutputFormat::from_magic_bytes(img_bytes)
                            .unwrap_or(crate::types::DEFAULT_OUTPUT_FORMAT)
                    });
                match format {
                    crate::types::ImageOutputFormat::Jpeg => {
                        let with_metadata =
                            self.metadata_trap.apply_bytes(img_bytes, &ctx_with_level)?;
                        self.steganography
                            .apply_qtable_seed_bytes(&with_metadata, ctx_with_level.seed())
                    }
                    _ => {
                        let mut minimal_ctx = ctx_with_level.clone();
                        minimal_ctx.set_protection_level(crate::types::ProtectionLevel::Light);
                        let img = image::load_from_memory(img_bytes)?;
                        let stego_img = self.steganography.embed_lsb_minimal(&img, &minimal_ctx);
                        let encoded =
                            crate::util::image::encode_image(&stego_img, format.to_image_format())?;
                        self.metadata_trap.apply_bytes(&encoded, &ctx_with_level)
                    }
                }
            }
            ProtectionLevel::Standard => self.apply_bytes_pipeline(img_bytes, &ctx_with_level),
        }
    }

    fn validate_jpeg_dimensions_from_bytes(img_bytes: &[u8], max_dim: Option<u32>) -> Result<()> {
        if let Some(max) = max_dim {
            let header = jpeg_transcoder::header::JpegHeader::parse(img_bytes)?;
            if header.width as u32 > max || header.height as u32 > max {
                return Err(Error::ImageDecode(format!(
                    "Image dimensions {}x{} exceed maximum allowed {}",
                    header.width, header.height, max
                )));
            }
        }
        Ok(())
    }

    fn apply_bytes_pipeline(&self, img_bytes: &[u8], ctx: &ProtectionContext) -> Result<Vec<u8>> {
        let input_format = ctx
            .input_format()
            .or_else(|| crate::types::ImageOutputFormat::from_magic_bytes(img_bytes))
            .ok_or_else(|| Error::InvalidFormat("Unrecognized image format".to_string()))?;

        let output_format = ctx
            .output_format()
            .or(ctx.input_format())
            .unwrap_or(crate::types::DEFAULT_OUTPUT_FORMAT);

        // JPEG-in, JPEG-out: byte-only path (DCT stego + metadata, no pixel decode).
        // This preserves quality and avoids lossy re-encode cycles.
        if input_format == crate::types::ImageOutputFormat::Jpeg
            && output_format == crate::types::ImageOutputFormat::Jpeg
        {
            Self::validate_jpeg_dimensions_from_bytes(img_bytes, ctx.max_dimension())?;
            let with_stego = self.steganography.apply_dct_stego_bytes(img_bytes, ctx)?;
            return self.metadata_trap.inject_bytes(&with_stego, ctx);
        }

        // Non-JPEG-in: decode then use shared pipeline
        let img = load_image_from_bytes(img_bytes)?;
        Self::validate_dimensions(&img, ctx.max_dimension())?;
        self.apply_pipeline_bytes(&img, ctx, output_format)
    }
}

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

/// Process an image with the specified protection level.
///
/// Takes an owned DynamicImage and returns a processed image.
///
/// # Errors
///
/// Returns [`Error::ImageDecode`] if the image dimensions exceed `max_dimension`.
/// Returns [`Error::ImageEncode`] or [`Error::Steganography`] if encoding or
/// embedding fails.
#[must_use = "the protected image should be saved or used"]
pub fn process_image(
    img: DynamicImage,
    level: ProtectionLevel,
    ctx: &ProtectionContext,
) -> Result<DynamicImage> {
    DEFAULT_PIPELINE
        .process(&img, level, ctx)
        .map(|c| c.into_owned())
}

/// Process multiple images in parallel.
///
/// Takes a slice of images and returns a vector of processed images.
/// Uses Rayon for parallel processing.
///
/// # Examples
///
/// ```no_run
/// use stegoeggo::{process_images_parallel, ProtectionContext, ProtectionLevel};
/// use image::DynamicImage;
///
/// let images: Vec<DynamicImage> = vec![
///     image::open("image1.png").unwrap(),
///     image::open("image2.png").unwrap(),
/// ];
/// let ctx = ProtectionContext::new(0.5, 42);
/// let protected = process_images_parallel(&images, ProtectionLevel::Standard, &ctx).unwrap();
/// ```
///
/// # Errors
///
/// Returns the first error encountered from any image processing call.
#[must_use = "the protected images should be saved or used"]
pub fn process_images_parallel(
    images: &[DynamicImage],
    level: ProtectionLevel,
    ctx: &ProtectionContext,
) -> Result<Vec<DynamicImage>> {
    use rayon::prelude::*;
    images
        .par_iter()
        .map(|img| {
            DEFAULT_PIPELINE
                .process(img, level, ctx)
                .map(|c| c.into_owned())
        })
        .collect()
}

/// Process multiple images in parallel (bytes variant).
///
/// Takes a slice of image bytes and returns a vector of processed image bytes.
///
/// # Examples
///
/// ```no_run
/// use stegoeggo::{process_images_bytes_parallel, ProtectionContext, ProtectionLevel};
///
/// let images: Vec<Vec<u8>> = vec![
///     std::fs::read("image1.png").unwrap(),
///     std::fs::read("image2.png").unwrap(),
/// ];
/// let ctx = ProtectionContext::new(0.5, 42);
/// let protected = process_images_bytes_parallel(&images, ProtectionLevel::Standard, &ctx).unwrap();
/// ```
///
/// # Errors
///
/// Returns the first error encountered from any image processing call.
#[must_use = "the protected image bytes should be saved or used"]
pub fn process_images_bytes_parallel(
    images: &[Vec<u8>],
    level: ProtectionLevel,
    ctx: &ProtectionContext,
) -> Result<Vec<Vec<u8>>> {
    use rayon::prelude::*;
    images
        .par_iter()
        .map(|img_bytes| DEFAULT_PIPELINE.process_bytes(img_bytes, level, ctx))
        .collect()
}

/// Process image bytes with the specified protection level.
///
/// Automatically detects the input format from magic bytes and preserves
/// the output format. Returns the protected image as bytes.
///
/// For JPEG-in/JPEG-out, this function takes a byte-only fast path that
/// operates on DCT coefficients directly, avoiding pixel decode/encode cycles.
///
/// # Examples
///
/// ```no_run
/// use stegoeggo::{process_image_bytes, ProtectionContext, ProtectionLevel};
///
/// let img_bytes: Vec<u8> = std::fs::read("input.png").unwrap();
/// let ctx = ProtectionContext::new(0.5, 42);
/// let protected = process_image_bytes(&img_bytes, ProtectionLevel::Standard, &ctx).unwrap();
/// std::fs::write("output.png", &protected).unwrap();
/// ```
///
/// # Errors
///
/// Returns [`Error::InvalidFormat`] if the image format cannot be determined.
/// Returns [`Error::ImageDecode`], [`Error::ImageEncode`], or
/// [`Error::Steganography`] if processing fails.
#[must_use = "the protected image bytes should be saved or used"]
pub fn process_image_bytes(
    img_bytes: &[u8],
    level: ProtectionLevel,
    ctx: &ProtectionContext,
) -> Result<Vec<u8>> {
    let format = ImageOutputFormat::from_magic_bytes(img_bytes)
        .ok_or_else(|| Error::InvalidFormat("Unrecognized image format".to_string()))?;

    let ctx_with_format = {
        let mut ctx = ctx.clone();
        if ctx.input_format().is_none() {
            ctx.set_input_format(format);
        }
        ctx
    };

    DEFAULT_PIPELINE.process_bytes(img_bytes, level, &ctx_with_format)
}

/// Process image bytes with protection level and return warnings about
/// degraded protection.
///
/// Like [`process_image_bytes`], but also returns a [`ProtectionWarning`] if
/// the protection was applied with reduced effectiveness. This is important
/// for legal defense use cases where the caller needs to know the actual
/// protection level applied.
///
/// This compatibility helper returns only the first warning. New reverse-proxy
/// integrations should prefer [`process_image_bytes_with_warnings`] so they can
/// log or enforce every warning emitted for the request.
///
/// # Examples
///
/// ```no_run
/// use stegoeggo::{process_image_bytes_with_info, ProtectionContext, ProtectionLevel};
///
/// let img_bytes: Vec<u8> = std::fs::read("input.jpg").unwrap();
/// let ctx = ProtectionContext::new(0.5, 42);
/// let (protected, warning) = process_image_bytes_with_info(
///     &img_bytes, ProtectionLevel::Standard, &ctx
/// ).unwrap();
/// if let Some(w) = warning {
///     eprintln!("Warning: {}", w);
/// }
/// ```
///
/// # Errors
///
/// Returns [`Error::InvalidFormat`] if the image format cannot be determined.
/// Returns [`Error::ImageDecode`], [`Error::ImageEncode`], or
/// [`Error::Steganography`] if processing fails.
pub fn process_image_bytes_with_info(
    img_bytes: &[u8],
    level: ProtectionLevel,
    ctx: &ProtectionContext,
) -> Result<(Vec<u8>, Option<ProtectionWarning>)> {
    let (bytes, warnings) = process_image_bytes_with_warnings(img_bytes, level, ctx)?;
    let warning = warnings
        .into_iter()
        .find(|w| matches!(w, ProtectionWarning::ProgressiveJpegFallback));
    Ok((bytes, warning))
}

/// Process image bytes with protection level and return all protection warnings.
///
/// This is the recommended API for reverse-proxy integrations. It keeps the
/// hot path byte-oriented, while giving the caller enough information to make
/// policy decisions about serving, logging, or falling back when the actual
/// emitted evidence is weaker than requested.
///
/// The library owns steganographic and metadata injection mechanics; the proxy
/// should still enforce request byte limits, concurrency limits, timeouts, and
/// cache policy outside this function.
///
/// # Errors
///
/// Returns [`Error::InvalidFormat`] if the image format cannot be determined.
/// Returns [`Error::ImageDecode`], [`Error::ImageEncode`], or
/// [`Error::Steganography`] if processing fails.
pub fn process_image_bytes_with_warnings(
    img_bytes: &[u8],
    level: ProtectionLevel,
    ctx: &ProtectionContext,
) -> Result<(Vec<u8>, Vec<ProtectionWarning>)> {
    let format = ImageOutputFormat::from_magic_bytes(img_bytes)
        .ok_or_else(|| Error::InvalidFormat("Unrecognized image format".to_string()))?;

    let ctx_with_format = {
        let mut ctx = ctx.clone();
        if ctx.input_format().is_none() {
            ctx.set_input_format(format);
        }
        ctx
    };

    let mut warnings = Vec::new();
    if level != ProtectionLevel::Disabled && ctx_with_format.mac_key().is_none() {
        warnings.push(ProtectionWarning::MissingMacKey);
    }
    if matches!(ctx_with_format.inject_metadata(), Some(false)) {
        warnings.push(ProtectionWarning::MetadataInjectionDisabled);
    }

    let output_format = ctx_with_format
        .output_format()
        .or(ctx_with_format.input_format())
        .unwrap_or(DEFAULT_OUTPUT_FORMAT);

    // Detect progressive JPEG fallback before processing — the pipeline silently
    // falls back to Q-table seed only for progressive JPEGs. If the caller
    // requested progressive JPEG output, the encoded output will be progressive
    // and the DCT transcoder will reject it.
    if level == ProtectionLevel::Standard
        && ctx_with_format.progressive_jpeg()
        && output_format == ImageOutputFormat::Jpeg
    {
        warnings.push(ProtectionWarning::ProgressiveJpegFallback);
    }

    // Also detect progressive JPEG input: the DCT transcoder cannot decode
    // progressive JPEGs, so Standard level falls back to Q-table seed only.
    if level == ProtectionLevel::Standard
        && format == ImageOutputFormat::Jpeg
        && is_progressive_jpeg(img_bytes)
    {
        warnings.push(ProtectionWarning::ProgressiveJpegFallback);
    }

    if level != ProtectionLevel::Disabled && output_format == ImageOutputFormat::Jpeg {
        warnings.push(ProtectionWarning::JpegReencodeFragile);
    }
    if level != ProtectionLevel::Disabled && output_format == ImageOutputFormat::WebP {
        warnings.push(ProtectionWarning::WebpLossyReencodeDestructive);
    }

    // Pre-check LSB capacity for PNG/WebP Standard level — the pipeline silently
    // skips embedding when the image has too few pixels.
    if level == ProtectionLevel::Standard
        && matches!(
            output_format,
            ImageOutputFormat::Png | ImageOutputFormat::WebP
        )
    {
        if let Ok(img) = image::load_from_memory(img_bytes) {
            let (w, h) = img.dimensions();
            let total_pixels = (w as usize) * (h as usize);
            // Payload: 32-byte V2 header × 3 (ECC) + 4 CRC = 100 bytes = 800 bits
            // Required pixels: ceil(800 / 3) × STEGO_SPREAD_FACTOR(5) ≈ 1340
            let payload_bits: usize = 800;
            let pixels_needed =
                payload_bits.div_ceil(3) * crate::protected::constants::STEGO_SPREAD_FACTOR;
            if total_pixels < pixels_needed {
                warnings.push(ProtectionWarning::LsbCapacitySkipped);
            }
        }
    }

    let result = DEFAULT_PIPELINE.process_bytes(img_bytes, level, &ctx_with_format)?;

    // Post-check DCT capacity: if the output is essentially unchanged (same length
    // or within a small margin), DCT stego likely failed due to insufficient
    // AC coefficients. This catches small JPEGs where the F5 embed silently falls
    // back to Q-table seed only.
    if level == ProtectionLevel::Standard && format == ImageOutputFormat::Jpeg {
        let size_delta = (result.len() as i64 - img_bytes.len() as i64).unsigned_abs();
        // If the output is smaller or nearly the same size, DCT stego was likely
        // skipped (Q-table seed adds only ~100 bytes, metadata adds ~500-2000 bytes).
        // A real DCT embed typically changes size noticeably due to coefficient modification.
        // Heuristic: if the output is within 10% of input size, DCT capacity was likely insufficient.
        if size_delta * 10 < img_bytes.len() as u64 / 20 {
            // Check if this is NOT a progressive JPEG (progressive gets its own warning)
            if !is_progressive_jpeg(img_bytes) {
                warnings.push(ProtectionWarning::DctCapacityInsufficient);
            }
        }
    }

    Ok((result, warnings))
}

/// Verify that image bytes contain a protection payload whose integrity can be proved.
///
/// Checks metadata seeds, DCT stego integrity (for JPEG), and LSB stego (for PNG/WebP).
///
/// # Returns
///
/// - [`VerificationStatus::Verified`] — protection data found and verification passed
/// - [`VerificationStatus::Invalid`] — protection data found but verification failed
///   (corrupted or wrong key)
/// - [`VerificationStatus::NotFound`] — no protection data found in the image
///
/// # Arguments
///
/// * `img_bytes` - Raw image bytes (PNG, JPEG, or WebP)
/// * `mac_key` - Optional MAC key for HMAC-SHA256 verification. Pass empty slice
///   for checksum-only verification.
///
/// # Examples
///
/// ```no_run
/// # let img_bytes: Vec<u8> = Vec::new();
/// match stegoeggo::verify_image_bytes(&img_bytes, &[]) {
///     stegoeggo::VerificationStatus::Verified => println!("Protected and verified"),
///     stegoeggo::VerificationStatus::Invalid => println!("Protected but verification failed"),
///     stegoeggo::VerificationStatus::NotFound => println!("No protection found"),
/// }
/// ```
pub fn verify_image_bytes(img_bytes: &[u8], mac_key: &[u8]) -> VerificationStatus {
    let stego = SteganographyProtector::new();
    stego.verify_payload_from_bytes_with_key(img_bytes, mac_key)
}

/// Verify protection with detailed results.
///
/// Like [`verify_image_bytes`], but returns a [`VerificationResult`] with
/// richer information about what was found and whether verification passed.
///
/// # Examples
///
/// ```no_run
/// use stegoeggo::{verify_image_bytes_detailed, VerificationResult};
///
/// let bytes = std::fs::read("protected.png").unwrap();
/// match verify_image_bytes_detailed(&bytes, b"my-key") {
///     VerificationResult::Verified { payload } => {
///         println!("Seed: {}, Intensity: {}", payload.seed(), payload.intensity());
///     }
///     VerificationResult::MetadataOnly { seed } => {
///         println!("Metadata seed found, but payload was not verified: {}", seed);
///     }
///     VerificationResult::Corrupted { .. } => println!("Protection found but corrupted"),
///     VerificationResult::NotFound => println!("No protection found"),
/// }
/// ```
pub fn verify_image_bytes_detailed(img_bytes: &[u8], mac_key: &[u8]) -> VerificationResult {
    let stego = SteganographyProtector::new();

    match stego.verify_payload_from_bytes_with_key(img_bytes, mac_key) {
        VerificationStatus::Verified => {
            if let Some(payload) = stego.extract_payload_from_bytes_with_key(img_bytes, mac_key) {
                return VerificationResult::Verified { payload };
            }
            return VerificationResult::NotFound;
        }
        VerificationStatus::Invalid => {
            if let Some(payload) = stego.extract_payload_from_bytes_with_key(img_bytes, mac_key) {
                return VerificationResult::Corrupted { payload };
            }
            return VerificationResult::NotFound;
        }
        VerificationStatus::NotFound => {}
    }

    if let Some(seed) = MetadataTrapProtector::extract_seed_from_image(img_bytes) {
        return VerificationResult::MetadataOnly { seed };
    }

    VerificationResult::NotFound
}

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

    #[test]
    fn test_pipeline_disabled() {
        let pipeline = ProtectionPipeline::new();
        let img = DynamicImage::new_rgb8(10, 10);

        let result = pipeline.process(
            &img,
            ProtectionLevel::Disabled,
            &ProtectionContext::default(),
        );
        assert!(result.is_ok());
    }

    #[test]
    fn test_pipeline_all_levels() {
        let pipeline = ProtectionPipeline::new();
        let img = DynamicImage::new_rgb8(10, 10);

        for level in &[
            ProtectionLevel::Disabled,
            ProtectionLevel::Light,
            ProtectionLevel::Standard,
        ] {
            let result = pipeline.process(&img, *level, &ProtectionContext::default());
            assert!(result.is_ok(), "Failed for level: {:?}", level);
        }
    }

    #[test]
    fn test_process_image_bytes() {
        use image::ImageEncoder;

        let img = DynamicImage::new_rgb8(10, 10);
        let mut buffer = Vec::new();
        {
            let encoder = image::codecs::png::PngEncoder::new(&mut buffer);
            let rgb = img.to_rgb8();
            encoder
                .write_image(&rgb, 10, 10, image::ExtendedColorType::Rgb8)
                .unwrap();
        }

        let result = process_image_bytes(
            &buffer,
            ProtectionLevel::Standard,
            &ProtectionContext::default(),
        );
        assert!(result.is_ok());
    }

    #[test]
    fn test_end_to_end_protection_verification() {
        let pipeline = ProtectionPipeline::new();
        let img = DynamicImage::new_rgb8(64, 64);

        let ctx = ProtectionContext::default()
            .with_seed(42)
            .with_intensity(0.5);

        let protected = pipeline
            .process(&img, ProtectionLevel::Standard, &ctx)
            .unwrap();

        let stego = SteganographyProtector::new();
        let verified = stego.verify_payload(&protected);

        assert!(verified, "Payload should be verified after protection");
    }

    #[test]
    fn test_process_bytes_and_verify() {
        use image::ImageEncoder;

        let img = DynamicImage::new_rgb8(32, 32);
        let mut input_bytes = Vec::new();
        {
            let encoder = image::codecs::png::PngEncoder::new(&mut input_bytes);
            let rgb = img.to_rgb8();
            encoder
                .write_image(&rgb, 32, 32, image::ExtendedColorType::Rgb8)
                .unwrap();
        }

        let ctx = ProtectionContext::default()
            .with_seed(12345)
            .with_intensity(0.7);

        let protected_bytes =
            process_image_bytes(&input_bytes, ProtectionLevel::Standard, &ctx).unwrap();

        assert!(!protected_bytes.is_empty());
        // Output should differ from input when intensity > 0.
        // Size difference alone is insufficient (metadata injection always
        // changes size), so also verify content differs for non-zero intensity.
        assert!(
            protected_bytes.len() != input_bytes.len() || ctx.intensity() == 0.0,
            "Protected bytes should differ from input at intensity {}",
            ctx.intensity()
        );
    }

    #[test]
    fn test_different_seeds_different_output() {
        let pipeline = ProtectionPipeline::new();
        let img = DynamicImage::new_rgb8(32, 32);

        let ctx1 = ProtectionContext::default().with_seed(42);
        let ctx2 = ProtectionContext::default().with_seed(99);

        let result1 = pipeline
            .process(&img, ProtectionLevel::Standard, &ctx1)
            .unwrap();
        let result2 = pipeline
            .process(&img, ProtectionLevel::Standard, &ctx2)
            .unwrap();

        let rgba1 = result1.to_rgba8();
        let rgba2 = result2.to_rgba8();

        assert_ne!(
            rgba1.as_raw(),
            rgba2.as_raw(),
            "Different seeds should produce different output"
        );
    }

    #[test]
    fn test_parallel_processing() {
        let images: Vec<DynamicImage> = (0..4).map(|_| DynamicImage::new_rgb8(16, 16)).collect();

        let ctx = ProtectionContext::default().with_seed(42);

        let results = process_images_parallel(&images, ProtectionLevel::Standard, &ctx).unwrap();

        assert_eq!(results.len(), 4);
    }

    #[test]
    fn test_metadata_extraction() {
        let img = DynamicImage::new_rgb8(32, 32);

        let ctx = ProtectionContext::default()
            .with_seed(42)
            .with_format(ImageOutputFormat::Png);

        let metadata_protector = MetadataTrapProtector::new();
        let encoded = crate::util::image::encode_image(&img, image::ImageFormat::Png).unwrap();

        let protected_bytes = metadata_protector.apply_bytes(&encoded, &ctx).unwrap();

        let seed = MetadataTrapProtector::extract_seed_from_image(&protected_bytes);

        assert!(
            seed.is_some(),
            "Seed should be extractable from protected image"
        );
    }

    #[test]
    fn test_intensity_zero_no_change() {
        let pipeline = ProtectionPipeline::new();
        let img = DynamicImage::new_rgb8(16, 16);

        let ctx = ProtectionContext::default()
            .with_seed(42)
            .with_intensity(0.0);

        let result = pipeline
            .process(&img, ProtectionLevel::Disabled, &ctx)
            .unwrap();

        let original_bytes = img.to_rgba8();
        let result_bytes = result.to_rgba8();

        assert_eq!(original_bytes.as_raw(), result_bytes.as_raw());
    }

    #[test]
    fn test_max_dimension_validation() {
        let pipeline = ProtectionPipeline::new();
        let img = DynamicImage::new_rgb8(1000, 1000);

        let ctx = ProtectionContext::default().with_max_dimension(512);

        let result = pipeline.process(&img, ProtectionLevel::Standard, &ctx);

        assert!(
            result.is_err(),
            "Should fail when image exceeds max dimension"
        );
    }

    #[test]
    fn test_max_dimension_validation_process_bytes() {
        use image::ImageEncoder;

        let img = DynamicImage::new_rgb8(1000, 1000);
        let mut buffer = Vec::new();
        {
            let encoder = image::codecs::png::PngEncoder::new(&mut buffer);
            let rgb = img.to_rgb8();
            encoder
                .write_image(&rgb, 1000, 1000, image::ExtendedColorType::Rgb8)
                .unwrap();
        }

        let ctx = ProtectionContext::default().with_max_dimension(512);

        let result = process_image_bytes(&buffer, ProtectionLevel::Standard, &ctx);

        assert!(
            result.is_err(),
            "Should fail when image exceeds max dimension via process_bytes"
        );
    }
}