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
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
//! RealESRGAN Integration module
//!
//! Provides integration with RealESRGAN AI upscaling model.
//!
//! # Features
//!
//! - 2x/4x AI upscaling for scanned images
//! - Multiple model support (general, anime, video)
//! - VRAM-aware tile processing
//! - GPU acceleration with fallback
//!
//! # Example
//!
//! ```rust,no_run
//! use superbook_pdf::{RealEsrgan, RealEsrganOptions};
//!
//! // Configure upscaling
//! let options = RealEsrganOptions::builder()
//!     .scale(2)
//!     .tile_size(400)
//!     .build();
//!
//! // Upscale an image
//! // let result = RealEsrgan::new().upscale("input.png", "output.png", &options);
//! ```

use crate::ai_bridge::{AiBridgeError, AiTool, SubprocessBridge};
use std::path::{Path, PathBuf};
use std::time::Duration;
use thiserror::Error;

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

/// Default tile size for balanced performance
const DEFAULT_TILE_SIZE: u32 = 400;

/// Tile size for high quality processing (more VRAM)
#[allow(dead_code)]
const HIGH_QUALITY_TILE_SIZE: u32 = 512;

/// Tile size for anime content optimization
const ANIME_TILE_SIZE: u32 = 256;

/// Tile size for low VRAM environments
const LOW_VRAM_TILE_SIZE: u32 = 128;

/// Default tile padding
const DEFAULT_TILE_PADDING: u32 = 10;

/// Minimum allowed tile size
const MIN_TILE_SIZE: u32 = 64;

/// Maximum allowed tile size
const MAX_TILE_SIZE: u32 = 1024;

/// Default scale factor
const DEFAULT_SCALE: u32 = 2;

/// Base VRAM for tile size calculation (4GB)
const BASE_VRAM_MB: u64 = 4096;

/// RealESRGAN error types
#[derive(Debug, Error)]
pub enum RealEsrganError {
    #[error("Model not found: {0}")]
    ModelNotFound(String),

    #[error("Invalid scale: {0} (must be 2 or 4)")]
    InvalidScale(u32),

    #[error("Input image not found: {0}")]
    InputNotFound(PathBuf),

    #[error("Output directory not writable: {0}")]
    OutputNotWritable(PathBuf),

    #[error("Processing failed: {0}")]
    ProcessingFailed(String),

    #[error("GPU memory insufficient (need {required}MB, available {available}MB)")]
    InsufficientVram { required: u64, available: u64 },

    #[error("Bridge error: {0}")]
    BridgeError(#[from] AiBridgeError),

    #[error("Image error: {0}")]
    ImageError(String),

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

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

/// RealESRGAN options
#[derive(Debug, Clone)]
pub struct RealEsrganOptions {
    /// Upscale factor
    pub scale: u32,
    /// Model selection
    pub model: RealEsrganModel,
    /// Tile size (pixels)
    pub tile_size: u32,
    /// Tile padding
    pub tile_padding: u32,
    /// Output format
    pub output_format: OutputFormat,
    /// Enable face enhancement
    pub face_enhance: bool,
    /// GPU ID (None for auto)
    pub gpu_id: Option<u32>,
    /// Use FP16 for speed
    pub fp16: bool,
}

impl Default for RealEsrganOptions {
    fn default() -> Self {
        Self {
            scale: DEFAULT_SCALE,
            model: RealEsrganModel::X4Plus,
            tile_size: DEFAULT_TILE_SIZE,
            tile_padding: DEFAULT_TILE_PADDING,
            output_format: OutputFormat::Png,
            face_enhance: false,
            gpu_id: None,
            fp16: true,
        }
    }
}

impl RealEsrganOptions {
    /// Create a new options builder
    pub fn builder() -> RealEsrganOptionsBuilder {
        RealEsrganOptionsBuilder::default()
    }

    /// Create options for 4x upscaling (high quality)
    pub fn x4_high_quality() -> Self {
        Self {
            scale: 4,
            model: RealEsrganModel::X4Plus,
            tile_size: ANIME_TILE_SIZE, // Smaller tiles for quality
            fp16: false,                // More accurate
            ..Default::default()
        }
    }

    /// Create options optimized for anime/illustrations
    pub fn anime() -> Self {
        Self {
            scale: 4,
            model: RealEsrganModel::X4PlusAnime,
            ..Default::default()
        }
    }

    /// Create options for low VRAM (< 4GB)
    pub fn low_vram() -> Self {
        Self {
            tile_size: LOW_VRAM_TILE_SIZE,
            tile_padding: 8,
            fp16: true,
            ..Default::default()
        }
    }
}

/// Builder for RealEsrganOptions
#[derive(Debug, Default)]
pub struct RealEsrganOptionsBuilder {
    options: RealEsrganOptions,
}

impl RealEsrganOptionsBuilder {
    /// Set upscale factor (2 or 4)
    #[must_use]
    pub fn scale(mut self, scale: u32) -> Self {
        self.options.scale = if scale >= 4 { 4 } else { 2 };
        self
    }

    /// Set model type
    #[must_use]
    pub fn model(mut self, model: RealEsrganModel) -> Self {
        self.options.model = model;
        self
    }

    /// Set tile size for memory efficiency
    #[must_use]
    pub fn tile_size(mut self, size: u32) -> Self {
        self.options.tile_size = size.clamp(MIN_TILE_SIZE, MAX_TILE_SIZE);
        self
    }

    /// Set tile padding
    #[must_use]
    pub fn tile_padding(mut self, padding: u32) -> Self {
        self.options.tile_padding = padding;
        self
    }

    /// Set output format
    #[must_use]
    pub fn output_format(mut self, format: OutputFormat) -> Self {
        self.options.output_format = format;
        self
    }

    /// Enable face enhancement
    #[must_use]
    pub fn face_enhance(mut self, enable: bool) -> Self {
        self.options.face_enhance = enable;
        self
    }

    /// Set GPU device ID
    #[must_use]
    pub fn gpu_id(mut self, id: u32) -> Self {
        self.options.gpu_id = Some(id);
        self
    }

    /// Enable FP16 mode for speed
    #[must_use]
    pub fn fp16(mut self, enable: bool) -> Self {
        self.options.fp16 = enable;
        self
    }

    /// Build the options
    #[must_use]
    pub fn build(self) -> RealEsrganOptions {
        self.options
    }
}

/// RealESRGAN model types
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub enum RealEsrganModel {
    /// RealESRGAN_x4plus (high quality, general purpose)
    #[default]
    X4Plus,
    /// RealESRGAN_x4plus_anime (anime/illustration)
    X4PlusAnime,
    /// RealESRNet_x4plus (faster, slightly lower quality)
    NetX4Plus,
    /// RealESRGAN_x2plus
    X2Plus,
    /// Custom model
    Custom(String),
}

impl RealEsrganModel {
    /// Get default scale for model
    pub fn default_scale(&self) -> u32 {
        match self {
            Self::X4Plus | Self::X4PlusAnime | Self::NetX4Plus => 4,
            Self::X2Plus => 2,
            Self::Custom(_) => 4,
        }
    }

    /// Get model name
    pub fn model_name(&self) -> &str {
        match self {
            Self::X4Plus => "RealESRGAN_x4plus",
            Self::X4PlusAnime => "RealESRGAN_x4plus_anime_6B",
            Self::NetX4Plus => "RealESRNet_x4plus",
            Self::X2Plus => "RealESRGAN_x2plus",
            Self::Custom(name) => name,
        }
    }
}

/// Output formats
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum OutputFormat {
    #[default]
    Png,
    Jpg {
        quality: u8,
    },
    Webp {
        quality: u8,
    },
}

impl OutputFormat {
    /// Get file extension
    pub fn extension(&self) -> &str {
        match self {
            OutputFormat::Png => "png",
            OutputFormat::Jpg { .. } => "jpg",
            OutputFormat::Webp { .. } => "webp",
        }
    }
}

/// Upscale result for single image
#[derive(Debug, Clone)]
pub struct UpscaleResult {
    /// Input file path
    pub input_path: PathBuf,
    /// Output file path
    pub output_path: PathBuf,
    /// Original resolution
    pub original_size: (u32, u32),
    /// Upscaled resolution
    pub upscaled_size: (u32, u32),
    /// Actual scale factor
    pub actual_scale: f32,
    /// Processing time
    pub processing_time: Duration,
    /// VRAM usage (MB)
    pub vram_used_mb: Option<u64>,
}

/// Batch upscale result
#[derive(Debug)]
pub struct BatchUpscaleResult {
    /// Successful results
    pub successful: Vec<UpscaleResult>,
    /// Failed files
    pub failed: Vec<(PathBuf, String)>,
    /// Total processing time
    pub total_time: Duration,
    /// Peak VRAM usage
    pub peak_vram_mb: Option<u64>,
}

/// RealESRGAN processor trait
pub trait RealEsrganProcessor {
    /// Upscale single image
    fn upscale(
        &self,
        input_path: &Path,
        output_path: &Path,
        options: &RealEsrganOptions,
    ) -> Result<UpscaleResult>;

    /// Batch upscale
    fn upscale_batch(
        &self,
        input_files: &[PathBuf],
        output_dir: &Path,
        options: &RealEsrganOptions,
        progress: Option<Box<dyn Fn(usize, usize) + Send>>,
    ) -> Result<BatchUpscaleResult>;

    /// Upscale all images in directory
    fn upscale_directory(
        &self,
        input_dir: &Path,
        output_dir: &Path,
        options: &RealEsrganOptions,
        progress: Option<Box<dyn Fn(usize, usize) + Send>>,
    ) -> Result<BatchUpscaleResult>;

    /// Get available models
    fn available_models(&self) -> Vec<RealEsrganModel>;

    /// Calculate recommended tile size
    fn recommended_tile_size(&self, image_size: (u32, u32), available_vram_mb: u64) -> u32;
}

/// RealESRGAN implementation
pub struct RealEsrgan {
    bridge: SubprocessBridge,
}

impl RealEsrgan {
    /// Create a new RealESRGAN processor
    pub fn new(bridge: SubprocessBridge) -> Self {
        Self { bridge }
    }

    /// Upscale single image
    pub fn upscale(
        &self,
        input_path: &Path,
        output_path: &Path,
        options: &RealEsrganOptions,
    ) -> Result<UpscaleResult> {
        if !input_path.exists() {
            return Err(RealEsrganError::InputNotFound(input_path.to_path_buf()));
        }

        // Get original image size
        let img =
            image::open(input_path).map_err(|e| RealEsrganError::ImageError(e.to_string()))?;
        let original_size = (img.width(), img.height());

        let start_time = std::time::Instant::now();

        // Create output directory if needed
        let output_dir = output_path.parent().unwrap_or(Path::new("."));
        if !output_dir.exists() {
            std::fs::create_dir_all(output_dir)
                .map_err(|_| RealEsrganError::OutputNotWritable(output_dir.to_path_buf()))?;
        }

        // Execute via bridge
        let result = self
            .bridge
            .execute(
                AiTool::RealESRGAN,
                &[input_path.to_path_buf()],
                output_dir,
                options,
            )
            .map_err(RealEsrganError::BridgeError)?;

        if !result.failed_files.is_empty() {
            let (_, error) = &result.failed_files[0];
            return Err(RealEsrganError::ProcessingFailed(error.clone()));
        }

        // Bridge saves to {output_dir}/{input_stem}_upscaled.{ext}
        // Rename to the expected output_path if different
        let bridge_output = output_dir.join(format!(
            "{}_upscaled.{}",
            input_path.file_stem().unwrap_or_default().to_string_lossy(),
            input_path.extension().unwrap_or_default().to_string_lossy()
        ));

        // Rename to expected path if different
        if bridge_output != output_path {
            if bridge_output.exists() {
                std::fs::rename(&bridge_output, output_path).map_err(|e| {
                    RealEsrganError::ProcessingFailed(format!(
                        "Failed to rename output file: {}",
                        e
                    ))
                })?;
            } else if !output_path.exists() {
                return Err(RealEsrganError::ProcessingFailed(format!(
                    "Output file not created: expected at {} or {}",
                    bridge_output.display(),
                    output_path.display()
                )));
            }
        }

        // Verify output and get upscaled size
        if !output_path.exists() {
            return Err(RealEsrganError::ProcessingFailed(format!(
                "Output file not found: {}",
                output_path.display()
            )));
        }

        let output_img =
            image::open(output_path).map_err(|e| RealEsrganError::ImageError(e.to_string()))?;
        let upscaled_size = (output_img.width(), output_img.height());
        let actual_scale = upscaled_size.0 as f32 / original_size.0 as f32;

        Ok(UpscaleResult {
            input_path: input_path.to_path_buf(),
            output_path: output_path.to_path_buf(),
            original_size,
            upscaled_size,
            actual_scale,
            processing_time: start_time.elapsed(),
            vram_used_mb: result.gpu_stats.map(|s| s.peak_vram_mb),
        })
    }

    /// Batch upscale multiple images
    pub fn upscale_batch(
        &self,
        input_files: &[PathBuf],
        output_dir: &Path,
        options: &RealEsrganOptions,
        progress: Option<Box<dyn Fn(usize, usize) + Send>>,
    ) -> Result<BatchUpscaleResult> {
        let start_time = std::time::Instant::now();
        let mut successful = Vec::new();
        let mut failed = Vec::new();

        // Create output directory
        if !output_dir.exists() {
            std::fs::create_dir_all(output_dir)
                .map_err(|_| RealEsrganError::OutputNotWritable(output_dir.to_path_buf()))?;
        }

        for (i, input_path) in input_files.iter().enumerate() {
            let output_filename = format!(
                "{}_{}x.{}",
                input_path.file_stem().unwrap_or_default().to_string_lossy(),
                options.scale,
                options.output_format.extension()
            );
            let output_path = output_dir.join(output_filename);

            match self.upscale(input_path, &output_path, options) {
                Ok(result) => successful.push(result),
                Err(e) => failed.push((input_path.clone(), e.to_string())),
            }

            if let Some(ref callback) = progress {
                callback(i + 1, input_files.len());
            }
        }

        Ok(BatchUpscaleResult {
            successful,
            failed,
            total_time: start_time.elapsed(),
            peak_vram_mb: None,
        })
    }

    /// Upscale all images in a directory
    pub fn upscale_directory(
        &self,
        input_dir: &Path,
        output_dir: &Path,
        options: &RealEsrganOptions,
        progress: Option<Box<dyn Fn(usize, usize) + Send>>,
    ) -> Result<BatchUpscaleResult> {
        // Find all image files in directory
        let mut input_files = Vec::new();
        let extensions = ["png", "jpg", "jpeg", "bmp", "tiff", "webp"];

        if input_dir.is_dir() {
            for entry in std::fs::read_dir(input_dir)? {
                let entry = entry?;
                let path = entry.path();
                if path.is_file() {
                    if let Some(ext) = path.extension() {
                        let ext_lower = ext.to_string_lossy().to_lowercase();
                        if extensions.contains(&ext_lower.as_str()) {
                            input_files.push(path);
                        }
                    }
                }
            }
        }

        // Sort for consistent ordering
        input_files.sort();

        self.upscale_batch(&input_files, output_dir, options, progress)
    }

    /// Get list of available models
    pub fn available_models(&self) -> Vec<RealEsrganModel> {
        vec![
            RealEsrganModel::X4Plus,
            RealEsrganModel::X4PlusAnime,
            RealEsrganModel::NetX4Plus,
            RealEsrganModel::X2Plus,
        ]
    }

    /// Calculate recommended tile size based on VRAM
    pub fn recommended_tile_size(&self, _image_size: (u32, u32), available_vram_mb: u64) -> u32 {
        // Empirical formula:
        // 4x upscale with FP16: ~100MB per 400x400 tile
        let scale_factor = (available_vram_mb as f64 / BASE_VRAM_MB as f64).sqrt();
        let recommended = (DEFAULT_TILE_SIZE as f64 * scale_factor) as u32;

        // Clamp to reasonable range
        recommended.clamp(MIN_TILE_SIZE, MAX_TILE_SIZE)
    }
}

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

    #[test]
    fn test_default_options() {
        let opts = RealEsrganOptions::default();

        assert_eq!(opts.scale, 2);
        assert!(matches!(opts.model, RealEsrganModel::X4Plus));
        assert_eq!(opts.tile_size, 400);
        assert_eq!(opts.tile_padding, 10);
        assert!(matches!(opts.output_format, OutputFormat::Png));
        assert!(!opts.face_enhance);
        assert!(opts.gpu_id.is_none());
        assert!(opts.fp16);
    }

    #[test]
    fn test_model_default_scale() {
        assert_eq!(RealEsrganModel::X4Plus.default_scale(), 4);
        assert_eq!(RealEsrganModel::X4PlusAnime.default_scale(), 4);
        assert_eq!(RealEsrganModel::NetX4Plus.default_scale(), 4);
        assert_eq!(RealEsrganModel::X2Plus.default_scale(), 2);
        assert_eq!(
            RealEsrganModel::Custom("test".to_string()).default_scale(),
            4
        );
    }

    #[test]
    fn test_model_names() {
        assert_eq!(RealEsrganModel::X4Plus.model_name(), "RealESRGAN_x4plus");
        assert_eq!(
            RealEsrganModel::X4PlusAnime.model_name(),
            "RealESRGAN_x4plus_anime_6B"
        );
        assert_eq!(RealEsrganModel::NetX4Plus.model_name(), "RealESRNet_x4plus");
        assert_eq!(RealEsrganModel::X2Plus.model_name(), "RealESRGAN_x2plus");
        assert_eq!(
            RealEsrganModel::Custom("MyModel".to_string()).model_name(),
            "MyModel"
        );
    }

    #[test]
    fn test_output_format_extension() {
        assert_eq!(OutputFormat::Png.extension(), "png");
        assert_eq!(OutputFormat::Jpg { quality: 90 }.extension(), "jpg");
        assert_eq!(OutputFormat::Webp { quality: 85 }.extension(), "webp");
    }

    #[test]
    fn test_recommended_tile_size() {
        // Create a mock bridge for testing
        let config = crate::ai_bridge::AiBridgeConfig {
            venv_path: PathBuf::from("tests/fixtures/test_venv"),
            ..Default::default()
        };

        // Skip if venv doesn't exist (we're just testing the algorithm)
        if config.venv_path.exists() {
            let bridge = SubprocessBridge::new(config).unwrap();
            let processor = RealEsrgan::new(bridge);

            // 8GB VRAM
            let tile_8gb = processor.recommended_tile_size((1920, 1080), 8192);
            assert!(tile_8gb >= 400);

            // 4GB VRAM
            let tile_4gb = processor.recommended_tile_size((1920, 1080), 4096);
            assert!(tile_4gb <= tile_8gb);

            // 2GB VRAM
            let tile_2gb = processor.recommended_tile_size((1920, 1080), 2048);
            assert!(tile_2gb <= tile_4gb);
        }
    }

    // Test the tile size algorithm directly
    #[test]
    fn test_tile_size_algorithm() {
        // Direct algorithm test without bridge
        let calculate_tile = |available_vram_mb: u64| -> u32 {
            let base_tile = 400;
            let base_vram = 4096_u64;
            let scale_factor = (available_vram_mb as f64 / base_vram as f64).sqrt();
            let recommended = (base_tile as f64 * scale_factor) as u32;
            recommended.clamp(128, 1024)
        };

        assert!(calculate_tile(8192) >= 400);
        assert!(calculate_tile(4096) >= 300);
        assert!(calculate_tile(2048) >= 200);
        assert!(calculate_tile(1024) >= 128);
    }

    #[test]
    fn test_builder_pattern() {
        let options = RealEsrganOptions::builder()
            .scale(4)
            .model(RealEsrganModel::X4PlusAnime)
            .tile_size(256)
            .tile_padding(16)
            .output_format(OutputFormat::Jpg { quality: 90 })
            .face_enhance(true)
            .gpu_id(0)
            .fp16(false)
            .build();

        assert_eq!(options.scale, 4);
        assert!(matches!(options.model, RealEsrganModel::X4PlusAnime));
        assert_eq!(options.tile_size, 256);
        assert_eq!(options.tile_padding, 16);
        assert!(matches!(
            options.output_format,
            OutputFormat::Jpg { quality: 90 }
        ));
        assert!(options.face_enhance);
        assert_eq!(options.gpu_id, Some(0));
        assert!(!options.fp16);
    }

    #[test]
    fn test_builder_scale_clamping() {
        // Scale should be normalized to 2 or 4
        let options = RealEsrganOptions::builder().scale(1).build();
        assert_eq!(options.scale, 2);

        let options = RealEsrganOptions::builder().scale(3).build();
        assert_eq!(options.scale, 2);

        let options = RealEsrganOptions::builder().scale(4).build();
        assert_eq!(options.scale, 4);

        let options = RealEsrganOptions::builder().scale(8).build();
        assert_eq!(options.scale, 4);
    }

    #[test]
    fn test_builder_tile_size_clamping() {
        // Tile size should be clamped to 64-1024
        let options = RealEsrganOptions::builder().tile_size(32).build();
        assert_eq!(options.tile_size, 64);

        let options = RealEsrganOptions::builder().tile_size(2000).build();
        assert_eq!(options.tile_size, 1024);

        let options = RealEsrganOptions::builder().tile_size(512).build();
        assert_eq!(options.tile_size, 512);
    }

    #[test]
    fn test_x4_high_quality_preset() {
        let options = RealEsrganOptions::x4_high_quality();

        assert_eq!(options.scale, 4);
        assert!(matches!(options.model, RealEsrganModel::X4Plus));
        assert_eq!(options.tile_size, 256);
        assert!(!options.fp16); // More accurate
    }

    #[test]
    fn test_anime_preset() {
        let options = RealEsrganOptions::anime();

        assert_eq!(options.scale, 4);
        assert!(matches!(options.model, RealEsrganModel::X4PlusAnime));
    }

    #[test]
    fn test_low_vram_preset() {
        let options = RealEsrganOptions::low_vram();

        assert_eq!(options.tile_size, 128);
        assert_eq!(options.tile_padding, 8);
        assert!(options.fp16);
    }

    // Note: The following tests require actual Python environment
    // They are marked with #[ignore] until environment is available

    // TC-RES-010: 入力ファイルなしエラー
    #[test]
    #[ignore = "requires external tool"]
    fn test_input_not_found_error() {
        let config = crate::ai_bridge::AiBridgeConfig {
            venv_path: PathBuf::from("tests/fixtures/test_venv"),
            ..Default::default()
        };
        let bridge = SubprocessBridge::new(config).unwrap();
        let processor = RealEsrgan::new(bridge);

        let result = processor.upscale(
            Path::new("/nonexistent/image.png"),
            Path::new("/tmp/output.png"),
            &RealEsrganOptions::default(),
        );

        assert!(matches!(result, Err(RealEsrganError::InputNotFound(_))));
    }

    // TC-RES-001: 単一画像アップスケール
    #[test]
    #[ignore = "requires external tool"]
    fn test_single_image_upscale() {
        let config = crate::ai_bridge::AiBridgeConfig {
            venv_path: PathBuf::from("tests/fixtures/test_venv"),
            ..Default::default()
        };
        let bridge = SubprocessBridge::new(config).unwrap();
        let processor = RealEsrgan::new(bridge);

        let temp_dir = tempfile::tempdir().unwrap();
        let output = temp_dir.path().join("upscaled.png");

        let result = processor
            .upscale(
                Path::new("tests/fixtures/small_image.png"),
                &output,
                &RealEsrganOptions::default(),
            )
            .unwrap();

        assert!(output.exists());
        assert_eq!(result.actual_scale, 2.0);
    }

    // TC-RES-002: 4x upscale test
    #[test]
    fn test_4x_upscale_options() {
        let options = RealEsrganOptions::builder().scale(4).build();
        assert_eq!(options.scale, 4);

        // Verify 4x preset
        let high_quality = RealEsrganOptions::x4_high_quality();
        assert_eq!(high_quality.scale, 4);
    }

    // TC-RES-005: Different models test
    #[test]
    fn test_different_models() {
        let models = vec![
            RealEsrganModel::X4Plus,
            RealEsrganModel::X4PlusAnime,
            RealEsrganModel::NetX4Plus,
            RealEsrganModel::X2Plus,
        ];

        for model in models {
            let options = RealEsrganOptions::builder().model(model.clone()).build();

            // Each model should have valid model name
            assert!(!options.model.model_name().is_empty());

            // Each model should have valid default scale
            assert!(model.default_scale() == 2 || model.default_scale() == 4);
        }
    }

    // Test UpscaleResult construction
    #[test]
    fn test_upscale_result_construction() {
        let result = UpscaleResult {
            input_path: PathBuf::from("input.png"),
            output_path: PathBuf::from("output.png"),
            original_size: (100, 100),
            upscaled_size: (200, 200),
            actual_scale: 2.0,
            processing_time: Duration::from_secs(5),
            vram_used_mb: Some(1024),
        };

        assert_eq!(result.input_path, PathBuf::from("input.png"));
        assert_eq!(result.output_path, PathBuf::from("output.png"));
        assert_eq!(result.original_size, (100, 100));
        assert_eq!(result.upscaled_size, (200, 200));
        assert_eq!(result.actual_scale, 2.0);
        assert_eq!(result.processing_time, Duration::from_secs(5));
        assert_eq!(result.vram_used_mb, Some(1024));
    }

    // Test BatchUpscaleResult construction
    #[test]
    fn test_batch_upscale_result_construction() {
        let successful_result = UpscaleResult {
            input_path: PathBuf::from("input.png"),
            output_path: PathBuf::from("output.png"),
            original_size: (100, 100),
            upscaled_size: (200, 200),
            actual_scale: 2.0,
            processing_time: Duration::from_secs(1),
            vram_used_mb: None,
        };

        let result = BatchUpscaleResult {
            successful: vec![successful_result],
            failed: vec![(PathBuf::from("failed.png"), "Error".to_string())],
            total_time: Duration::from_secs(10),
            peak_vram_mb: Some(2048),
        };

        assert_eq!(result.successful.len(), 1);
        assert_eq!(result.failed.len(), 1);
        assert_eq!(result.total_time, Duration::from_secs(10));
        assert_eq!(result.peak_vram_mb, Some(2048));
    }

    // Test output format quality settings
    #[test]
    fn test_output_format_quality() {
        let jpg_90 = OutputFormat::Jpg { quality: 90 };
        let jpg_50 = OutputFormat::Jpg { quality: 50 };
        let webp_80 = OutputFormat::Webp { quality: 80 };

        assert_eq!(jpg_90.extension(), "jpg");
        assert_eq!(jpg_50.extension(), "jpg");
        assert_eq!(webp_80.extension(), "webp");

        // Extract quality values
        if let OutputFormat::Jpg { quality } = jpg_90 {
            assert_eq!(quality, 90);
        }
        if let OutputFormat::Webp { quality } = webp_80 {
            assert_eq!(quality, 80);
        }
    }

    // Test error types
    #[test]
    fn test_error_types() {
        let model_err = RealEsrganError::ModelNotFound("test".to_string());
        assert!(model_err.to_string().contains("Model not found"));

        let scale_err = RealEsrganError::InvalidScale(3);
        assert!(scale_err.to_string().contains("Invalid scale"));

        let input_err = RealEsrganError::InputNotFound(PathBuf::from("/test"));
        assert!(input_err.to_string().contains("Input image not found"));

        let vram_err = RealEsrganError::InsufficientVram {
            required: 8000,
            available: 4000,
        };
        assert!(vram_err.to_string().contains("insufficient"));
    }

    // Test available models list
    #[test]
    fn test_available_models_list() {
        let config = crate::ai_bridge::AiBridgeConfig {
            venv_path: PathBuf::from("tests/fixtures/test_venv"),
            ..Default::default()
        };

        if config.venv_path.exists() {
            let bridge = SubprocessBridge::new(config).unwrap();
            let processor = RealEsrgan::new(bridge);
            let models = processor.available_models();

            assert!(!models.is_empty());
            assert!(models.len() >= 4); // At least 4 built-in models
        }
    }

    // TC-RES-003: バッチ処理, TC-RES-004: ディレクトリ処理
    // TC-RES-008: Progress callback test (unit test portion)
    #[test]
    fn test_progress_callback_structure() {
        use std::sync::{Arc, Mutex};

        let progress_log = Arc::new(Mutex::new(Vec::new()));
        let progress_clone = progress_log.clone();

        // Simulate progress callback
        let callback = move |current: usize, total: usize| {
            progress_clone.lock().unwrap().push((current, total));
        };

        // Simulate 5 progress updates
        for i in 1..=5 {
            callback(i, 5);
        }

        let recorded = progress_log.lock().unwrap();
        assert_eq!(recorded.len(), 5);
        assert_eq!(recorded[0], (1, 5));
        assert_eq!(recorded[4], (5, 5));
    }

    // Test WebP output format
    #[test]
    fn test_webp_output_format() {
        let options = RealEsrganOptions::builder()
            .output_format(OutputFormat::Webp { quality: 85 })
            .build();

        assert!(matches!(
            options.output_format,
            OutputFormat::Webp { quality: 85 }
        ));
    }

    // Test custom model support
    #[test]
    fn test_custom_model() {
        let custom = RealEsrganModel::Custom("MyCustomModel_x8".to_string());

        assert_eq!(custom.model_name(), "MyCustomModel_x8");
        assert_eq!(custom.default_scale(), 4); // Default for custom models
    }

    // Test all error variants can display
    #[test]
    fn test_error_display() {
        let errors = vec![
            RealEsrganError::ModelNotFound("test".to_string()),
            RealEsrganError::InvalidScale(3),
            RealEsrganError::InputNotFound(PathBuf::from("/test")),
            RealEsrganError::OutputNotWritable(PathBuf::from("/test")),
            RealEsrganError::ProcessingFailed("test error".to_string()),
            RealEsrganError::InsufficientVram {
                required: 8000,
                available: 4000,
            },
            RealEsrganError::ImageError("image error".to_string()),
        ];

        for err in errors {
            // Verify each error has a non-empty display message
            assert!(!err.to_string().is_empty());
        }
    }

    // Test tile padding validation
    #[test]
    fn test_tile_padding_in_builder() {
        let options = RealEsrganOptions::builder().tile_padding(20).build();
        assert_eq!(options.tile_padding, 20);

        let options = RealEsrganOptions::builder().tile_padding(0).build();
        assert_eq!(options.tile_padding, 0);
    }

    // Test face enhance option
    #[test]
    fn test_face_enhance_option() {
        let options = RealEsrganOptions::builder().face_enhance(true).build();
        assert!(options.face_enhance);

        let default_options = RealEsrganOptions::default();
        assert!(!default_options.face_enhance);
    }

    // Test model enum equality
    #[test]
    fn test_model_enum_equality() {
        assert_eq!(RealEsrganModel::X4Plus, RealEsrganModel::X4Plus);
        assert_ne!(RealEsrganModel::X4Plus, RealEsrganModel::X2Plus);

        let custom1 = RealEsrganModel::Custom("model1".to_string());
        let custom2 = RealEsrganModel::Custom("model1".to_string());
        let custom3 = RealEsrganModel::Custom("model2".to_string());

        assert_eq!(custom1, custom2);
        assert_ne!(custom1, custom3);
    }

    // Test output format equality
    #[test]
    fn test_output_format_equality() {
        assert_eq!(OutputFormat::Png, OutputFormat::Png);
        assert_eq!(
            OutputFormat::Jpg { quality: 90 },
            OutputFormat::Jpg { quality: 90 }
        );
        assert_ne!(
            OutputFormat::Jpg { quality: 90 },
            OutputFormat::Jpg { quality: 80 }
        );
    }

    // Test result with None vram
    #[test]
    fn test_upscale_result_without_vram() {
        let result = UpscaleResult {
            input_path: PathBuf::from("input.png"),
            output_path: PathBuf::from("output.png"),
            original_size: (100, 100),
            upscaled_size: (400, 400),
            actual_scale: 4.0,
            processing_time: Duration::from_secs(10),
            vram_used_mb: None,
        };

        assert!(result.vram_used_mb.is_none());
        assert_eq!(result.actual_scale, 4.0);
    }

    // TC-RES-006: タイルサイズ調整テスト拡張
    #[test]
    fn test_tile_size_variations() {
        // 様々なタイルサイズの設定をテスト
        let tile_sizes = [128, 256, 400, 512, 1024];

        for &size in &tile_sizes {
            let options = RealEsrganOptions::builder().tile_size(size).build();
            // tile_size は最小32にクランプされる
            assert!(
                options.tile_size >= 32,
                "Tile size {} was clamped incorrectly",
                size
            );
        }
    }

    // TC-RES-009: 推奨タイルサイズ算出テスト拡張
    // Note: RealEsrgan::recommended_tile_sizeはSubprocessBridgeが必要なので
    // ここではタイルサイズアルゴリズムのロジックをテスト
    #[test]
    fn test_tile_size_algorithm_extended() {
        // タイルサイズアルゴリズムの検証
        // base_tile = 400, base_vram = 4096
        // scale_factor = (vram / base_vram).sqrt()

        let vram_configs: [(u64, u32); 4] = [
            (2048, 283),  // sqrt(0.5) * 400 ≈ 283
            (4096, 400),  // sqrt(1.0) * 400 = 400
            (8192, 566),  // sqrt(2.0) * 400 ≈ 566
            (16384, 800), // sqrt(4.0) * 400 = 800
        ];

        for (vram_mb, expected_approx) in vram_configs {
            let scale_factor = (vram_mb as f64 / 4096.0).sqrt();
            let calculated = (400.0 * scale_factor) as u32;
            let clamped = calculated.clamp(128, 1024);

            // 計算値が期待値の±10%以内であることを確認
            let diff = (clamped as i32 - expected_approx as i32).unsigned_abs();
            assert!(
                diff <= expected_approx / 10 + 10,
                "For {}MB VRAM: expected ~{}, got {}",
                vram_mb,
                expected_approx,
                clamped
            );
        }
    }

    // TC-RES-005: 異なるモデル使用テスト拡張
    #[test]
    fn test_all_model_variants() {
        let models = [
            RealEsrganModel::X2Plus,
            RealEsrganModel::X4Plus,
            RealEsrganModel::X4PlusAnime,
            RealEsrganModel::NetX4Plus,
        ];

        for model in models {
            let options = RealEsrganOptions::builder().model(model.clone()).build();

            // モデルが正しく設定されていることを確認
            assert_eq!(options.model, model);

            // デフォルトスケールが取得できることを確認
            let default_scale = model.default_scale();
            assert!((2..=4).contains(&default_scale));
        }
    }

    // TC-RES-007: 出力フォーマットテスト拡張
    #[test]
    fn test_output_format_variants() {
        let formats = [
            (OutputFormat::Png, "png"),
            (OutputFormat::Jpg { quality: 90 }, "jpg"),
            (OutputFormat::Webp { quality: 85 }, "webp"),
        ];

        for (format, expected_ext) in formats {
            assert_eq!(format.extension(), expected_ext);
        }
    }

    #[test]
    fn test_batch_result_construction() {
        let result = BatchUpscaleResult {
            successful: vec![UpscaleResult {
                input_path: PathBuf::from("img1.png"),
                output_path: PathBuf::from("img1_upscaled.png"),
                original_size: (100, 100),
                upscaled_size: (200, 200),
                actual_scale: 2.0,
                processing_time: Duration::from_secs(1),
                vram_used_mb: Some(1000),
            }],
            failed: vec![(PathBuf::from("bad.png"), "File not found".to_string())],
            total_time: Duration::from_secs(5),
            peak_vram_mb: Some(2000),
        };

        assert_eq!(result.successful.len(), 1);
        assert_eq!(result.failed.len(), 1);
        assert_eq!(result.peak_vram_mb, Some(2000));
    }

    #[test]
    fn test_error_specific_messages() {
        let err = RealEsrganError::InsufficientVram {
            required: 8000,
            available: 4000,
        };
        let msg = err.to_string();
        assert!(msg.contains("8000") || msg.contains("4000"));

        let err = RealEsrganError::InvalidScale(3);
        let msg = err.to_string();
        assert!(msg.contains("3"));
    }

    // Additional comprehensive tests

    #[test]
    fn test_options_debug_impl() {
        let options = RealEsrganOptions::builder().scale(4).tile_size(512).build();

        let debug_str = format!("{:?}", options);
        assert!(debug_str.contains("RealEsrganOptions"));
        assert!(debug_str.contains("512"));
    }

    #[test]
    fn test_model_debug_impl() {
        let model = RealEsrganModel::X4Plus;
        let debug_str = format!("{:?}", model);
        assert!(debug_str.contains("X4Plus"));
    }

    #[test]
    fn test_output_format_debug_impl() {
        let format = OutputFormat::Jpg { quality: 95 };
        let debug_str = format!("{:?}", format);
        assert!(debug_str.contains("Jpg"));
        assert!(debug_str.contains("95"));
    }

    #[test]
    fn test_error_debug_impl() {
        let err = RealEsrganError::InvalidScale(5);
        let debug_str = format!("{:?}", err);
        assert!(debug_str.contains("InvalidScale"));
    }

    #[test]
    fn test_upscale_result_debug_impl() {
        let result = UpscaleResult {
            input_path: PathBuf::from("in.png"),
            output_path: PathBuf::from("out.png"),
            original_size: (100, 100),
            upscaled_size: (200, 200),
            actual_scale: 2.0,
            processing_time: Duration::from_secs(1),
            vram_used_mb: None,
        };

        let debug_str = format!("{:?}", result);
        assert!(debug_str.contains("UpscaleResult"));
    }

    #[test]
    fn test_batch_result_debug_impl() {
        let result = BatchUpscaleResult {
            successful: vec![],
            failed: vec![],
            total_time: Duration::from_secs(0),
            peak_vram_mb: None,
        };

        let debug_str = format!("{:?}", result);
        assert!(debug_str.contains("BatchUpscaleResult"));
    }

    #[test]
    fn test_options_clone() {
        let original = RealEsrganOptions::builder()
            .scale(4)
            .model(RealEsrganModel::X4PlusAnime)
            .tile_size(256)
            .fp16(true)
            .build();

        let cloned = original.clone();
        assert_eq!(cloned.scale, original.scale);
        assert_eq!(cloned.tile_size, original.tile_size);
        assert_eq!(cloned.fp16, original.fp16);
    }

    #[test]
    fn test_model_clone() {
        let original = RealEsrganModel::Custom("test_model".to_string());
        let cloned = original.clone();

        assert_eq!(cloned.model_name(), original.model_name());
    }

    #[test]
    fn test_output_format_clone() {
        let original = OutputFormat::Webp { quality: 85 };
        let cloned = original;

        assert_eq!(cloned.extension(), original.extension());
    }

    #[test]
    fn test_upscale_result_clone() {
        let original = UpscaleResult {
            input_path: PathBuf::from("input.png"),
            output_path: PathBuf::from("output.png"),
            original_size: (100, 100),
            upscaled_size: (400, 400),
            actual_scale: 4.0,
            processing_time: Duration::from_millis(500),
            vram_used_mb: Some(2048),
        };

        let cloned = original.clone();
        assert_eq!(cloned.input_path, original.input_path);
        assert_eq!(cloned.actual_scale, original.actual_scale);
        assert_eq!(cloned.vram_used_mb, original.vram_used_mb);
    }

    #[test]
    fn test_gpu_id_settings() {
        // Default is CPU mode (None)
        let default_opts = RealEsrganOptions::default();
        assert!(default_opts.gpu_id.is_none());

        // GPU 0
        let gpu0_opts = RealEsrganOptions::builder().gpu_id(0).build();
        assert_eq!(gpu0_opts.gpu_id, Some(0));

        // Multi-GPU
        for gpu_id in [0, 1, 2, 3] {
            let opts = RealEsrganOptions::builder().gpu_id(gpu_id).build();
            assert_eq!(opts.gpu_id, Some(gpu_id));
        }
    }

    #[test]
    fn test_fp16_toggle() {
        let fp16_on = RealEsrganOptions::builder().fp16(true).build();
        assert!(fp16_on.fp16);

        let fp16_off = RealEsrganOptions::builder().fp16(false).build();
        assert!(!fp16_off.fp16);

        // Default should be true (for speed optimization)
        let default_opts = RealEsrganOptions::default();
        assert!(default_opts.fp16);
    }

    #[test]
    fn test_jpeg_quality_range() {
        for quality in [1, 25, 50, 75, 90, 95, 100] {
            let opts = RealEsrganOptions::builder()
                .output_format(OutputFormat::Jpg { quality })
                .build();

            if let OutputFormat::Jpg { quality: q } = opts.output_format {
                assert_eq!(q, quality);
            } else {
                panic!("Expected Jpg format");
            }
        }
    }

    #[test]
    fn test_webp_quality_range() {
        for quality in [1, 50, 80, 100] {
            let opts = RealEsrganOptions::builder()
                .output_format(OutputFormat::Webp { quality })
                .build();

            if let OutputFormat::Webp { quality: q } = opts.output_format {
                assert_eq!(q, quality);
            } else {
                panic!("Expected Webp format");
            }
        }
    }

    #[test]
    fn test_processing_time_variations() {
        let times = [
            Duration::from_millis(100),
            Duration::from_secs(1),
            Duration::from_secs(60),
            Duration::from_secs(3600),
        ];

        for time in times {
            let result = UpscaleResult {
                input_path: PathBuf::from("in.png"),
                output_path: PathBuf::from("out.png"),
                original_size: (100, 100),
                upscaled_size: (200, 200),
                actual_scale: 2.0,
                processing_time: time,
                vram_used_mb: None,
            };
            assert_eq!(result.processing_time, time);
        }
    }

    #[test]
    fn test_upscale_size_calculations() {
        // 2x upscale
        let result_2x = UpscaleResult {
            input_path: PathBuf::from("in.png"),
            output_path: PathBuf::from("out.png"),
            original_size: (100, 200),
            upscaled_size: (200, 400),
            actual_scale: 2.0,
            processing_time: Duration::from_secs(1),
            vram_used_mb: None,
        };
        assert_eq!(result_2x.upscaled_size.0, result_2x.original_size.0 * 2);
        assert_eq!(result_2x.upscaled_size.1, result_2x.original_size.1 * 2);

        // 4x upscale
        let result_4x = UpscaleResult {
            input_path: PathBuf::from("in.png"),
            output_path: PathBuf::from("out.png"),
            original_size: (100, 200),
            upscaled_size: (400, 800),
            actual_scale: 4.0,
            processing_time: Duration::from_secs(5),
            vram_used_mb: Some(4096),
        };
        assert_eq!(result_4x.upscaled_size.0, result_4x.original_size.0 * 4);
        assert_eq!(result_4x.upscaled_size.1, result_4x.original_size.1 * 4);
    }

    #[test]
    fn test_vram_usage_values() {
        // Various VRAM amounts
        for vram in [512, 1024, 2048, 4096, 8192, 16384] {
            let result = UpscaleResult {
                input_path: PathBuf::from("in.png"),
                output_path: PathBuf::from("out.png"),
                original_size: (100, 100),
                upscaled_size: (200, 200),
                actual_scale: 2.0,
                processing_time: Duration::from_secs(1),
                vram_used_mb: Some(vram),
            };
            assert_eq!(result.vram_used_mb, Some(vram));
        }
    }

    #[test]
    fn test_batch_result_empty() {
        let result = BatchUpscaleResult {
            successful: vec![],
            failed: vec![],
            total_time: Duration::from_secs(0),
            peak_vram_mb: None,
        };

        assert!(result.successful.is_empty());
        assert!(result.failed.is_empty());
    }

    #[test]
    fn test_batch_result_all_failed() {
        let failed: Vec<(PathBuf, String)> = (0..10)
            .map(|i| (PathBuf::from(format!("img_{}.png", i)), "Error".to_string()))
            .collect();

        let result = BatchUpscaleResult {
            successful: vec![],
            failed,
            total_time: Duration::from_secs(10),
            peak_vram_mb: None,
        };

        assert!(result.successful.is_empty());
        assert_eq!(result.failed.len(), 10);
    }

    #[test]
    fn test_batch_result_all_successful() {
        let successful: Vec<UpscaleResult> = (0..10)
            .map(|i| UpscaleResult {
                input_path: PathBuf::from(format!("in_{}.png", i)),
                output_path: PathBuf::from(format!("out_{}.png", i)),
                original_size: (100, 100),
                upscaled_size: (200, 200),
                actual_scale: 2.0,
                processing_time: Duration::from_secs(1),
                vram_used_mb: None,
            })
            .collect();

        let result = BatchUpscaleResult {
            successful,
            failed: vec![],
            total_time: Duration::from_secs(10),
            peak_vram_mb: Some(4096),
        };

        assert_eq!(result.successful.len(), 10);
        assert!(result.failed.is_empty());
    }

    #[test]
    fn test_model_names_not_empty() {
        let models = [
            RealEsrganModel::X2Plus,
            RealEsrganModel::X4Plus,
            RealEsrganModel::X4PlusAnime,
            RealEsrganModel::NetX4Plus,
            RealEsrganModel::Custom("custom".to_string()),
        ];

        for model in models {
            assert!(!model.model_name().is_empty());
        }
    }

    #[test]
    fn test_builder_default_values() {
        let builder_opts = RealEsrganOptions::builder().build();
        let default_opts = RealEsrganOptions::default();

        assert_eq!(builder_opts.scale, default_opts.scale);
        assert_eq!(builder_opts.tile_size, default_opts.tile_size);
        assert_eq!(builder_opts.fp16, default_opts.fp16);
    }

    #[test]
    fn test_error_io_conversion() {
        let io_err = std::io::Error::new(std::io::ErrorKind::PermissionDenied, "access denied");
        let real_err: RealEsrganError = io_err.into();
        let msg = real_err.to_string();
        assert!(!msg.is_empty());
    }

    #[test]
    fn test_preset_presets_consistency() {
        // High quality preset
        let hq = RealEsrganOptions::x4_high_quality();
        assert_eq!(hq.scale, 4);
        assert!(!hq.fp16); // More precise

        // Anime preset
        let anime = RealEsrganOptions::anime();
        assert!(matches!(anime.model, RealEsrganModel::X4PlusAnime));

        // Low VRAM preset
        let low_vram = RealEsrganOptions::low_vram();
        assert!(low_vram.fp16); // More memory efficient
        assert!(low_vram.tile_size <= 128);
    }

    #[test]
    fn test_output_format_default() {
        let default_opts = RealEsrganOptions::default();
        assert!(matches!(default_opts.output_format, OutputFormat::Png));
    }

    #[test]
    fn test_scale_only_2_or_4() {
        // Only 2x and 4x should be valid
        for scale in [1, 2, 3, 4, 5, 6, 7, 8] {
            let opts = RealEsrganOptions::builder().scale(scale).build();
            assert!(opts.scale == 2 || opts.scale == 4);
        }
    }

    // ============ Error Handling Tests ============

    #[test]
    fn test_error_model_not_found() {
        let err = RealEsrganError::ModelNotFound("custom_model".to_string());
        let msg = format!("{}", err);
        assert!(msg.contains("Model not found"));
        assert!(msg.contains("custom_model"));
    }

    #[test]
    fn test_error_invalid_scale() {
        let err = RealEsrganError::InvalidScale(3);
        let msg = format!("{}", err);
        assert!(msg.contains("Invalid scale"));
        assert!(msg.contains("3"));
    }

    #[test]
    fn test_error_input_not_found() {
        let path = std::path::PathBuf::from("/missing/image.png");
        let err = RealEsrganError::InputNotFound(path);
        let msg = format!("{}", err);
        assert!(msg.contains("Input image not found"));
    }

    #[test]
    fn test_error_output_not_writable() {
        let path = std::path::PathBuf::from("/readonly/dir");
        let err = RealEsrganError::OutputNotWritable(path);
        let msg = format!("{}", err);
        assert!(msg.contains("not writable"));
    }

    #[test]
    fn test_error_processing_failed() {
        let err = RealEsrganError::ProcessingFailed("CUDA out of memory".to_string());
        let msg = format!("{}", err);
        assert!(msg.contains("Processing failed"));
        assert!(msg.contains("CUDA"));
    }

    #[test]
    fn test_error_insufficient_vram() {
        let err = RealEsrganError::InsufficientVram {
            required: 4096,
            available: 2048,
        };
        let msg = format!("{}", err);
        assert!(msg.contains("memory"));
        assert!(msg.contains("4096"));
        assert!(msg.contains("2048"));
    }

    #[test]
    fn test_error_image_error() {
        let err = RealEsrganError::ImageError("Corrupt PNG header".to_string());
        let msg = format!("{}", err);
        assert!(msg.contains("Image error"));
    }

    #[test]
    fn test_error_from_io_error() {
        let io_err = std::io::Error::new(std::io::ErrorKind::PermissionDenied, "access denied");
        let res_err: RealEsrganError = io_err.into();
        let msg = format!("{}", res_err);
        assert!(msg.contains("IO error"));
    }

    #[test]
    fn test_error_debug_all_variants() {
        let errors: Vec<RealEsrganError> = vec![
            RealEsrganError::ModelNotFound("test".to_string()),
            RealEsrganError::InvalidScale(5),
            RealEsrganError::InputNotFound(std::path::PathBuf::from("/test")),
            RealEsrganError::OutputNotWritable(std::path::PathBuf::from("/test")),
            RealEsrganError::ProcessingFailed("test".to_string()),
            RealEsrganError::InsufficientVram {
                required: 100,
                available: 50,
            },
            RealEsrganError::ImageError("test".to_string()),
        ];

        for err in &errors {
            let debug = format!("{:?}", err);
            assert!(!debug.is_empty());
        }
    }

    // ============ Concurrency Tests ============

    #[test]
    fn test_realesrgan_types_send_sync() {
        fn assert_send_sync<T: Send + Sync>() {}
        assert_send_sync::<RealEsrganOptions>();
        assert_send_sync::<RealEsrganModel>();
        assert_send_sync::<OutputFormat>();
        assert_send_sync::<UpscaleResult>();
    }

    #[test]
    fn test_concurrent_options_building() {
        use std::thread;
        let handles: Vec<_> = (0..8)
            .map(|i| {
                thread::spawn(move || {
                    RealEsrganOptions::builder()
                        .scale(if i % 2 == 0 { 2 } else { 4 })
                        .tile_size(128 + (i as u32 * 64))
                        .fp16(i % 2 == 0)
                        .build()
                })
            })
            .collect();

        let results: Vec<_> = handles.into_iter().map(|h| h.join().unwrap()).collect();
        assert_eq!(results.len(), 8);

        for (i, opt) in results.iter().enumerate() {
            let expected_scale = if i % 2 == 0 { 2 } else { 4 };
            assert_eq!(opt.scale, expected_scale);
        }
    }

    #[test]
    fn test_parallel_upscale_result_creation() {
        use rayon::prelude::*;

        let results: Vec<_> = (0..100)
            .into_par_iter()
            .map(|i| UpscaleResult {
                input_path: PathBuf::from(format!("input_{}.png", i)),
                output_path: PathBuf::from(format!("output_{}.png", i)),
                original_size: (100 + i as u32, 100 + i as u32),
                upscaled_size: (200 + i as u32 * 2, 200 + i as u32 * 2),
                actual_scale: 2.0,
                processing_time: Duration::from_millis(i as u64 * 10),
                vram_used_mb: Some(1024 + i as u64),
            })
            .collect();

        assert_eq!(results.len(), 100);
        for (i, result) in results.iter().enumerate() {
            assert_eq!(result.original_size.0, 100 + i as u32);
        }
    }

    #[test]
    fn test_model_thread_transfer() {
        use std::thread;

        let models = vec![
            RealEsrganModel::X4Plus,
            RealEsrganModel::X4PlusAnime,
            RealEsrganModel::Custom("custom".to_string()),
        ];

        let handles: Vec<_> = models
            .into_iter()
            .map(|model| {
                thread::spawn(move || {
                    let name = model.model_name().to_string();
                    let scale = model.default_scale();
                    (name, scale)
                })
            })
            .collect();

        let results: Vec<_> = handles.into_iter().map(|h| h.join().unwrap()).collect();
        assert_eq!(results.len(), 3);
        assert!(!results[0].0.is_empty());
    }

    #[test]
    fn test_concurrent_output_format_usage() {
        use std::thread;

        let formats = vec![
            OutputFormat::Png,
            OutputFormat::Jpg { quality: 90 },
            OutputFormat::Webp { quality: 85 },
        ];

        let handles: Vec<_> = formats
            .into_iter()
            .map(|format| thread::spawn(move || format.extension().to_string()))
            .collect();

        let extensions: Vec<_> = handles.into_iter().map(|h| h.join().unwrap()).collect();
        assert_eq!(extensions, vec!["png", "jpg", "webp"]);
    }

    #[test]
    fn test_options_shared_across_threads() {
        use std::sync::Arc;
        use std::thread;

        let options = Arc::new(
            RealEsrganOptions::builder()
                .scale(4)
                .model(RealEsrganModel::X4PlusAnime)
                .tile_size(256)
                .build(),
        );

        let handles: Vec<_> = (0..4)
            .map(|_| {
                let opts = Arc::clone(&options);
                thread::spawn(move || {
                    assert_eq!(opts.scale, 4);
                    assert_eq!(opts.tile_size, 256);
                    opts.model.model_name().to_string()
                })
            })
            .collect();

        for handle in handles {
            let name = handle.join().unwrap();
            assert!(name.contains("anime"));
        }
    }

    // ============ Boundary Value Tests ============

    #[test]
    fn test_tile_size_minimum_boundary() {
        let options = RealEsrganOptions::builder().tile_size(0).build();
        assert_eq!(options.tile_size, MIN_TILE_SIZE); // Should clamp to 64
    }

    #[test]
    fn test_tile_size_maximum_boundary() {
        let options = RealEsrganOptions::builder().tile_size(u32::MAX).build();
        assert_eq!(options.tile_size, MAX_TILE_SIZE); // Should clamp to 1024
    }

    #[test]
    fn test_tile_padding_zero() {
        let options = RealEsrganOptions::builder().tile_padding(0).build();
        assert_eq!(options.tile_padding, 0);
    }

    #[test]
    fn test_tile_padding_large() {
        let options = RealEsrganOptions::builder().tile_padding(1000).build();
        assert_eq!(options.tile_padding, 1000);
    }

    #[test]
    fn test_gpu_id_zero() {
        let options = RealEsrganOptions::builder().gpu_id(0).build();
        assert_eq!(options.gpu_id, Some(0));
    }

    #[test]
    fn test_gpu_id_high() {
        let options = RealEsrganOptions::builder().gpu_id(7).build();
        assert_eq!(options.gpu_id, Some(7));
    }

    #[test]
    fn test_jpeg_quality_zero() {
        let format = OutputFormat::Jpg { quality: 0 };
        if let OutputFormat::Jpg { quality } = format {
            assert_eq!(quality, 0);
        }
    }

    #[test]
    fn test_jpeg_quality_max() {
        let format = OutputFormat::Jpg { quality: 100 };
        if let OutputFormat::Jpg { quality } = format {
            assert_eq!(quality, 100);
        }
    }

    #[test]
    fn test_webp_quality_zero() {
        let format = OutputFormat::Webp { quality: 0 };
        if let OutputFormat::Webp { quality } = format {
            assert_eq!(quality, 0);
        }
    }

    #[test]
    fn test_webp_quality_max() {
        let format = OutputFormat::Webp { quality: 100 };
        if let OutputFormat::Webp { quality } = format {
            assert_eq!(quality, 100);
        }
    }

    #[test]
    fn test_original_size_zero() {
        let result = UpscaleResult {
            input_path: PathBuf::from("zero.png"),
            output_path: PathBuf::from("zero_out.png"),
            original_size: (0, 0),
            upscaled_size: (0, 0),
            actual_scale: 0.0,
            processing_time: Duration::ZERO,
            vram_used_mb: None,
        };
        assert_eq!(result.original_size, (0, 0));
    }

    #[test]
    fn test_upscaled_size_large() {
        let result = UpscaleResult {
            input_path: PathBuf::from("large.png"),
            output_path: PathBuf::from("large_out.png"),
            original_size: (8192, 8192),
            upscaled_size: (32768, 32768),
            actual_scale: 4.0,
            processing_time: Duration::from_secs(300),
            vram_used_mb: Some(16384),
        };
        assert_eq!(result.upscaled_size, (32768, 32768));
    }

    #[test]
    fn test_processing_time_zero() {
        let result = UpscaleResult {
            input_path: PathBuf::from("instant.png"),
            output_path: PathBuf::from("instant_out.png"),
            original_size: (1, 1),
            upscaled_size: (2, 2),
            actual_scale: 2.0,
            processing_time: Duration::ZERO,
            vram_used_mb: None,
        };
        assert_eq!(result.processing_time, Duration::ZERO);
    }

    #[test]
    fn test_vram_used_zero() {
        let result = UpscaleResult {
            input_path: PathBuf::from("cpu.png"),
            output_path: PathBuf::from("cpu_out.png"),
            original_size: (100, 100),
            upscaled_size: (200, 200),
            actual_scale: 2.0,
            processing_time: Duration::from_secs(60),
            vram_used_mb: Some(0),
        };
        assert_eq!(result.vram_used_mb, Some(0));
    }

    #[test]
    fn test_vram_used_large() {
        let result = UpscaleResult {
            input_path: PathBuf::from("big.png"),
            output_path: PathBuf::from("big_out.png"),
            original_size: (4096, 4096),
            upscaled_size: (16384, 16384),
            actual_scale: 4.0,
            processing_time: Duration::from_secs(120),
            vram_used_mb: Some(24576), // 24GB
        };
        assert_eq!(result.vram_used_mb, Some(24576));
    }

    #[test]
    fn test_actual_scale_fractional() {
        // Non-integer scale can occur with some models
        let result = UpscaleResult {
            input_path: PathBuf::from("test.png"),
            output_path: PathBuf::from("test_out.png"),
            original_size: (100, 100),
            upscaled_size: (350, 350),
            actual_scale: 3.5,
            processing_time: Duration::from_secs(5),
            vram_used_mb: None,
        };
        assert!((result.actual_scale - 3.5).abs() < 0.01);
    }

    #[test]
    fn test_batch_failed_empty_error() {
        let batch = BatchUpscaleResult {
            successful: vec![],
            failed: vec![(PathBuf::from("file.png"), String::new())],
            total_time: Duration::from_secs(1),
            peak_vram_mb: None,
        };
        assert!(batch.failed[0].1.is_empty());
    }

    #[test]
    fn test_batch_peak_vram_zero() {
        let batch = BatchUpscaleResult {
            successful: vec![],
            failed: vec![],
            total_time: Duration::ZERO,
            peak_vram_mb: Some(0),
        };
        assert_eq!(batch.peak_vram_mb, Some(0));
    }

    #[test]
    fn test_insufficient_vram_error_equal_values() {
        let err = RealEsrganError::InsufficientVram {
            required: 4096,
            available: 4096,
        };
        let msg = err.to_string();
        assert!(msg.contains("4096"));
    }

    #[test]
    fn test_custom_model_empty_name() {
        let model = RealEsrganModel::Custom(String::new());
        assert!(model.model_name().is_empty());
    }

    #[test]
    fn test_upscale_result_success() {
        let result = UpscaleResult {
            input_path: std::path::PathBuf::from("/input/image.png"),
            output_path: std::path::PathBuf::from("/output/image_2x.png"),
            original_size: (1920, 1080),
            upscaled_size: (3840, 2160),
            actual_scale: 2.0,
            processing_time: std::time::Duration::from_secs(5),
            vram_used_mb: Some(512),
        };
        assert!((result.actual_scale - 2.0).abs() < 0.01);
        assert_eq!(result.upscaled_size.0, result.original_size.0 * 2);
        assert_eq!(result.upscaled_size.1, result.original_size.1 * 2);
    }

    #[test]
    fn test_upscale_result_4x() {
        let result = UpscaleResult {
            input_path: std::path::PathBuf::from("/input/small.png"),
            output_path: std::path::PathBuf::from("/output/large.png"),
            original_size: (640, 480),
            upscaled_size: (2560, 1920),
            actual_scale: 4.0,
            processing_time: std::time::Duration::from_secs(15),
            vram_used_mb: None,
        };
        assert!((result.actual_scale - 4.0).abs() < 0.01);
        assert_eq!(result.upscaled_size.0, result.original_size.0 * 4);
    }

    #[test]
    fn test_model_enum_all_variants() {
        use super::RealEsrganModel;
        let models = [
            RealEsrganModel::X4Plus,
            RealEsrganModel::X4PlusAnime,
            RealEsrganModel::NetX4Plus,
            RealEsrganModel::X2Plus,
            RealEsrganModel::Custom("my_model".to_string()),
        ];

        for model in &models {
            let debug = format!("{:?}", model);
            assert!(!debug.is_empty());
        }
    }
}