superbook-pdf 0.1.0

High-quality PDF converter for scanned books with AI enhancement, deskew correction, and Japanese OCR
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
//! Color Statistics and Global Color Adjustment module
//!
//! Provides functionality for analyzing color statistics across pages
//! and applying global color correction for consistent book appearance.
//!
//! # Features
//!
//! - Paper/ink color extraction via histogram analysis
//! - MAD-based outlier exclusion
//! - Linear scale/offset color adjustment
//! - Ghost suppression for see-through pages
//!
//! # Example
//!
//! ```rust,no_run
//! use superbook_pdf::color_stats::{ColorStats, ColorAnalyzer, GlobalColorParam};
//! use std::path::Path;
//!
//! // Analyze a page
//! let stats = ColorAnalyzer::calculate_stats(Path::new("page.png")).unwrap();
//! println!("Paper color: RGB({:.0}, {:.0}, {:.0})",
//!     stats.paper_r, stats.paper_g, stats.paper_b);
//!
//! // Get global adjustment parameters
//! let params = ColorAnalyzer::decide_global_adjustment(&[stats]);
//! println!("Scale R: {:.2}", params.scale_r);
//! ```

use image::{Rgb, RgbImage};
use rayon::prelude::*;
use std::path::{Path, PathBuf};
use thiserror::Error;

// ============================================================
// Constants
// ============================================================

/// Sample step for histogram building (skip pixels for performance)
const SAMPLE_STEP: u32 = 4;

/// Percentile for ink color detection (dark pixels)
const INK_PERCENTILE: f64 = 0.05;

/// Percentile for paper color detection (light pixels)
const PAPER_PERCENTILE: f64 = 0.95;

/// Minimum scale factor for color adjustment
const MIN_SCALE: f64 = 0.8;

/// Maximum scale factor for color adjustment
const MAX_SCALE: f64 = 4.0;

/// Default saturation threshold for paper detection
const DEFAULT_SAT_THRESHOLD: u8 = 55;

/// Default color distance threshold
const DEFAULT_COLOR_DIST_THRESHOLD: u8 = 35;

/// Default white clip range
const DEFAULT_WHITE_CLIP_RANGE: u8 = 30;

// ============================================================
// Error Types
// ============================================================

/// Color analysis error types
#[derive(Debug, Error)]
pub enum ColorStatsError {
    #[error("Image not found: {0}")]
    ImageNotFound(PathBuf),

    #[error("Invalid image: {0}")]
    InvalidImage(String),

    #[error("No valid pages for analysis")]
    NoValidPages,

    #[error("IO error: {0}")]
    IoError(#[from] std::io::Error),
}

pub type Result<T> = std::result::Result<T, ColorStatsError>;

// ============================================================
// Data Structures
// ============================================================

/// Color statistics for a single page
#[derive(Debug, Clone, Default)]
pub struct ColorStats {
    /// Page number (1-based)
    pub page_number: usize,

    /// Paper (background) color - Red channel average
    pub paper_r: f64,
    /// Paper (background) color - Green channel average
    pub paper_g: f64,
    /// Paper (background) color - Blue channel average
    pub paper_b: f64,

    /// Ink (foreground) color - Red channel average
    pub ink_r: f64,
    /// Ink (foreground) color - Green channel average
    pub ink_g: f64,
    /// Ink (foreground) color - Blue channel average
    pub ink_b: f64,

    /// Mean R (for backward compatibility, same as paper_r)
    pub mean_r: f64,
    /// Mean G (for backward compatibility, same as paper_g)
    pub mean_g: f64,
    /// Mean B (for backward compatibility, same as paper_b)
    pub mean_b: f64,
}

impl ColorStats {
    /// Calculate paper luminance (ITU-R BT.601)
    pub fn paper_luminance(&self) -> f64 {
        0.299 * self.paper_r + 0.587 * self.paper_g + 0.114 * self.paper_b
    }

    /// Calculate ink luminance
    pub fn ink_luminance(&self) -> f64 {
        0.299 * self.ink_r + 0.587 * self.ink_g + 0.114 * self.ink_b
    }
}

/// Bleed-through (裏写り) suppression parameters using HSV color space
///
/// This structure defines the HSV color ranges that identify bleed-through
/// artifacts from the reverse side of pages in scanned books.
///
/// # Phase 1.3 Enhancement
///
/// Bleed-through typically appears as:
/// - Yellowish/orange tint (hue 20-65 degrees)
/// - Low saturation (< 30% for pastel colors)
/// - High value/brightness (> 70% for light colors)
#[derive(Debug, Clone)]
pub struct BleedSuppression {
    /// Minimum hue for bleed detection (degrees, 0-360)
    /// Yellow starts around 20 degrees
    pub hue_min: f32,

    /// Maximum hue for bleed detection (degrees, 0-360)
    /// Orange ends around 65 degrees
    pub hue_max: f32,

    /// Maximum saturation for bleed detection (0.0-1.0)
    /// Only detect pastel/faded colors (typically < 0.3)
    pub saturation_max: f32,

    /// Minimum value (brightness) for bleed detection (0.0-1.0)
    /// Only detect light colors (typically > 0.7)
    pub value_min: f32,

    /// Enable bleed suppression
    pub enabled: bool,

    /// Strength of bleed suppression (0.0-1.0)
    /// 1.0 = full white, 0.0 = no change
    pub strength: f32,
}

impl Default for BleedSuppression {
    fn default() -> Self {
        Self {
            hue_min: 20.0,
            hue_max: 65.0,
            // C# version uses BleedValueMin = 0.35, no saturation check
            // But we keep saturation_max for additional filtering
            saturation_max: 1.0,  // No saturation filter (match C# behavior)
            value_min: 0.35,      // Match C# BleedValueMin = 0.35
            enabled: true,
            strength: 1.0,
        }
    }
}

impl BleedSuppression {
    /// Create a new BleedSuppression configuration
    pub fn new(hue_min: f32, hue_max: f32, saturation_max: f32, value_min: f32) -> Self {
        Self {
            hue_min,
            hue_max,
            saturation_max,
            value_min,
            enabled: true,
            strength: 1.0,
        }
    }

    /// Check if a pixel is a bleed-through artifact
    ///
    /// # Arguments
    /// * `h` - Hue (0-360 degrees)
    /// * `s` - Saturation (0.0-1.0)
    /// * `v` - Value/Brightness (0.0-1.0)
    ///
    /// # Returns
    /// `true` if the pixel matches bleed-through characteristics
    pub fn is_bleed_through(&self, h: f32, s: f32, v: f32) -> bool {
        if !self.enabled {
            return false;
        }

        // Check hue range (yellow to orange)
        let hue_match = h >= self.hue_min && h <= self.hue_max;

        // Check saturation (low saturation = pastel/faded)
        let sat_match = s <= self.saturation_max;

        // Check value (high brightness)
        let val_match = v >= self.value_min;

        hue_match && sat_match && val_match
    }

    /// Create configuration for aggressive bleed removal
    pub fn aggressive() -> Self {
        Self {
            hue_min: 15.0,
            hue_max: 75.0,
            saturation_max: 0.40,
            value_min: 0.60,
            enabled: true,
            strength: 1.0,
        }
    }

    /// Create configuration for gentle bleed removal
    pub fn gentle() -> Self {
        Self {
            hue_min: 25.0,
            hue_max: 55.0,
            saturation_max: 0.20,
            value_min: 0.80,
            enabled: true,
            strength: 0.7,
        }
    }

    /// Disable bleed suppression
    pub fn disabled() -> Self {
        Self {
            enabled: false,
            ..Default::default()
        }
    }
}

/// Global color adjustment parameters
#[derive(Debug, Clone)]
pub struct GlobalColorParam {
    /// Scale factor for Red channel
    pub scale_r: f64,
    /// Scale factor for Green channel
    pub scale_g: f64,
    /// Scale factor for Blue channel
    pub scale_b: f64,

    /// Offset for Red channel
    pub offset_r: f64,
    /// Offset for Green channel
    pub offset_g: f64,
    /// Offset for Blue channel
    pub offset_b: f64,

    /// Ghost suppression luminance threshold
    pub ghost_suppress_threshold: u8,
    /// White clip range (how close to white to clip)
    pub white_clip_range: u8,

    /// Representative paper color RGB
    pub paper_r: u8,
    pub paper_g: u8,
    pub paper_b: u8,

    /// Saturation threshold for paper detection (0-255)
    pub sat_threshold: u8,
    /// Color distance threshold (L1 norm)
    pub color_dist_threshold: u8,

    /// Bleed-through hue range minimum (degrees) - legacy
    pub bleed_hue_min: f32,
    /// Bleed-through hue range maximum (degrees) - legacy
    pub bleed_hue_max: f32,
    /// Bleed-through minimum value (HSV) - legacy
    pub bleed_value_min: f32,

    /// Enhanced bleed suppression configuration (Phase 1.3)
    pub bleed_suppression: BleedSuppression,
}

impl Default for GlobalColorParam {
    fn default() -> Self {
        Self {
            scale_r: 1.0,
            scale_g: 1.0,
            scale_b: 1.0,
            offset_r: 0.0,
            offset_g: 0.0,
            offset_b: 0.0,
            ghost_suppress_threshold: 200,
            white_clip_range: DEFAULT_WHITE_CLIP_RANGE,
            paper_r: 255,
            paper_g: 255,
            paper_b: 255,
            sat_threshold: DEFAULT_SAT_THRESHOLD,
            color_dist_threshold: DEFAULT_COLOR_DIST_THRESHOLD,
            bleed_hue_min: 20.0,
            bleed_hue_max: 65.0,
            bleed_value_min: 0.35,
            bleed_suppression: BleedSuppression::default(),
        }
    }
}

// ============================================================
// Color Analyzer
// ============================================================

/// Color statistics analyzer
pub struct ColorAnalyzer;

impl ColorAnalyzer {
    /// Calculate color statistics from an image file
    pub fn calculate_stats(image_path: &Path) -> Result<ColorStats> {
        if !image_path.exists() {
            return Err(ColorStatsError::ImageNotFound(image_path.to_path_buf()));
        }

        let img =
            image::open(image_path).map_err(|e| ColorStatsError::InvalidImage(e.to_string()))?;

        let rgb = img.to_rgb8();
        Ok(Self::calculate_stats_from_image(&rgb, 0))
    }

    /// Calculate color statistics from an RGB image
    pub fn calculate_stats_from_image(image: &RgbImage, page_number: usize) -> ColorStats {
        let (w, h) = image.dimensions();
        let step = SAMPLE_STEP;

        // Build luminance histogram
        let mut histogram = [0u64; 256];
        let mut total = 0u64;

        for y in (0..h).step_by(step as usize) {
            for x in (0..w).step_by(step as usize) {
                let pixel = image.get_pixel(x, y);
                let lum = Self::luminance(pixel.0[0], pixel.0[1], pixel.0[2]);
                histogram[lum as usize] += 1;
                total += 1;
            }
        }

        // Find 5% (ink) and 95% (paper) percentile luminance thresholds
        let low_target = (total as f64 * INK_PERCENTILE) as u64;
        let high_target = (total as f64 * PAPER_PERCENTILE) as u64;

        let mut low_lum = 0u8;
        let mut high_lum = 255u8;
        let mut acc = 0u64;

        for (i, &count) in histogram.iter().enumerate() {
            acc += count;
            if acc >= low_target && low_lum == 0 {
                low_lum = i as u8;
            }
            if acc >= high_target {
                high_lum = i as u8;
                break;
            }
        }

        // Calculate RGB averages for paper (bright) and ink (dark) pixels
        let mut sum_paper_r = 0u64;
        let mut sum_paper_g = 0u64;
        let mut sum_paper_b = 0u64;
        let mut cnt_paper = 0u64;

        let mut sum_ink_r = 0u64;
        let mut sum_ink_g = 0u64;
        let mut sum_ink_b = 0u64;
        let mut cnt_ink = 0u64;

        for y in (0..h).step_by(step as usize) {
            for x in (0..w).step_by(step as usize) {
                let pixel = image.get_pixel(x, y);
                let (r, g, b) = (pixel.0[0], pixel.0[1], pixel.0[2]);
                let lum = Self::luminance(r, g, b);

                if lum >= high_lum {
                    // Paper pixel
                    sum_paper_r += r as u64;
                    sum_paper_g += g as u64;
                    sum_paper_b += b as u64;
                    cnt_paper += 1;
                } else if lum <= low_lum {
                    // Ink pixel
                    sum_ink_r += r as u64;
                    sum_ink_g += g as u64;
                    sum_ink_b += b as u64;
                    cnt_ink += 1;
                }
            }
        }

        // Prevent division by zero
        if cnt_paper == 0 {
            cnt_paper = 1;
        }
        if cnt_ink == 0 {
            cnt_ink = 1;
        }

        let paper_r = sum_paper_r as f64 / cnt_paper as f64;
        let paper_g = sum_paper_g as f64 / cnt_paper as f64;
        let paper_b = sum_paper_b as f64 / cnt_paper as f64;

        let ink_r = sum_ink_r as f64 / cnt_ink as f64;
        let ink_g = sum_ink_g as f64 / cnt_ink as f64;
        let ink_b = sum_ink_b as f64 / cnt_ink as f64;

        ColorStats {
            page_number,
            paper_r,
            paper_g,
            paper_b,
            ink_r,
            ink_g,
            ink_b,
            mean_r: paper_r,
            mean_g: paper_g,
            mean_b: paper_b,
        }
    }

    /// Exclude outlier pages using MAD (Median Absolute Deviation)
    pub fn exclude_outliers(stats_list: &[ColorStats]) -> Vec<ColorStats> {
        if stats_list.len() < 3 {
            return stats_list.to_vec();
        }

        // Calculate paper luminance for each page
        let mut luminances: Vec<(usize, f64)> = stats_list
            .iter()
            .enumerate()
            .map(|(i, s)| (i, s.paper_luminance()))
            .collect();

        luminances.sort_by(|a, b| a.1.total_cmp(&b.1));

        // Calculate median
        let median = Self::percentile_f64(
            &luminances.iter().map(|(_, l)| *l).collect::<Vec<_>>(),
            50.0,
        );

        // Calculate MAD
        let mut deviations: Vec<f64> = luminances.iter().map(|(_, l)| (l - median).abs()).collect();
        deviations.sort_by(|a, b| a.total_cmp(b));
        let mad = Self::percentile_f64(&deviations, 50.0);

        // Filter out outliers (> 1.5 * MAD from median)
        let threshold = mad * 1.5;
        let valid_indices: Vec<usize> = luminances
            .iter()
            .filter(|(_, l)| (l - median).abs() <= threshold)
            .map(|(i, _)| *i)
            .collect();

        if valid_indices.is_empty() {
            return stats_list.to_vec();
        }

        valid_indices
            .iter()
            .map(|&i| stats_list[i].clone())
            .collect()
    }

    /// Decide global color adjustment parameters from filtered stats
    pub fn decide_global_adjustment(stats_list: &[ColorStats]) -> GlobalColorParam {
        if stats_list.is_empty() {
            return GlobalColorParam::default();
        }

        // Exclude outliers using MAD
        let filtered = Self::exclude_outliers(stats_list);
        if filtered.is_empty() {
            return GlobalColorParam::default();
        }

        // Calculate median of paper/ink colors
        let bg_r = Self::percentile_f64(
            &filtered.iter().map(|s| s.paper_r).collect::<Vec<_>>(),
            50.0,
        );
        let bg_g = Self::percentile_f64(
            &filtered.iter().map(|s| s.paper_g).collect::<Vec<_>>(),
            50.0,
        );
        let bg_b = Self::percentile_f64(
            &filtered.iter().map(|s| s.paper_b).collect::<Vec<_>>(),
            50.0,
        );

        let ink_r =
            Self::percentile_f64(&filtered.iter().map(|s| s.ink_r).collect::<Vec<_>>(), 50.0);
        let ink_g =
            Self::percentile_f64(&filtered.iter().map(|s| s.ink_g).collect::<Vec<_>>(), 50.0);
        let ink_b =
            Self::percentile_f64(&filtered.iter().map(|s| s.ink_b).collect::<Vec<_>>(), 50.0);

        // C#互換: ink色が明るすぎる場合は補正をスキップ
        // (画像の大部分が白い場合、5%パーセンタイルでは実際のインクを捉えられない)
        let ink_lum = 0.299 * ink_r + 0.587 * ink_g + 0.114 * ink_b;
        let paper_lum = 0.299 * bg_r + 0.587 * bg_g + 0.114 * bg_b;
        let contrast = paper_lum - ink_lum;

        // コントラストが小さい場合は補正をスキップ
        // - ink輝度が100以上: 本来のインク色ではなく、薄灰色を誤検出している
        // - コントラストが100未満: 既に十分なコントラストがある
        // C#版では元々良好な画像には補正が効かない設計
        if contrast < 100.0 || ink_lum > 100.0 {
            return GlobalColorParam::default();
        }

        // Calculate linear scale: ink -> 0, paper -> 255
        let (scale_r, offset_r) = Self::linear_scale(bg_r, ink_r);
        let (scale_g, offset_g) = Self::linear_scale(bg_g, ink_g);
        let (scale_b, offset_b) = Self::linear_scale(bg_b, ink_b);

        // Calculate ghost suppression threshold
        let clamp8 = |v: f64| v.clamp(0.0, 255.0) as u8;

        let bg_lum_scaled = 0.299 * clamp8(bg_r * scale_r + offset_r) as f64
            + 0.587 * clamp8(bg_g * scale_g + offset_g) as f64
            + 0.114 * clamp8(bg_b * scale_b + offset_b) as f64;

        let ink_lum_scaled = 0.299 * clamp8(ink_r * scale_r + offset_r) as f64
            + 0.587 * clamp8(ink_g * scale_g + offset_g) as f64
            + 0.114 * clamp8(ink_b * scale_b + offset_b) as f64;

        // Ghost threshold = midpoint between paper and ink
        let ghost_threshold = ((ink_lum_scaled + bg_lum_scaled) * 0.5).clamp(0.0, 255.0) as u8;

        GlobalColorParam {
            scale_r,
            scale_g,
            scale_b,
            offset_r,
            offset_g,
            offset_b,
            ghost_suppress_threshold: ghost_threshold,
            white_clip_range: DEFAULT_WHITE_CLIP_RANGE,
            paper_r: bg_r.round() as u8,
            paper_g: bg_g.round() as u8,
            paper_b: bg_b.round() as u8,
            sat_threshold: DEFAULT_SAT_THRESHOLD,
            color_dist_threshold: DEFAULT_COLOR_DIST_THRESHOLD,
            bleed_hue_min: 20.0,
            bleed_hue_max: 65.0,
            bleed_value_min: 0.35,
            bleed_suppression: BleedSuppression::default(),
        }
    }

    /// Apply global color adjustment to an image
    pub fn apply_adjustment(image: &mut RgbImage, params: &GlobalColorParam) {
        let (w, h) = image.dimensions();
        let clip_start = params.ghost_suppress_threshold as i32;
        let clip_end = (255 - params.white_clip_range as i32).clamp(0, 255);

        for y in 0..h {
            for x in 0..w {
                let pixel = image.get_pixel(x, y);
                let (src_r, src_g, src_b) = (pixel.0[0], pixel.0[1], pixel.0[2]);

                // Linear color correction
                let mut r = Self::clamp8(src_r as f64 * params.scale_r + params.offset_r);
                let mut g = Self::clamp8(src_g as f64 * params.scale_g + params.offset_g);
                let mut b = Self::clamp8(src_b as f64 * params.scale_b + params.offset_b);

                // Paper-like pixel whitening (smooth-step)
                let lum = Self::luminance(r, g, b) as i32;
                if lum >= clip_start {
                    let max = r.max(g).max(b);
                    let min = r.min(g).min(b);
                    let sat = if max == 0 {
                        0
                    } else {
                        (max - min) as i32 * 255 / max as i32
                    };

                    let dist = (r as i32 - params.paper_r as i32).abs()
                        + (g as i32 - params.paper_g as i32).abs()
                        + (b as i32 - params.paper_b as i32).abs();

                    if sat < params.sat_threshold as i32
                        && dist < params.color_dist_threshold as i32
                    {
                        let t = ((lum - clip_start) as f64 / (clip_end - clip_start + 1) as f64)
                            .clamp(0.0, 1.0);
                        let wgt = t * t * (3.0 - 2.0 * t); // Smooth-step

                        r = Self::clamp8(r as f64 + (255.0 - r as f64) * wgt);
                        g = Self::clamp8(g as f64 + (255.0 - g as f64) * wgt);
                        b = Self::clamp8(b as f64 + (255.0 - b as f64) * wgt);
                    }
                }

                // C#互換: パステルピンク(赤桃色)のみ完全白化
                // Note: Phase 1.3のBleedSuppressionは削除(C#版に存在しない機能で灰色化の原因)
                let (hue, _, _) = Self::rgb_to_hsv(r, g, b);

                let max2 = r.max(g).max(b);
                let min2 = r.min(g).min(b);
                let sat2 = if max2 == 0 {
                    0
                } else {
                    (max2 - min2) as i32 * 255 / max2 as i32
                };
                let lum2 = Self::luminance(r, g, b);

                // C#版と同じ条件: 高輝度 + 低彩度 + 赤桃色Hue範囲のみ
                let is_pastel_pink = lum2 > 230 && sat2 < 30 && (hue <= 40.0 || hue >= 330.0);

                if is_pastel_pink {
                    r = 255;
                    g = 255;
                    b = 255;
                }

                image.put_pixel(x, y, Rgb([r, g, b]));
            }
        }
    }

    /// Apply bleed-through suppression only (without other adjustments)
    ///
    /// Phase 1.3: Dedicated function for bleed-through removal
    pub fn apply_bleed_suppression(image: &mut RgbImage, bleed_config: &BleedSuppression) {
        if !bleed_config.enabled {
            return;
        }

        let (w, h) = image.dimensions();

        for y in 0..h {
            for x in 0..w {
                let pixel = image.get_pixel(x, y);
                let (r, g, b) = (pixel.0[0], pixel.0[1], pixel.0[2]);

                let (hue, sat, val) = Self::rgb_to_hsv(r, g, b);

                if bleed_config.is_bleed_through(hue, sat, val) {
                    let strength = bleed_config.strength;
                    let new_r = Self::clamp8(r as f64 + (255.0 - r as f64) * strength as f64);
                    let new_g = Self::clamp8(g as f64 + (255.0 - g as f64) * strength as f64);
                    let new_b = Self::clamp8(b as f64 + (255.0 - b as f64) * strength as f64);
                    image.put_pixel(x, y, Rgb([new_r, new_g, new_b]));
                }
            }
        }
    }

    /// Detect bleed-through percentage in an image
    ///
    /// Returns the percentage of pixels that match bleed-through characteristics.
    pub fn detect_bleed_percentage(image: &RgbImage, bleed_config: &BleedSuppression) -> f64 {
        if !bleed_config.enabled {
            return 0.0;
        }

        let (w, h) = image.dimensions();
        let mut bleed_count = 0u64;

        for y in (0..h).step_by(SAMPLE_STEP as usize) {
            for x in (0..w).step_by(SAMPLE_STEP as usize) {
                let pixel = image.get_pixel(x, y);
                let (r, g, b) = (pixel.0[0], pixel.0[1], pixel.0[2]);
                let (hue, sat, val) = Self::rgb_to_hsv(r, g, b);

                if bleed_config.is_bleed_through(hue, sat, val) {
                    bleed_count += 1;
                }
            }
        }

        let sample_total = ((w / SAMPLE_STEP) * (h / SAMPLE_STEP)) as f64;
        if sample_total > 0.0 {
            (bleed_count as f64 / sample_total) * 100.0
        } else {
            0.0
        }
    }

    /// Analyze multiple pages and return statistics with outliers filtered per group
    pub fn analyze_book_pages(
        image_paths: &[PathBuf],
    ) -> Result<(Vec<ColorStats>, Vec<ColorStats>)> {
        let stats_results: Vec<Result<ColorStats>> = image_paths
            .par_iter()
            .enumerate()
            .map(|(i, path)| {
                let mut stats = Self::calculate_stats(path)?;
                stats.page_number = i + 1;
                Ok(stats)
            })
            .collect();

        let stats: Vec<ColorStats> = stats_results.into_iter().filter_map(|r| r.ok()).collect();

        if stats.is_empty() {
            return Err(ColorStatsError::NoValidPages);
        }

        // Split into odd and even pages
        let odd: Vec<ColorStats> = stats
            .iter()
            .filter(|s| s.page_number % 2 == 1)
            .cloned()
            .collect();
        let even: Vec<ColorStats> = stats
            .iter()
            .filter(|s| s.page_number % 2 == 0)
            .cloned()
            .collect();

        Ok((odd, even))
    }

    // ============================================================
    // Private Helper Functions
    // ============================================================

    fn luminance(r: u8, g: u8, b: u8) -> u8 {
        (0.299 * r as f64 + 0.587 * g as f64 + 0.114 * b as f64).round() as u8
    }

    fn clamp8(v: f64) -> u8 {
        v.clamp(0.0, 255.0).round() as u8
    }

    fn linear_scale(bg: f64, ink: f64) -> (f64, f64) {
        let diff = bg - ink;
        if diff < 1.0 {
            return (1.0, 0.0);
        }
        let s = (255.0 / diff).clamp(MIN_SCALE, MAX_SCALE);
        let o = -ink * s;
        (s, o)
    }

    fn percentile_f64(values: &[f64], p: f64) -> f64 {
        if values.is_empty() {
            return 0.0;
        }
        let mut sorted = values.to_vec();
        sorted.sort_by(|a, b| a.total_cmp(b));

        let rank = (p / 100.0) * (sorted.len() - 1) as f64;
        let lo = rank.floor() as usize;
        let hi = rank.ceil() as usize;

        if lo == hi {
            sorted[lo]
        } else {
            sorted[lo] + (sorted[hi] - sorted[lo]) * (rank - lo as f64)
        }
    }

    fn rgb_to_hsv(r: u8, g: u8, b: u8) -> (f32, f32, f32) {
        let rf = r as f32 / 255.0;
        let gf = g as f32 / 255.0;
        let bf = b as f32 / 255.0;

        let max = rf.max(gf).max(bf);
        let min = rf.min(gf).min(bf);
        let v = max;
        let d = max - min;
        let s = if max == 0.0 { 0.0 } else { d / max };

        let h = if d == 0.0 {
            0.0
        } else if max == rf {
            60.0 * (((gf - bf) / d) % 6.0)
        } else if max == gf {
            60.0 * (((bf - rf) / d) + 2.0)
        } else {
            60.0 * (((rf - gf) / d) + 4.0)
        };

        let h = if h < 0.0 { h + 360.0 } else { h };
        (h, s, v)
    }
}

// ============================================================
// Tests
// ============================================================

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

    #[test]
    fn test_default_global_color_param() {
        let params = GlobalColorParam::default();
        assert_eq!(params.scale_r, 1.0);
        assert_eq!(params.scale_g, 1.0);
        assert_eq!(params.scale_b, 1.0);
        assert_eq!(params.offset_r, 0.0);
        assert_eq!(params.ghost_suppress_threshold, 200);
    }

    #[test]
    fn test_color_stats_luminance() {
        let stats = ColorStats {
            page_number: 1,
            paper_r: 255.0,
            paper_g: 255.0,
            paper_b: 255.0,
            ink_r: 0.0,
            ink_g: 0.0,
            ink_b: 0.0,
            ..Default::default()
        };

        assert!((stats.paper_luminance() - 255.0).abs() < 0.1);
        assert!((stats.ink_luminance() - 0.0).abs() < 0.1);
    }

    #[test]
    fn test_luminance_calculation() {
        assert_eq!(ColorAnalyzer::luminance(255, 255, 255), 255);
        assert_eq!(ColorAnalyzer::luminance(0, 0, 0), 0);
    }

    #[test]
    fn test_linear_scale() {
        let (s, o) = ColorAnalyzer::linear_scale(255.0, 0.0);
        assert!((s - 1.0).abs() < 0.01);
        assert!((o - 0.0).abs() < 0.01);

        // When ink is 50, paper is 200, we need to scale to 0-255
        let (s, _o) = ColorAnalyzer::linear_scale(200.0, 50.0);
        // 50 -> 0, 200 -> 255
        // s * 50 + o = 0  =>  o = -50s
        // s * 200 + o = 255  =>  200s - 50s = 255  =>  150s = 255  =>  s = 1.7
        assert!(s > 1.0);
    }

    #[test]
    fn test_percentile() {
        let values = vec![1.0, 2.0, 3.0, 4.0, 5.0];
        assert!((ColorAnalyzer::percentile_f64(&values, 50.0) - 3.0).abs() < 0.01);
        assert!((ColorAnalyzer::percentile_f64(&values, 0.0) - 1.0).abs() < 0.01);
        assert!((ColorAnalyzer::percentile_f64(&values, 100.0) - 5.0).abs() < 0.01);
    }

    #[test]
    fn test_exclude_outliers_small_list() {
        let stats = vec![
            ColorStats {
                page_number: 1,
                paper_r: 250.0,
                paper_g: 250.0,
                paper_b: 250.0,
                ..Default::default()
            },
            ColorStats {
                page_number: 2,
                paper_r: 240.0,
                paper_g: 240.0,
                paper_b: 240.0,
                ..Default::default()
            },
        ];

        let filtered = ColorAnalyzer::exclude_outliers(&stats);
        assert_eq!(filtered.len(), 2); // Too few to filter
    }

    #[test]
    fn test_exclude_outliers() {
        let stats = vec![
            ColorStats {
                page_number: 1,
                paper_r: 250.0,
                paper_g: 250.0,
                paper_b: 250.0,
                ..Default::default()
            },
            ColorStats {
                page_number: 2,
                paper_r: 245.0,
                paper_g: 245.0,
                paper_b: 245.0,
                ..Default::default()
            },
            ColorStats {
                page_number: 3,
                paper_r: 248.0,
                paper_g: 248.0,
                paper_b: 248.0,
                ..Default::default()
            },
            ColorStats {
                page_number: 4,
                paper_r: 100.0,
                paper_g: 100.0,
                paper_b: 100.0,
                ..Default::default()
            }, // Outlier
            ColorStats {
                page_number: 5,
                paper_r: 252.0,
                paper_g: 252.0,
                paper_b: 252.0,
                ..Default::default()
            },
        ];

        let filtered = ColorAnalyzer::exclude_outliers(&stats);
        // Page 4 should be excluded as an outlier
        assert!(filtered.len() < stats.len() || filtered.iter().all(|s| s.page_number != 4));
    }

    #[test]
    fn test_decide_global_adjustment() {
        let stats = vec![ColorStats {
            page_number: 1,
            paper_r: 250.0,
            paper_g: 248.0,
            paper_b: 245.0,
            ink_r: 10.0,
            ink_g: 10.0,
            ink_b: 10.0,
            ..Default::default()
        }];

        let params = ColorAnalyzer::decide_global_adjustment(&stats);
        assert!(params.scale_r > 0.9);
        assert!(params.paper_r > 240);
    }

    #[test]
    fn test_rgb_to_hsv() {
        // Red
        let (h, s, v) = ColorAnalyzer::rgb_to_hsv(255, 0, 0);
        assert!(h.abs() < 1.0 || (h - 360.0).abs() < 1.0);
        assert!((s - 1.0).abs() < 0.01);
        assert!((v - 1.0).abs() < 0.01);

        // White
        let (_, s, v) = ColorAnalyzer::rgb_to_hsv(255, 255, 255);
        assert!((s - 0.0).abs() < 0.01);
        assert!((v - 1.0).abs() < 0.01);
    }

    #[test]
    fn test_apply_adjustment_identity() {
        let mut img = RgbImage::from_pixel(10, 10, Rgb([128, 128, 128]));
        let params = GlobalColorParam::default();

        ColorAnalyzer::apply_adjustment(&mut img, &params);

        // With identity transform, pixels should be close to original
        let pixel = img.get_pixel(5, 5);
        assert!(pixel.0[0] > 100 && pixel.0[0] < 200);
    }

    #[test]
    fn test_image_not_found() {
        let result = ColorAnalyzer::calculate_stats(Path::new("/nonexistent/image.png"));
        assert!(matches!(result, Err(ColorStatsError::ImageNotFound(_))));
    }

    #[test]
    fn test_calculate_stats_from_image() {
        let img = RgbImage::from_pixel(100, 100, Rgb([240, 238, 235]));
        let stats = ColorAnalyzer::calculate_stats_from_image(&img, 1);

        assert_eq!(stats.page_number, 1);
        // Uniform image should have paper close to pixel values
        assert!(stats.paper_r > 230.0);
    }

    #[test]
    fn test_send_sync() {
        fn assert_send_sync<T: Send + Sync>() {}
        assert_send_sync::<ColorStats>();
        assert_send_sync::<GlobalColorParam>();
        assert_send_sync::<ColorStatsError>();
    }

    #[test]
    fn test_error_types() {
        let _err1 = ColorStatsError::ImageNotFound(PathBuf::from("/test"));
        let _err2 = ColorStatsError::InvalidImage("bad".to_string());
        let _err3 = ColorStatsError::NoValidPages;
    }

    // ============================================================
    // Spec TC ID Tests
    // ============================================================

    // TC-COLOR-001: 白背景・黒文字 - paper≈255, ink≈0
    #[test]
    fn test_tc_color_001_white_background_black_text() {
        // Create image with mostly white background and some black pixels
        let mut img = RgbImage::from_pixel(100, 100, Rgb([255, 255, 255]));
        // Add some black "text" pixels
        for y in 40..60 {
            for x in 20..80 {
                img.put_pixel(x, y, Rgb([0, 0, 0]));
            }
        }

        let stats = ColorAnalyzer::calculate_stats_from_image(&img, 1);

        // Paper should be close to white (255)
        assert!(
            stats.paper_luminance() > 240.0,
            "Paper luminance {} should be > 240",
            stats.paper_luminance()
        );

        // Ink should be close to black (0)
        assert!(
            stats.ink_luminance() < 30.0,
            "Ink luminance {} should be < 30",
            stats.ink_luminance()
        );
    }

    // TC-COLOR-002: 黄ばんだ紙 - paper<255, 補正で白化
    #[test]
    fn test_tc_color_002_yellowed_paper_correction() {
        // Create image with yellowed paper (cream/beige tint)
        let mut img = RgbImage::from_pixel(100, 100, Rgb([245, 235, 210])); // Yellowed paper
        // Add some dark text
        for y in 40..60 {
            for x in 20..80 {
                img.put_pixel(x, y, Rgb([30, 25, 20]));
            }
        }

        let stats = ColorAnalyzer::calculate_stats_from_image(&img, 1);

        // Paper color should be less than pure white
        assert!(
            stats.paper_r < 255.0 || stats.paper_g < 255.0 || stats.paper_b < 255.0,
            "Yellowed paper should not be pure white"
        );

        // Blue channel should be lower than red (yellowing)
        assert!(
            stats.paper_b < stats.paper_r,
            "Yellowed paper should have lower blue than red"
        );

        // After correction, should become more neutral
        let all_stats = vec![stats];
        let params = ColorAnalyzer::decide_global_adjustment(&all_stats);

        // Scale should correct the yellowing (blue needs more boost)
        assert!(
            params.scale_b >= params.scale_r,
            "Blue scale {} should be >= red scale {} to correct yellowing",
            params.scale_b,
            params.scale_r
        );
    }

    // TC-COLOR-003: ゴースト抑制パラメータ計算
    #[test]
    fn test_tc_color_003_ghost_suppression_params() {
        // Create realistic book page: white paper with dark text
        let mut img = RgbImage::from_pixel(100, 100, Rgb([245, 243, 240])); // Slightly off-white paper
        // Add dark text
        for y in 30..40 {
            for x in 20..80 {
                img.put_pixel(x, y, Rgb([30, 28, 25])); // Dark ink
            }
        }
        // Add faint ghost/bleed-through (between ink and paper)
        for y in 60..70 {
            for x in 20..80 {
                img.put_pixel(x, y, Rgb([200, 198, 195])); // Ghost - lighter than ink, darker than paper
            }
        }

        let stats = ColorAnalyzer::calculate_stats_from_image(&img, 1);
        let params = ColorAnalyzer::decide_global_adjustment(&[stats]);

        // Ghost suppression threshold should be between ink and paper luminance
        // Paper luminance ≈ 243, Ink luminance ≈ 28
        // After scaling, threshold should be around midpoint
        assert!(
            params.ghost_suppress_threshold > 0 && params.ghost_suppress_threshold < 255,
            "Ghost suppression threshold {} should be in valid range",
            params.ghost_suppress_threshold
        );

        // Scale should be positive (mapping ink to 0, paper to 255)
        assert!(
            params.scale_r > 0.0 && params.scale_g > 0.0 && params.scale_b > 0.0,
            "Scale factors should be positive: R={}, G={}, B={}",
            params.scale_r,
            params.scale_g,
            params.scale_b
        );

        // Paper color should be detected
        assert!(
            params.paper_r > 200 && params.paper_g > 200 && params.paper_b > 200,
            "Paper color should be light: R={}, G={}, B={}",
            params.paper_r,
            params.paper_g,
            params.paper_b
        );
    }

    // TC-COLOR-004: カラー画像 - 彩度保持
    #[test]
    fn test_tc_color_004_color_image_saturation_preserved() {
        // Create image with colored content
        let mut img = RgbImage::from_pixel(100, 100, Rgb([255, 255, 255]));
        // Add red block
        for y in 20..40 {
            for x in 20..40 {
                img.put_pixel(x, y, Rgb([255, 50, 50])); // Red
            }
        }
        // Add blue block
        for y in 60..80 {
            for x in 60..80 {
                img.put_pixel(x, y, Rgb([50, 50, 255])); // Blue
            }
        }

        let _original_red = *img.get_pixel(30, 30);
        let _original_blue = *img.get_pixel(70, 70);

        let stats = ColorAnalyzer::calculate_stats_from_image(&img, 1);
        let params = ColorAnalyzer::decide_global_adjustment(&[stats]);
        ColorAnalyzer::apply_adjustment(&mut img, &params);

        // Check that colored pixels still have color (not desaturated to gray)
        let adjusted_red = img.get_pixel(30, 30);
        let adjusted_blue = img.get_pixel(70, 70);

        // Red pixel should still be predominantly red
        assert!(
            adjusted_red.0[0] > adjusted_red.0[1] && adjusted_red.0[0] > adjusted_red.0[2],
            "Red pixel should remain red after adjustment"
        );

        // Blue pixel should still be predominantly blue
        assert!(
            adjusted_blue.0[2] > adjusted_blue.0[0] && adjusted_blue.0[2] > adjusted_blue.0[1],
            "Blue pixel should remain blue after adjustment"
        );
    }

    // TC-COLOR-005: 外れ値ページ - MADで除外
    #[test]
    fn test_tc_color_005_outlier_exclusion_mad() {
        // Create stats with one obvious outlier
        let stats = vec![
            ColorStats {
                page_number: 1,
                paper_r: 250.0,
                paper_g: 250.0,
                paper_b: 250.0,
                ink_r: 10.0,
                ink_g: 10.0,
                ink_b: 10.0,
                ..Default::default()
            },
            ColorStats {
                page_number: 2,
                paper_r: 248.0,
                paper_g: 248.0,
                paper_b: 248.0,
                ink_r: 12.0,
                ink_g: 12.0,
                ink_b: 12.0,
                ..Default::default()
            },
            ColorStats {
                page_number: 3,
                paper_r: 252.0,
                paper_g: 252.0,
                paper_b: 252.0,
                ink_r: 8.0,
                ink_g: 8.0,
                ink_b: 8.0,
                ..Default::default()
            },
            ColorStats {
                page_number: 4,
                paper_r: 50.0, // Extreme outlier - dark page
                paper_g: 50.0,
                paper_b: 50.0,
                ink_r: 10.0,
                ink_g: 10.0,
                ink_b: 10.0,
                ..Default::default()
            },
            ColorStats {
                page_number: 5,
                paper_r: 249.0,
                paper_g: 249.0,
                paper_b: 249.0,
                ink_r: 11.0,
                ink_g: 11.0,
                ink_b: 11.0,
                ..Default::default()
            },
            ColorStats {
                page_number: 6,
                paper_r: 251.0,
                paper_g: 251.0,
                paper_b: 251.0,
                ink_r: 9.0,
                ink_g: 9.0,
                ink_b: 9.0,
                ..Default::default()
            },
        ];

        let filtered = ColorAnalyzer::exclude_outliers(&stats);

        // The outlier (page 4 with paper_r=50) should be excluded
        let has_outlier = filtered.iter().any(|s| s.page_number == 4);

        assert!(
            !has_outlier || filtered.len() < stats.len(),
            "Outlier page 4 should be excluded by MAD filter"
        );

        // Remaining pages should have consistent paper color
        if filtered.len() > 1 {
            let paper_values: Vec<f64> = filtered.iter().map(|s| s.paper_r).collect();
            let min = paper_values.iter().cloned().fold(f64::INFINITY, f64::min);
            let max = paper_values
                .iter()
                .cloned()
                .fold(f64::NEG_INFINITY, f64::max);

            assert!(
                max - min < 50.0,
                "Filtered paper values should be consistent (range {} is too large)",
                max - min
            );
        }
    }

    // ============================================================
    // Phase 1.3: BleedSuppression Tests
    // ============================================================

    // TC-BLEED-001: BleedSuppression デフォルト値 (C#互換)
    #[test]
    fn test_bleed_suppression_default() {
        let bleed = BleedSuppression::default();
        assert_eq!(bleed.hue_min, 20.0);
        assert_eq!(bleed.hue_max, 65.0);
        // C# version: no saturation filter, BleedValueMin = 0.35
        assert_eq!(bleed.saturation_max, 1.0);  // No saturation filter
        assert_eq!(bleed.value_min, 0.35);      // Match C# BleedValueMin
        assert!(bleed.enabled);
        assert_eq!(bleed.strength, 1.0);
    }

    // TC-BLEED-002: 裏写り検出 - 黄色系 (C#互換)
    #[test]
    fn test_bleed_detection_yellow_bleed() {
        let bleed = BleedSuppression::default();

        // Yellow bleed-through (hue=40, any sat, high val)
        assert!(bleed.is_bleed_through(40.0, 0.2, 0.8));

        // C# version doesn't filter by saturation, so high sat yellow is also bleed
        assert!(bleed.is_bleed_through(40.0, 0.5, 0.8));

        // Not bleed: dark yellow (value < 0.35)
        assert!(!bleed.is_bleed_through(40.0, 0.2, 0.3));
    }

    // TC-BLEED-003: 裏写り検出 - 範囲外
    #[test]
    fn test_bleed_detection_out_of_range() {
        let bleed = BleedSuppression::default();

        // Blue (hue=240) - not bleed
        assert!(!bleed.is_bleed_through(240.0, 0.2, 0.8));

        // Red (hue=0) - not bleed
        assert!(!bleed.is_bleed_through(0.0, 0.2, 0.8));

        // Green (hue=120) - not bleed
        assert!(!bleed.is_bleed_through(120.0, 0.2, 0.8));
    }

    // TC-BLEED-004: 裏写り検出 - 無効時
    #[test]
    fn test_bleed_detection_disabled() {
        let bleed = BleedSuppression::disabled();

        // Should not detect anything when disabled
        assert!(!bleed.is_bleed_through(40.0, 0.2, 0.8));
    }

    // TC-BLEED-005: 裏写り抑制適用
    #[test]
    fn test_apply_bleed_suppression() {
        // Create image with yellow bleed-through
        let mut img = RgbImage::from_pixel(10, 10, Rgb([255, 240, 200])); // Light yellow

        let bleed = BleedSuppression::default();
        ColorAnalyzer::apply_bleed_suppression(&mut img, &bleed);

        // Pixel should be whitened
        let pixel = img.get_pixel(5, 5);
        assert!(
            pixel.0[0] > 250 && pixel.0[1] > 250 && pixel.0[2] > 250,
            "Bleed pixel should be whitened: {:?}",
            pixel
        );
    }

    // TC-BLEED-006: 裏写り検出率
    #[test]
    fn test_detect_bleed_percentage() {
        // Create image with some bleed-through
        let mut img = RgbImage::from_pixel(100, 100, Rgb([255, 255, 255])); // White

        // Add bleed-through area (25% of image)
        for y in 0..50 {
            for x in 0..50 {
                img.put_pixel(x, y, Rgb([255, 240, 200])); // Light yellow
            }
        }

        let bleed = BleedSuppression::default();
        let percentage = ColorAnalyzer::detect_bleed_percentage(&img, &bleed);

        // Should detect roughly 25% bleed
        assert!(
            percentage > 10.0 && percentage < 40.0,
            "Bleed percentage {} should be around 25%",
            percentage
        );
    }

    // TC-BLEED-007: アグレッシブモード
    #[test]
    fn test_bleed_suppression_aggressive() {
        let bleed = BleedSuppression::aggressive();

        // Aggressive should have wider ranges
        assert!(bleed.hue_min < 20.0);
        assert!(bleed.hue_max > 65.0);
        assert!(bleed.saturation_max > 0.30);
        assert!(bleed.value_min < 0.70);
    }

    // TC-BLEED-008: ジェントルモード
    #[test]
    fn test_bleed_suppression_gentle() {
        let bleed = BleedSuppression::gentle();

        // Gentle should have narrower ranges
        assert!(bleed.hue_min > 20.0);
        assert!(bleed.hue_max < 65.0);
        assert!(bleed.saturation_max < 0.30);
        assert!(bleed.value_min > 0.70);
        assert!(bleed.strength < 1.0);
    }

    // TC-BLEED-009: カスタム設定
    #[test]
    fn test_bleed_suppression_custom() {
        let bleed = BleedSuppression::new(30.0, 50.0, 0.25, 0.75);

        assert_eq!(bleed.hue_min, 30.0);
        assert_eq!(bleed.hue_max, 50.0);
        assert_eq!(bleed.saturation_max, 0.25);
        assert_eq!(bleed.value_min, 0.75);
    }

    // TC-BLEED-010: GlobalColorParamにBleedSuppression含む
    #[test]
    fn test_global_color_param_includes_bleed() {
        let params = GlobalColorParam::default();

        // Should include default bleed suppression
        assert!(params.bleed_suppression.enabled);
        assert_eq!(params.bleed_suppression.hue_min, 20.0);
    }
}