kindling-mobi 0.14.5

Kindle MOBI/AZW3 builder for dictionaries, books, and comics. Drop-in kindlegen replacement.
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
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
/// Comic book to MOBI converter.
///
/// Converts image folders, CBZ files, CBR files, or EPUB files into
/// Kindle-optimized MOBI files using a fixed-layout EPUB intermediate
/// representation.
///
/// Pipeline:
///   1. Extract/scan images from input (folder, CBZ, CBR, or EPUB)
///   2. Parse ComicInfo.xml if present (metadata, manga detection)
///   3. Process images in parallel:
///      a. Detect and split double-page spreads (landscape images)
///      b. Crop uniform-color borders
///      c. Apply auto-contrast and gamma correction (grayscale devices only)
///      d. Resize and encode as JPEG
///   4. Write processed images + OPF + XHTML to a temp directory
///   5. Call mobi::build_mobi() on the temp directory's OPF
///   6. Clean up temp dir

use std::fs;
use std::io::Read;

use std::path::{Path, PathBuf};

use crate::cbr;
use crate::epub;
use crate::DEFAULT_AUTHOR;

use image::imageops::FilterType;
use image::{DynamicImage, GenericImageView, GrayImage, Luma, Rgb, RgbImage};
use rayon::prelude::*;

use crate::mobi;
use crate::moire;

/// Device profile for Kindle screen dimensions.
#[derive(Debug, Clone, Copy)]
pub struct DeviceProfile {
    pub width: u32,
    pub height: u32,
    pub grayscale: bool,
    pub name: &'static str,
}

/// All supported device profiles.
const PROFILES: &[DeviceProfile] = &[
    DeviceProfile { width: 1072, height: 1448, grayscale: true, name: "paperwhite" },
    DeviceProfile { width: 1264, height: 1680, grayscale: true, name: "oasis" },
    DeviceProfile { width: 1860, height: 2480, grayscale: true, name: "scribe" },
    DeviceProfile { width: 1072, height: 1448, grayscale: true, name: "basic" },
    DeviceProfile { width: 1264, height: 1680, grayscale: false, name: "colorsoft" },
    DeviceProfile { width: 1200, height: 1920, grayscale: false, name: "fire-hd-10" },
    DeviceProfile { width: 1236, height: 1648, grayscale: true, name: "kpw5" },
    DeviceProfile { width: 1986, height: 2648, grayscale: true, name: "scribe2025" },
    DeviceProfile { width: 1240, height: 1860, grayscale: true, name: "kindle2024" },
];

/// Look up a device profile by name (case-insensitive).
pub fn get_profile(name: &str) -> Option<DeviceProfile> {
    let lower = name.to_lowercase();
    PROFILES.iter().find(|p| p.name == lower).copied()
}

/// Return a comma-separated list of valid device names.
pub fn valid_device_names() -> String {
    PROFILES.iter().map(|p| p.name).collect::<Vec<_>>().join(", ")
}

/// Specifies how the cover image should be chosen.
#[derive(Debug, Clone)]
pub enum CoverSource {
    /// Use a specific page number (1-based) as the cover.
    PageNumber(usize),
    /// Use an external image file as the cover.
    FilePath(PathBuf),
}

/// Options controlling comic image processing.
#[derive(Debug, Clone)]
pub struct ComicOptions {
    /// Enable RTL (right-to-left) reading direction for manga.
    pub rtl: bool,
    /// Enable double-page spread splitting (default: true).
    pub split: bool,
    /// Crop mode matching KCC's `--cropping` flag:
    /// - 0: disabled
    /// - 1: margins only
    /// - 2: margins + page numbers (default)
    pub crop: u8,
    /// Enable auto-contrast and gamma correction (default: true).
    pub enhance: bool,
    /// Force webtoon mode (vertical strip merge + split).
    pub webtoon: bool,
    /// Enable Kindle Panel View (tap-to-zoom panels). Default: true for comics.
    pub panel_view: bool,
    /// JPEG encoding quality (1-100). Default: 85.
    pub jpeg_quality: u8,
    /// Maximum pixel height for webtoon strip merges before chunking. Default: 65536.
    pub max_height: u32,
    /// Embed the generated EPUB in the MOBI (for Kindle Previewer compat). Default: true.
    pub embed_source: bool,
    /// Document type for EXTH 501: "EBOK" (Books shelf) or "PDOC" (Documents shelf).
    /// Default: None (PDOC).
    pub doc_type: Option<String>,
    /// Override title from ComicInfo.xml.
    pub title_override: Option<String>,
    /// Override author from ComicInfo.xml.
    pub author_override: Option<String>,
    /// Language code for OPF metadata (e.g. "ja", "en", "ko").
    pub language: Option<String>,
    /// Override cover image selection.
    pub cover: Option<CoverSource>,
    /// Rotate double-page spreads 90 degrees clockwise instead of splitting them.
    /// Useful for tablet users who want a full-page spread view.
    pub rotate_spreads: bool,
    /// Panel reading order for Panel View. Controls the order panels are
    /// navigated when tapping on Kindle.
    /// - "horizontal-lr": left-to-right, top-to-bottom (Western comics)
    /// - "horizontal-rl": right-to-left, top-to-bottom (manga)
    /// - "vertical-lr": top-to-bottom, left-to-right (4-koma, vertical strips)
    /// - "vertical-rl": top-to-bottom, right-to-left (4-koma RTL)
    /// None means auto-detect: horizontal-rl if RTL, horizontal-lr otherwise.
    pub panel_reading_order: Option<String>,
    /// Center-crop the cover image to fill the device screen (no borders).
    pub cover_fill: bool,
    /// Enforce Kindle publishing limits (warn about large HTML files and file counts).
    pub kindle_limits: bool,
    /// Output KF8-only format (.azw3) instead of dual MOBI7+KF8 (.mobi).
    pub kf8_only: bool,
    /// Run the build-time HTML self-check on the assembled MOBI text
    /// blob. Default: true. When a bad blob is detected the build emits
    /// warnings but does not abort.
    pub self_check: bool,
    /// Emit KF8 comic output that matches kindlegen's byte-level shape
    /// (single-line template, no DOCTYPE/meta charset, flat body/div
    /// without inline styles, `image/jpg` mime, `page N` lowercase
    /// alt, img without aid, AID stride of 1_000_000 per spine page).
    /// Off by default: kindling's normal output is pretty-printed and
    /// slightly richer ("better than kindlegen"). Turn this on for
    /// parity tests or when producing reference builds.
    pub kindlegen_parity: bool,
}

impl Default for ComicOptions {
    fn default() -> Self {
        ComicOptions {
            rtl: false,
            split: true,
            crop: 2,
            enhance: true,
            webtoon: false,
            panel_view: true,
            jpeg_quality: 85,
            max_height: 65536,
            // Comics default to NOT embedding the source EPUB. Embedding
            // duplicates every image byte as a zipped EPUB attached to the
            // MOBI, which for a large comic (~400 pages) produces a 100+ MB
            // SRCS PalmDB record. A single record that large trips up the
            // Kindle reader's "Unable to Open Item" path, even though the
            // Kindle indexer is happy to add the file to the library. The
            // source is only useful for round-tripping through Kindle
            // Previewer, which is not the workflow for sideloaded comics.
            // Pass `--embed-source` to opt back in.
            embed_source: false,
            doc_type: None,
            title_override: None,
            author_override: None,
            language: None,
            cover: None,
            rotate_spreads: false,
            panel_reading_order: None,
            cover_fill: false,
            kindle_limits: false,
            kf8_only: false,
            self_check: true,
            kindlegen_parity: false,
        }
    }
}

/// Metadata parsed from a ComicInfo.xml file.
#[derive(Debug, Clone, Default)]
pub struct ComicMetadata {
    pub title: Option<String>,
    pub series: Option<String>,
    pub number: Option<String>,
    pub writers: Vec<String>,
    pub pencillers: Vec<String>,
    pub inkers: Vec<String>,
    pub summary: Option<String>,
    pub manga_rtl: bool,
    pub language: Option<String>,
    pub year: Option<String>,
    pub month: Option<String>,
}

impl ComicMetadata {
    /// Build an effective title from series/number/title fields.
    pub fn effective_title(&self) -> Option<String> {
        match (&self.series, &self.number, &self.title) {
            (Some(series), Some(num), Some(title)) => {
                Some(format!("{} #{} - {}", series, num, title))
            }
            (Some(series), Some(num), None) => Some(format!("{} #{}", series, num)),
            (Some(series), None, Some(title)) => Some(format!("{} - {}", series, title)),
            (None, _, Some(title)) => Some(title.clone()),
            _ => self.series.clone(),
        }
    }

    /// Collect all creators into a single string.
    pub fn creators(&self) -> Vec<String> {
        let mut all = Vec::new();
        all.extend(self.writers.iter().cloned());
        all.extend(self.pencillers.iter().cloned());
        all.extend(self.inkers.iter().cloned());
        all
    }
}

/// A single processed page image (JPEG bytes, ready for embedding).
struct ProcessedImage {
    /// 0-based page index
    index: usize,
    /// JPEG-encoded image bytes
    jpeg_data: Vec<u8>,
    /// Actual pixel dimensions of the processed image
    width: u32,
    height: u32,
    /// Panel rectangles for Panel View (None = no panels / full-page splash)
    panels: Option<Vec<PanelRect>>,
}

/// Run the full comic-to-MOBI pipeline.
pub fn build_comic(
    input: &Path,
    output: &Path,
    profile: &DeviceProfile,
) -> Result<(), Box<dyn std::error::Error>> {
    build_comic_with_options(input, output, profile, &ComicOptions::default())
}

/// Run the full comic-to-MOBI pipeline with processing options.
pub fn build_comic_with_options(
    input: &Path,
    output: &Path,
    profile: &DeviceProfile,
    options: &ComicOptions,
) -> Result<(), Box<dyn std::error::Error>> {
    // Step 1: Collect source images (and optionally a temp dir from
    // CBZ/CBR/EPUB extraction). The variable retains the historical
    // `cbz_temp_dir` name for continuity with earlier versions.
    let (source_images, cbz_temp_dir) = collect_images(input)?;
    if source_images.is_empty() {
        return Err("No images found in input".into());
    }
    eprintln!("Found {} images", source_images.len());

    // Step 1b: Webtoon detection and preprocessing
    let is_webtoon = options.webtoon || detect_webtoon(&source_images);
    let source_images = if is_webtoon {
        if options.webtoon {
            eprintln!("Webtoon mode enabled");
        } else {
            eprintln!("Detected webtoon format");
        }
        let pages = webtoon_preprocess(&source_images, profile, options)?;
        eprintln!("Split webtoon into {} pages", pages.len());
        pages
    } else {
        source_images
    };

    // Step 2: Parse ComicInfo.xml if present
    let metadata = find_and_parse_comic_info(input, cbz_temp_dir.as_deref());

    // Determine effective RTL setting: CLI flag OR ComicInfo.xml manga detection
    let rtl = options.rtl || metadata.as_ref().map_or(false, |m| m.manga_rtl);
    if rtl {
        eprintln!("RTL (manga) mode enabled");
    }

    // Step 3: Process images in parallel (with spread splitting, cropping, enhancement)
    eprintln!("Processing images for {} ({}x{}, {})...",
        profile.name, profile.width, profile.height,
        if profile.grayscale { "grayscale" } else { "color" });

    // Determine which source image index is the cover page (for cover_fill).
    // For external file covers, cover_fill is applied separately below.
    let cover_source_idx = match &options.cover {
        Some(CoverSource::PageNumber(n)) => Some(n.saturating_sub(1)),
        Some(CoverSource::FilePath(_)) => None, // handled separately
        None => Some(0),
    };

    let total = source_images.len();
    let processed_groups: Vec<Option<(usize, Vec<Vec<u8>>)>> = source_images
        .par_iter()
        .enumerate()
        .map(|(idx, img_path)| {
            if idx % 10 == 0 || idx == total - 1 {
                eprintln!("Processing image {}/{}...", idx + 1, total);
            }
            let is_cover = options.cover_fill && cover_source_idx == Some(idx);
            match process_image_pipeline(img_path, profile, options, is_cover) {
                Ok(jpeg_pages) => Some((idx, jpeg_pages)),
                Err(e) => {
                    eprintln!("Warning: skipping {} ({})", img_path.display(), e);
                    None
                }
            }
        })
        .collect();

    // Filter out skipped images and unwrap
    let processed_groups: Vec<(usize, Vec<Vec<u8>>)> = processed_groups.into_iter().flatten().collect();

    if processed_groups.is_empty() {
        return Err("All images failed to load - no valid images to process".into());
    }

    // Sort by original index, then flatten (each source image may produce 1 or 2 pages)
    let mut processed_groups = processed_groups;
    processed_groups.sort_by_key(|(idx, _)| *idx);

    let mut processed: Vec<ProcessedImage> = Vec::new();
    let mut page_idx = 0;
    for (_orig_idx, pages) in &processed_groups {
        for jpeg_data in pages {
            // Read actual image dimensions from the JPEG data
            let (w, h) = image::load_from_memory(jpeg_data)
                .map(|img| (img.width(), img.height()))
                .unwrap_or((profile.width, profile.height));
            processed.push(ProcessedImage {
                index: page_idx,
                jpeg_data: jpeg_data.clone(),
                width: w,
                height: h,
                panels: None, // Filled in below if panel_view is enabled
            });
            page_idx += 1;
        }
    }

    // Reverse page order for RTL reading direction
    if rtl {
        processed.reverse();
        // Re-index after reversal
        for (i, page) in processed.iter_mut().enumerate() {
            page.index = i;
        }
    }

    let total_image_bytes: usize = processed.iter().map(|p| p.jpeg_data.len()).sum();
    eprintln!("Processed into {} pages ({:.1} MB total JPEG data)",
        processed.len(),
        total_image_bytes as f64 / (1024.0 * 1024.0));

    // Step 3b: Detect panels for Panel View if enabled
    if options.panel_view {
        eprintln!("Detecting panels for Panel View...");
        let panel_results = detect_panels_for_pages(&processed);
        let mut panel_count = 0;
        for (i, panels) in panel_results.into_iter().enumerate() {
            if let Some(ref p) = panels {
                panel_count += 1;
                eprintln!("  Page {}: {} panels", i + 1, p.len());
            }
            processed[i].panels = panels;
        }
        eprintln!("Panel View: detected panels on {}/{} pages", panel_count, processed.len());

        // Sort panels according to reading order
        let reading_order = resolve_panel_reading_order(
            options.panel_reading_order.as_deref(), options.rtl,
        );
        if reading_order != "horizontal-lr" {
            eprintln!("Panel View: sorting panels in {} order", reading_order);
        }
        for page in processed.iter_mut() {
            if let Some(ref mut panels) = page.panels {
                sort_panels_by_reading_order(panels, reading_order);
            }
        }
    }

    // Step 4: Write OPF + XHTML + images to temp directory
    let temp_dir = create_temp_dir(output)?;
    let opf_path = write_fixed_layout_epub_v2(
        &temp_dir, &processed, profile, rtl, metadata.as_ref(), options.panel_view, options,
    )?;

    // Step 4b: Run KDP validation on the generated OPF. Errors fail the
    // build (with cleanup); warnings print but continue. This lets us
    // catch OPF-level regressions (missing cover, bad manifest references,
    // unsupported tags) before they ship in a MOBI.
    match crate::validate::validate_opf(&opf_path) {
        Ok(report) => {
            for finding in &report.findings {
                // Only show warnings and errors; comic OPFs always emit an
                // info about marketing cover which is noise here.
                if !matches!(finding.level, crate::validate::Level::Info) {
                    eprintln!("  {}", finding);
                }
            }
            let errors = report.error_count();
            if errors > 0 {
                if temp_dir.exists() {
                    let _ = fs::remove_dir_all(&temp_dir);
                }
                if let Some(ref cbz_dir) = cbz_temp_dir {
                    if cbz_dir.exists() {
                        let _ = fs::remove_dir_all(cbz_dir);
                    }
                }
                return Err(format!(
                    "Comic OPF validation failed with {} errors",
                    errors
                )
                .into());
            }
        }
        Err(e) => {
            eprintln!("Warning: could not validate comic OPF: {}", e);
        }
    }

    // Capture the OPF title/author for the post-build readback check.
    let opf_snapshot: Option<(String, String)> = crate::opf::OPFData::parse(&opf_path)
        .ok()
        .map(|o| (o.title.clone(), o.author.clone()));

    // Step 5: Build MOBI
    eprintln!("Building MOBI...");
    // If embed_source, zip the temp dir into an EPUB for SRCS embedding
    let srcs_data = if options.embed_source {
        epub::create_epub_from_dir(&temp_dir).ok()
    } else {
        None
    };
    let result = mobi::build_mobi(
        &opf_path,
        output,
        false,  // compress
        false,  // headwords_only (N/A for books)
        srcs_data.as_deref(),
        false,  // no CMET
        true,   // skip HD images (KCC doesn't emit HD container)
        false,  // default creator identity
        options.kf8_only,
        options.doc_type.as_deref(),
        options.kindle_limits,
        options.self_check,
        options.kindlegen_parity,
        false,  // strict_accents (dictionary-only flag, no effect on comics)
    );

    // Step 6: Clean up temp dirs
    if temp_dir.exists() {
        if let Err(e) = fs::remove_dir_all(&temp_dir) {
            eprintln!("Warning: failed to clean up temp dir {}: {}", temp_dir.display(), e);
        }
    }
    if let Some(cbz_dir) = cbz_temp_dir {
        if cbz_dir.exists() {
            if let Err(e) = fs::remove_dir_all(&cbz_dir) {
                eprintln!("Warning: failed to clean up archive extraction dir {}: {}", cbz_dir.display(), e);
            }
        }
    }

    // Step 7: Post-build MOBI readback check. If EXTH 100 or 503 are
    // missing, fail the build rather than ship a file the Kindle indexer
    // will silently drop.
    result?;

    let (title, author) = match opf_snapshot.as_ref() {
        Some((t, a)) => (t.as_str(), a.as_str()),
        None => ("", ""),
    };
    let expected = crate::mobi_check::ExpectedMetadata {
        title: if title.is_empty() { None } else { Some(title) },
        author: if author.is_empty() { None } else { Some(author) },
        is_comic: true,
        is_dictionary: false,
    };
    let report = crate::mobi_check::check_mobi_file(output, &expected)?;
    crate::mobi_check::report_result(output, &report)?;

    Ok(())
}

/// Collect image file paths from input (folder, CBZ, CBR, or EPUB).
///
/// Returns (image_paths, optional_temp_dir). The temp dir, if present,
/// should be cleaned up by the caller after processing.
fn collect_images(input: &Path) -> Result<(Vec<PathBuf>, Option<PathBuf>), Box<dyn std::error::Error>> {
    if input.is_dir() {
        Ok((collect_images_from_dir(input)?, None))
    } else if let Some(ext) = input.extension() {
        let ext_lower = ext.to_string_lossy().to_lowercase();
        match ext_lower.as_str() {
            "cbz" | "zip" => {
                let (images, temp_dir) = extract_cbz(input)?;
                Ok((images, Some(temp_dir)))
            }
            "epub" => {
                let (images, temp_dir) = extract_epub_images(input)?;
                Ok((images, Some(temp_dir)))
            }
            "cbr" | "rar" => {
                let (images, temp_dir) = cbr::extract_cbr(input)?;
                Ok((images, Some(temp_dir)))
            }
            "pdf" => Err("PDF support coming soon".into()),
            _ => Err(format!("Unsupported input format: .{}", ext_lower).into()),
        }
    } else {
        Err("Cannot determine input type (not a directory and has no extension)".into())
    }
}

/// Extract images from an EPUB file in spine order.
///
/// Uses epub::extract_epub() to unpack the archive, then parses the OPF to get
/// spine ordering. For each spine item (XHTML file), finds referenced images
/// via `<img src="...">` or `<svg><image xlink:href="...">` tags. Returns images
/// in spine order, which is critical for correct page ordering in manga/comics.
///
/// Returns (image_paths, temp_extraction_dir).
fn extract_epub_images(epub_path: &Path) -> Result<(Vec<PathBuf>, PathBuf), Box<dyn std::error::Error>> {
    use crate::opf::OPFData;

    let (temp_dir, opf_path) = epub::extract_epub(epub_path)?;

    let opf = OPFData::parse(&opf_path)?;
    let opf_dir = opf_path.parent().unwrap_or(Path::new("."));

    // Collect images referenced in spine-ordered XHTML pages.
    // This preserves reading order rather than filesystem alphabetical order.
    let mut ordered_images: Vec<PathBuf> = Vec::new();
    let mut seen = std::collections::HashSet::new();

    for (_id, href) in &opf.spine_items {
        let xhtml_path = opf_dir.join(href);
        if !xhtml_path.exists() {
            continue;
        }

        let xhtml_dir = xhtml_path.parent().unwrap_or(opf_dir);

        let content = match fs::read_to_string(&xhtml_path) {
            Ok(c) => c,
            Err(_) => continue,
        };

        // Extract image references from the XHTML content
        let image_refs = extract_image_refs_from_xhtml(&content);

        for img_ref in image_refs {
            // Resolve relative path against the XHTML file's directory
            let img_path = xhtml_dir.join(&img_ref);
            let img_path = img_path.canonicalize().unwrap_or(img_path);

            if img_path.exists() && is_image_file(&img_path) && seen.insert(img_path.clone()) {
                ordered_images.push(img_path);
            }
        }
    }

    // If spine parsing yielded no images, fall back to collecting all images
    // from the extracted directory in natural sort order
    if ordered_images.is_empty() {
        eprintln!("No images found via EPUB spine, falling back to directory scan");
        ordered_images = collect_images_from_dir(&temp_dir)?;
    }

    if ordered_images.is_empty() {
        let _ = fs::remove_dir_all(&temp_dir);
        return Err("No image files found in EPUB archive".into());
    }

    eprintln!("EPUB: found {} images in spine order", ordered_images.len());

    Ok((ordered_images, temp_dir))
}

/// Extract image file references from XHTML content.
///
/// Handles three common patterns found in fixed-layout EPUB comics:
///   1. `<img src="...">` - standard HTML image tags
///   2. `<image xlink:href="...">` or `<image href="...">` - SVG image elements
///   3. CSS background-image references (less common, but seen in some EPUBs)
pub fn extract_image_refs_from_xhtml(content: &str) -> Vec<String> {
    use quick_xml::events::Event;
    use quick_xml::Reader;

    let mut refs = Vec::new();
    let mut reader = Reader::from_str(content);
    reader.config_mut().trim_text(true);
    let mut buf = Vec::new();

    loop {
        match reader.read_event_into(&mut buf) {
            Ok(Event::Start(ref e)) | Ok(Event::Empty(ref e)) => {
                let tag_name = e.name();
                let tag = std::str::from_utf8(tag_name.as_ref()).unwrap_or("");
                // Strip namespace prefix if present (e.g., "xhtml:img" -> "img")
                let local = tag.rsplit(':').next().unwrap_or(tag);

                match local {
                    "img" => {
                        // <img src="..."/>
                        for attr in e.attributes().flatten() {
                            if attr.key.as_ref() == b"src" {
                                let src = String::from_utf8_lossy(&attr.value).to_string();
                                if !src.is_empty() {
                                    refs.push(src);
                                }
                            }
                        }
                    }
                    "image" => {
                        // <image xlink:href="..." /> or <image href="..."/>
                        for attr in e.attributes().flatten() {
                            let key = std::str::from_utf8(attr.key.as_ref()).unwrap_or("");
                            // Match "href", "xlink:href", or any ns-prefixed href
                            if key == "href" || key.ends_with(":href") {
                                let href = String::from_utf8_lossy(&attr.value).to_string();
                                if !href.is_empty() {
                                    refs.push(href);
                                }
                            }
                        }
                    }
                    _ => {}
                }
            }
            Ok(Event::Eof) => break,
            Err(_) => {
                // XHTML parsing failed; fall back to regex extraction
                return extract_image_refs_regex(content);
            }
            _ => {}
        }
        buf.clear();
    }

    // If XML parsing yielded nothing, try regex as fallback
    // (some EPUB XHTML is not well-formed XML)
    if refs.is_empty() {
        return extract_image_refs_regex(content);
    }

    refs
}

/// Regex fallback for extracting image references from XHTML.
///
/// Used when the XML parser fails (malformed XHTML) or finds no images.
pub fn extract_image_refs_regex(content: &str) -> Vec<String> {
    use regex::Regex;
    use std::sync::OnceLock;

    static IMG_SRC_RE: OnceLock<Regex> = OnceLock::new();
    static IMAGE_HREF_RE: OnceLock<Regex> = OnceLock::new();

    let img_re = IMG_SRC_RE.get_or_init(|| {
        Regex::new(r#"<img\s[^>]*src="([^"]+)""#).unwrap()
    });
    let image_re = IMAGE_HREF_RE.get_or_init(|| {
        Regex::new(r#"<image\s[^>]*(?:xlink:)?href="([^"]+)""#).unwrap()
    });

    let mut refs = Vec::new();
    for cap in img_re.captures_iter(content) {
        if let Some(m) = cap.get(1) {
            refs.push(m.as_str().to_string());
        }
    }
    for cap in image_re.captures_iter(content) {
        if let Some(m) = cap.get(1) {
            refs.push(m.as_str().to_string());
        }
    }
    refs
}

/// Scan a directory for image files, sorted naturally by filename.
fn collect_images_from_dir(dir: &Path) -> Result<Vec<PathBuf>, Box<dyn std::error::Error>> {
    let mut images: Vec<PathBuf> = Vec::new();

    // Collect from this directory only (not recursive into subdirectories initially)
    // but if no images found at top level, try one level of subdirectories
    collect_images_recursive(dir, &mut images)?;

    if images.is_empty() {
        return Err(format!("No image files found in {}", dir.display()).into());
    }

    // Natural sort: sort by filename with numeric portions sorted numerically
    images.sort_by(|a, b| natural_sort_key(a).cmp(&natural_sort_key(b)));

    Ok(images)
}

/// Recursively collect image files from a directory.
fn collect_images_recursive(dir: &Path, images: &mut Vec<PathBuf>) -> Result<(), Box<dyn std::error::Error>> {
    let mut entries: Vec<_> = fs::read_dir(dir)?
        .filter_map(|e| e.ok())
        .collect();
    entries.sort_by_key(|e| e.file_name());

    for entry in entries {
        let path = entry.path();
        if path.is_dir() {
            collect_images_recursive(&path, images)?;
        } else if is_image_file(&path) {
            images.push(path);
        }
    }
    Ok(())
}

/// Check if a file path has an image extension.
fn is_image_file(path: &Path) -> bool {
    match path.extension().and_then(|e| e.to_str()) {
        Some(ext) => {
            let lower = ext.to_lowercase();
            matches!(lower.as_str(), "jpg" | "jpeg" | "png" | "gif" | "webp" | "bmp" | "tiff" | "tif")
        }
        None => false,
    }
}

/// Generate a natural sort key: split filename into text/numeric segments.
fn natural_sort_key(path: &Path) -> Vec<NaturalSortPart> {
    let name = path.file_name().unwrap_or_default().to_string_lossy();
    let mut parts = Vec::new();
    let mut current_num = String::new();
    let mut current_text = String::new();

    for ch in name.chars() {
        if ch.is_ascii_digit() {
            if !current_text.is_empty() {
                parts.push(NaturalSortPart::Text(current_text.to_lowercase()));
                current_text.clear();
            }
            current_num.push(ch);
        } else {
            if !current_num.is_empty() {
                parts.push(NaturalSortPart::Number(current_num.parse::<u64>().unwrap_or(0)));
                current_num.clear();
            }
            current_text.push(ch);
        }
    }
    if !current_num.is_empty() {
        parts.push(NaturalSortPart::Number(current_num.parse::<u64>().unwrap_or(0)));
    }
    if !current_text.is_empty() {
        parts.push(NaturalSortPart::Text(current_text.to_lowercase()));
    }
    parts
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
enum NaturalSortPart {
    // Number sorts before Text at the same position
    Number(u64),
    Text(String),
}

/// Extract images from a CBZ (ZIP) file to a temp directory, then collect paths.
///
/// Returns (image_paths, temp_extraction_dir).
fn extract_cbz(cbz_path: &Path) -> Result<(Vec<PathBuf>, PathBuf), Box<dyn std::error::Error>> {
    let file = fs::File::open(cbz_path)?;
    let mut archive = zip::ZipArchive::new(file)?;

    let stem = cbz_path.file_stem().unwrap_or_default().to_string_lossy();
    let parent = cbz_path.parent().unwrap_or(Path::new("."));
    let extract_dir = parent.join(format!(".kindling_cbz_{}", stem));

    if extract_dir.exists() {
        fs::remove_dir_all(&extract_dir)?;
    }
    fs::create_dir_all(&extract_dir)?;

    let mut image_paths: Vec<PathBuf> = Vec::new();

    for i in 0..archive.len() {
        let mut entry = archive.by_index(i)?;
        let name = entry.name().to_string();

        // Skip directories and hidden files (like __MACOSX)
        if name.ends_with('/') || name.starts_with("__MACOSX") || name.contains("/.") {
            continue;
        }

        let out_path = extract_dir.join(&name);

        // Also extract ComicInfo.xml if present
        let lower_name = name.to_lowercase();
        if lower_name == "comicinfo.xml" || lower_name.ends_with("/comicinfo.xml") {
            if let Some(parent_dir) = out_path.parent() {
                fs::create_dir_all(parent_dir)?;
            }
            let mut buf = Vec::new();
            entry.read_to_end(&mut buf)?;
            fs::write(&out_path, &buf)?;
            continue;
        }

        // Check if this is an image file before extracting
        if !is_image_file(Path::new(&name)) {
            continue;
        }

        if let Some(parent_dir) = out_path.parent() {
            fs::create_dir_all(parent_dir)?;
        }

        let mut buf = Vec::new();
        entry.read_to_end(&mut buf)?;
        fs::write(&out_path, &buf)?;
        image_paths.push(out_path);
    }

    // Natural sort
    image_paths.sort_by(|a, b| natural_sort_key(a).cmp(&natural_sort_key(b)));

    if image_paths.is_empty() {
        // Clean up the empty extraction dir
        let _ = fs::remove_dir_all(&extract_dir);
        return Err("No image files found in CBZ archive".into());
    }

    Ok((image_paths, extract_dir))
}

/// Full image processing pipeline: split spreads, crop, enhance, resize, encode.
///
/// Returns one or two JPEG byte vectors (two if the image was a double-page spread
/// and splitting is enabled).
fn process_image_pipeline(
    path: &Path,
    profile: &DeviceProfile,
    options: &ComicOptions,
    cover_fill: bool,
) -> Result<Vec<Vec<u8>>, Box<dyn std::error::Error>> {
    let mut img = image::open(path)?;

    // Check for zero-dimension images
    let (w, h) = img.dimensions();
    if w == 0 || h == 0 {
        return Err(format!("zero dimensions ({}x{})", w, h).into());
    }

    // Step 0: Moire correction for grayscale source images on color devices.
    // Color e-ink screens (Colorsoft, Fire) use a CFA overlay that produces
    // rainbow artifacts when displaying high-frequency grayscale content like
    // manga screentone. Apply a mild blur + unsharp mask to suppress this.
    if !profile.grayscale && is_grayscale_source(&img) {
        moire::remove_moire(&mut img);
    }

    // Step 1: Crop borders on the full image BEFORE splitting spreads.
    // Cropping the full spread first ensures both halves get symmetric treatment.
    // If we split first and crop each half independently, asymmetric borders on
    // the left vs. right half can produce mismatched page sizes.
    let img = match options.crop {
        0 => img,
        // Mode 1: margin crop only
        1 => crop_borders(&img),
        // Mode 2 (default): margins + page numbers
        _ => {
            let cropped = crop_borders(&img);
            crop_page_numbers(&cropped)
        }
    };

    // Step 2: Detect and split double-page spreads
    // Always split as [left, right] regardless of RTL. The global page reversal
    // in build_comic_with_options handles RTL ordering: reversing [left, right]
    // yields [right, left], which is the correct RTL reading order for a spread.
    // Swapping here AND reversing globally would cancel out, producing the wrong
    // cover image (left half instead of right half for RTL).
    //
    // When rotate_spreads is enabled, landscape spreads are rotated 90 degrees
    // clockwise instead of being split, producing a single portrait page that
    // preserves the full spread. This overrides the split behavior for spreads.
    let pages = if options.rotate_spreads && is_double_page_spread(&img) {
        vec![img.rotate90()]
    } else if options.split && is_double_page_spread(&img) {
        let (left, right) = split_spread(&img);
        vec![left, right]
    } else {
        vec![img]
    };

    // Step 3-4: Process each page (enhance, resize, encode)
    let mut results = Vec::new();
    for (page_idx, page) in pages.into_iter().enumerate() {
        let page = if options.enhance && profile.grayscale {
            enhance_image(&page)
        } else {
            page
        };

        // Cover fill: center-crop to device aspect ratio (first page only)
        let page = if cover_fill && page_idx == 0 {
            cover_fill_crop(&page, profile.width, profile.height)
        } else {
            page
        };

        // Resize to fit device dimensions while maintaining aspect ratio
        let page = page.resize(profile.width, profile.height, FilterType::Lanczos3);

        // Convert to grayscale if the device profile requires it
        let page = if profile.grayscale {
            DynamicImage::ImageLuma8(page.to_luma8())
        } else {
            page
        };

        // Encode as JPEG with the configured quality level
        let jpeg_buf = encode_jpeg(&page, options.jpeg_quality)?;
        results.push(jpeg_buf);
    }

    Ok(results)
}

/// Center-crop an image to match the target aspect ratio.
///
/// If the image is wider than the target ratio, trims left and right equally.
/// If the image is taller than the target ratio, trims top and bottom equally.
/// Returns the original image unchanged if it already matches the target ratio.
fn cover_fill_crop(img: &DynamicImage, target_width: u32, target_height: u32) -> DynamicImage {
    let (w, h) = img.dimensions();
    let target_ratio = target_width as f64 / target_height as f64;
    let img_ratio = w as f64 / h as f64;

    if (img_ratio - target_ratio).abs() < 0.001 {
        // Already matches the target aspect ratio
        return img.clone();
    }

    let (crop_w, crop_h) = if img_ratio > target_ratio {
        // Image is wider than target: crop horizontally (keep full height)
        let new_w = (h as f64 * target_ratio).round() as u32;
        (new_w.min(w), h)
    } else {
        // Image is taller than target: crop vertically (keep full width)
        let new_h = (w as f64 / target_ratio).round() as u32;
        (w, new_h.min(h))
    };

    let x = (w - crop_w) / 2;
    let y = (h - crop_h) / 2;

    image::imageops::crop_imm(img, x, y, crop_w, crop_h).to_image().into()
}

/// Encode a DynamicImage as JPEG with a specific quality level (1-100).
fn encode_jpeg(img: &DynamicImage, quality: u8) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
    let mut jpeg_buf = Vec::new();
    let cursor = std::io::Cursor::new(&mut jpeg_buf);
    let encoder = image::codecs::jpeg::JpegEncoder::new_with_quality(cursor, quality);
    img.write_with_encoder(encoder)?;
    Ok(jpeg_buf)
}

// ---------------------------------------------------------------------------
// Grayscale source detection (for moire correction)
// ---------------------------------------------------------------------------

/// Check if a source image is effectively grayscale.
///
/// Returns true if the image is a GrayImage, or if it's an RGB/RGBA image
/// where the color channels have very low variance (i.e. R ~= G ~= B for all
/// pixels). This catches grayscale manga/comics saved as RGB files.
fn is_grayscale_source(img: &DynamicImage) -> bool {
    match img {
        DynamicImage::ImageLuma8(_) | DynamicImage::ImageLuma16(_) => true,
        _ => {
            // Sample pixels to check if R ~= G ~= B across the image.
            // For efficiency, sample at most ~1000 pixels in a grid.
            let (w, h) = img.dimensions();
            if w == 0 || h == 0 {
                return true;
            }
            let rgb = img.to_rgb8();
            let step_x = (w / 32).max(1);
            let step_y = (h / 32).max(1);
            let mut max_channel_diff: u8 = 0;
            let mut x = 0;
            while x < w {
                let mut y = 0;
                while y < h {
                    let p = rgb.get_pixel(x, y).0;
                    let r = p[0];
                    let g = p[1];
                    let b = p[2];
                    let diff = (r.max(g).max(b)) - (r.min(g).min(b));
                    if diff > max_channel_diff {
                        max_channel_diff = diff;
                    }
                    // Early exit: if any sampled pixel has significant color,
                    // this is not a grayscale source.
                    if max_channel_diff > 10 {
                        return false;
                    }
                    y += step_y;
                }
                x += step_x;
            }
            // All sampled pixels had R ~= G ~= B within 10 levels
            true
        }
    }
}

// ---------------------------------------------------------------------------
// Double-page spread detection and splitting
// ---------------------------------------------------------------------------

/// Detect whether an image is a double-page spread (landscape orientation).
pub fn is_double_page_spread(img: &DynamicImage) -> bool {
    let (w, h) = img.dimensions();
    w > h
}

/// Split a landscape image into left and right halves.
pub fn split_spread(img: &DynamicImage) -> (DynamicImage, DynamicImage) {
    let (w, h) = img.dimensions();
    let mid = w / 2;
    let left = img.crop_imm(0, 0, mid, h);
    let right = img.crop_imm(mid, 0, w - mid, h);
    (left, right)
}

// ---------------------------------------------------------------------------
// Border/margin cropping
// ---------------------------------------------------------------------------

/// Detect and crop uniform-color borders around an image.
///
/// Scans each edge inward looking for rows/columns whose average pixel value
/// is within a threshold of the edge pixel. Only crops if the border is at
/// least 2% of the image dimension to avoid false positives.
pub fn crop_borders(img: &DynamicImage) -> DynamicImage {
    let gray = img.to_luma8();
    let (w, h) = gray.dimensions();
    if w < 10 || h < 10 {
        return img.clone();
    }

    let threshold: f64 = 20.0; // Pixel value tolerance for "same color as border"
    let min_border_frac: f64 = 0.02; // Minimum 2% of dimension to count as border

    // Detect top border
    let edge_top = row_average(&gray, 0);
    let mut top = 0u32;
    for y in 0..h {
        if (row_average(&gray, y) - edge_top).abs() > threshold {
            break;
        }
        top = y + 1;
    }
    if (top as f64) < (h as f64 * min_border_frac) {
        top = 0;
    }

    // Detect bottom border
    let edge_bottom = row_average(&gray, h - 1);
    let mut bottom = h;
    for y in (0..h).rev() {
        if (row_average(&gray, y) - edge_bottom).abs() > threshold {
            break;
        }
        bottom = y;
    }
    if ((h - bottom) as f64) < (h as f64 * min_border_frac) {
        bottom = h;
    }

    // Detect left border
    let edge_left = col_average(&gray, 0);
    let mut left = 0u32;
    for x in 0..w {
        if (col_average(&gray, x) - edge_left).abs() > threshold {
            break;
        }
        left = x + 1;
    }
    if (left as f64) < (w as f64 * min_border_frac) {
        left = 0;
    }

    // Detect right border
    let edge_right = col_average(&gray, w - 1);
    let mut right = w;
    for x in (0..w).rev() {
        if (col_average(&gray, x) - edge_right).abs() > threshold {
            break;
        }
        right = x;
    }
    if ((w - right) as f64) < (w as f64 * min_border_frac) {
        right = w;
    }

    // Ensure we have a valid crop region
    if left >= right || top >= bottom {
        return img.clone();
    }

    // Only crop if we actually detected borders
    if top == 0 && bottom == h && left == 0 && right == w {
        return img.clone();
    }

    img.crop_imm(left, top, right - left, bottom - top)
}

/// Average pixel value of a row in a grayscale image.
fn row_average(img: &GrayImage, y: u32) -> f64 {
    let w = img.width();
    let sum: f64 = (0..w).map(|x| img.get_pixel(x, y).0[0] as f64).sum();
    sum / w as f64
}

/// Average pixel value of a column in a grayscale image.
fn col_average(img: &GrayImage, x: u32) -> f64 {
    let h = img.height();
    let sum: f64 = (0..h).map(|y| img.get_pixel(x, y).0[0] as f64).sum();
    sum / h as f64
}

// ---------------------------------------------------------------------------
// Page number cropping
// ---------------------------------------------------------------------------

/// Detect and crop page-number strips from the top and/or bottom of an image.
///
/// Page numbers in comics are typically a small number (e.g. "1", "23", "iv")
/// sitting alone in a thin strip at the very top or bottom edge. This function
/// examines strips of configurable height at each edge and crops them when:
///
///   - The strip is dominated by one background color (sampled from the corners).
///   - A small cluster of non-background pixels exists (the page number itself),
///     covering less than `MAX_INK_FRAC` of the strip area.
///
/// The function is intentionally conservative: false negatives (leaving a page
/// number in place) are acceptable, false positives (cropping real content) are
/// not. It is designed to run on an already margin-cropped image.
pub fn crop_page_numbers(img: &DynamicImage) -> DynamicImage {
    let gray = img.to_luma8();
    let (w, h) = gray.dimensions();

    // Images too small to sensibly analyse - return unchanged.
    if w < 20 || h < 40 {
        return img.clone();
    }

    // How much of the image height to inspect at each edge (top/bottom).
    const STRIP_FRAC: f64 = 0.06; // 6%
    // Maximum fraction of non-background ("ink") pixels in the strip for it to
    // be considered a page-number strip. Real page numbers are tiny; panels or
    // speech bubbles will have far more ink.
    const MAX_INK_FRAC: f64 = 0.08;
    // Minimum ink required so we don't crop a strip that is pure background
    // (that case is already handled by crop_borders).
    const MIN_INK_FRAC: f64 = 0.0005;
    // Pixel-value tolerance: a pixel whose luma differs from the background
    // by more than this is "ink".
    const COLOR_TOL: u8 = 30;

    let strip_h = ((h as f64 * STRIP_FRAC).round() as u32).max(3);

    // --- Detect background color from corner samples ---
    let bg = detect_strip_background(&gray, w, h);

    // --- Bottom strip ---
    let crop_bottom = if h > strip_h {
        is_page_number_strip(&gray, w, h.saturating_sub(strip_h), h, bg, COLOR_TOL, MIN_INK_FRAC, MAX_INK_FRAC)
    } else {
        0
    };

    // --- Top strip ---
    let crop_top = if h > strip_h {
        is_page_number_strip(&gray, w, 0, strip_h, bg, COLOR_TOL, MIN_INK_FRAC, MAX_INK_FRAC)
    } else {
        0
    };

    // Safety: never remove more than 10% total from the height.
    let max_total = (h as f64 * 0.10) as u32;
    if crop_top + crop_bottom > max_total || crop_top + crop_bottom == 0 {
        return img.clone();
    }

    let new_top = crop_top;
    let new_bottom = h - crop_bottom;
    if new_top >= new_bottom {
        return img.clone();
    }

    img.crop_imm(0, new_top, w, new_bottom - new_top)
}

/// Sample the four corners and edges of a grayscale image to estimate the
/// background luma value.
fn detect_strip_background(gray: &GrayImage, w: u32, h: u32) -> u8 {
    // Sample a few pixels from each corner and each edge midpoint
    let samples = [
        (0, 0),
        (w - 1, 0),
        (0, h - 1),
        (w - 1, h - 1),
        (w / 2, 0),
        (w / 2, h - 1),
        (0, h / 2),
        (w - 1, h / 2),
    ];
    let sum: u32 = samples.iter().map(|&(x, y)| gray.get_pixel(x, y).0[0] as u32).sum();
    (sum / samples.len() as u32) as u8
}

/// Analyse a horizontal strip and return the number of rows to crop (0 if the
/// strip does not look like an isolated page number).
///
/// `y_start..y_end` defines the strip. The function counts "ink" pixels (those
/// differing from `bg` by more than `tol`) and checks that:
///   1. The ink fraction is between `min_ink` and `max_ink`.
///   2. The ink is horizontally concentrated (not spread across the full width,
///      which would indicate a panel border or text block).
fn is_page_number_strip(
    gray: &GrayImage,
    w: u32,
    y_start: u32,
    y_end: u32,
    bg: u8,
    tol: u8,
    min_ink: f64,
    max_ink: f64,
) -> u32 {
    let strip_h = y_end - y_start;
    let total_pixels = (w as u64) * (strip_h as u64);
    if total_pixels == 0 {
        return 0;
    }

    let mut ink_count: u64 = 0;
    let mut ink_x_min: u32 = w;
    let mut ink_x_max: u32 = 0;
    let mut ink_y_min: u32 = y_end;
    let mut ink_y_max: u32 = y_start;

    for y in y_start..y_end {
        for x in 0..w {
            let v = gray.get_pixel(x, y).0[0];
            let diff = if v > bg { v - bg } else { bg - v };
            if diff > tol {
                ink_count += 1;
                if x < ink_x_min { ink_x_min = x; }
                if x > ink_x_max { ink_x_max = x; }
                if y < ink_y_min { ink_y_min = y; }
                if y > ink_y_max { ink_y_max = y; }
            }
        }
    }

    let ink_frac = ink_count as f64 / total_pixels as f64;

    // Must have *some* ink (otherwise it's just blank margin, not a page number).
    if ink_frac < min_ink {
        return 0;
    }
    // Too much ink - likely real content (panel, speech bubble, etc.).
    if ink_frac > max_ink {
        return 0;
    }

    // The ink cluster should be horizontally narrow relative to the page width.
    // A page number like "123" occupies perhaps 5-15% of the width. A panel
    // border or wide text block will span much more.
    if ink_x_min >= ink_x_max {
        return 0;
    }
    let ink_width_frac = (ink_x_max - ink_x_min) as f64 / w as f64;
    if ink_width_frac > 0.35 {
        return 0;
    }

    // Passed all checks - return the full strip height as the crop amount.
    strip_h
}

// ---------------------------------------------------------------------------
// Auto-contrast and gamma correction
// ---------------------------------------------------------------------------

/// Apply auto-contrast (histogram stretching) and gamma correction.
///
/// Auto-contrast clips 0.5% from each end of the histogram and stretches
/// the remaining range to 0-255. Gamma correction (0.8) darkens midtones
/// slightly for better e-ink readability.
pub fn enhance_image(img: &DynamicImage) -> DynamicImage {
    let gray = img.to_luma8();
    let (w, h) = gray.dimensions();
    let total_pixels = (w * h) as f64;

    // Build histogram
    let mut histogram = [0u32; 256];
    for pixel in gray.pixels() {
        histogram[pixel.0[0] as usize] += 1;
    }

    // Find clip points at 0.5% from each end
    let clip_count = (total_pixels * 0.005) as u32;
    let mut low = 0u8;
    let mut cumulative = 0u32;
    for i in 0..256 {
        cumulative += histogram[i];
        if cumulative >= clip_count {
            low = i as u8;
            break;
        }
    }

    let mut high = 255u8;
    cumulative = 0;
    for i in (0..256).rev() {
        cumulative += histogram[i];
        if cumulative >= clip_count {
            high = i as u8;
            break;
        }
    }

    if high <= low {
        // Image is essentially uniform, nothing to enhance
        return img.clone();
    }

    // Build lookup table: auto-contrast + gamma
    let gamma: f64 = 0.8;
    let range = (high - low) as f64;
    let mut lut = [0u8; 256];
    for i in 0..256 {
        let clamped = (i as u8).max(low).min(high);
        let normalized = (clamped - low) as f64 / range; // 0.0 .. 1.0
        let gamma_corrected = normalized.powf(gamma);
        lut[i] = (gamma_corrected * 255.0).round().clamp(0.0, 255.0) as u8;
    }

    // Apply to all channels of the original image
    let (w, h) = img.dimensions();
    match img {
        DynamicImage::ImageLuma8(_) => {
            let mut out = GrayImage::new(w, h);
            for (x, y, pixel) in gray.enumerate_pixels() {
                out.put_pixel(x, y, Luma([lut[pixel.0[0] as usize]]));
            }
            DynamicImage::ImageLuma8(out)
        }
        _ => {
            // For color images, convert to grayscale for LUT, then apply to each channel
            let rgb = img.to_rgb8();
            let mut out = RgbImage::new(w, h);
            for (x, y, pixel) in rgb.enumerate_pixels() {
                out.put_pixel(x, y, Rgb([
                    lut[pixel.0[0] as usize],
                    lut[pixel.0[1] as usize],
                    lut[pixel.0[2] as usize],
                ]));
            }
            DynamicImage::ImageRgb8(out)
        }
    }
}

// ---------------------------------------------------------------------------
// Webtoon detection, merging, and splitting
// ---------------------------------------------------------------------------

/// Detect webtoon format: all input images have height > 3x width.
pub fn detect_webtoon(images: &[PathBuf]) -> bool {
    if images.is_empty() {
        return false;
    }
    images.iter().all(|path| {
        match image::image_dimensions(path) {
            Ok((w, h)) => h > 3 * w,
            Err(_) => false,
        }
    })
}

/// Full webtoon preprocessing: load images, merge into a tall strip, split at gutters.
///
/// If the merged strip would exceed `options.max_height`, the images are split
/// into chunks that each stay under the limit. Each chunk is merged and split
/// independently. This prevents OOM on massive webtoon directories.
///
/// Returns a list of temporary file paths for the split page images.
fn webtoon_preprocess(
    source_images: &[PathBuf],
    profile: &DeviceProfile,
    options: &ComicOptions,
) -> Result<Vec<PathBuf>, Box<dyn std::error::Error>> {
    // Load all images, skipping corrupt/unreadable ones
    let mut images: Vec<DynamicImage> = Vec::new();
    for p in source_images {
        match image::open(p) {
            Ok(img) => {
                let (w, h) = img.dimensions();
                if w == 0 || h == 0 {
                    eprintln!("Warning: skipping {} (zero dimensions {}x{})", p.display(), w, h);
                    continue;
                }
                images.push(img);
            }
            Err(e) => {
                eprintln!("Warning: skipping {} ({})", p.display(), e);
            }
        }
    }

    if images.is_empty() {
        return Err("All images failed to load - no valid images to process".into());
    }

    // Calculate total height to decide if we need to chunk
    let total_height: u32 = images.iter().map(|img| img.height()).sum();
    let max_height = options.max_height;

    let chunks: Vec<Vec<DynamicImage>> = if total_height > max_height {
        eprintln!(
            "Warning: merged strip height ({}) exceeds --max-height ({}), splitting into chunks",
            total_height, max_height
        );
        // Split images into chunks where each chunk's total height <= max_height
        let mut chunks = Vec::new();
        let mut current_chunk: Vec<DynamicImage> = Vec::new();
        let mut current_height: u32 = 0;

        for img in images {
            let h = img.height();
            if !current_chunk.is_empty() && current_height + h > max_height {
                chunks.push(std::mem::take(&mut current_chunk));
                current_height = 0;
            }
            current_height += h;
            current_chunk.push(img);
        }
        if !current_chunk.is_empty() {
            chunks.push(current_chunk);
        }
        eprintln!("Processing {} chunks", chunks.len());
        chunks
    } else {
        vec![images]
    };

    let temp_dir = std::env::temp_dir().join(format!(
        "kindling_webtoon_{}",
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_millis()
    ));
    fs::create_dir_all(&temp_dir)?;

    let mut all_paths: Vec<PathBuf> = Vec::new();
    let mut page_offset = 0usize;

    for (chunk_idx, chunk_images) in chunks.iter().enumerate() {
        // Merge into a single tall strip
        let strip = webtoon_merge(chunk_images);
        let (strip_w, strip_h) = strip.dimensions();
        if chunks.len() > 1 {
            eprintln!("Chunk {}: merged strip {}x{}", chunk_idx + 1, strip_w, strip_h);
        } else {
            eprintln!("Merged webtoon strip: {}x{}", strip_w, strip_h);
        }

        // Split at gutters
        let pages = webtoon_split(&strip, profile.height);
        if chunks.len() > 1 {
            eprintln!("Chunk {}: split into {} pages", chunk_idx + 1, pages.len());
        } else {
            eprintln!("Split into {} page images", pages.len());
        }

        let offset = page_offset;
        let paths: Vec<PathBuf> = pages
            .into_par_iter()
            .enumerate()
            .map(|(i, page)| {
                let path = temp_dir.join(format!("page_{:04}.png", offset + i));
                page.save(&path).expect("Failed to save webtoon page");
                path
            })
            .collect();

        // Sort by filename to preserve order (par_iter may reorder)
        let mut paths = paths;
        paths.sort_by(|a, b| natural_sort_key(a).cmp(&natural_sort_key(b)));

        page_offset += paths.len();
        all_paths.extend(paths);
    }

    Ok(all_paths)
}

/// Merge multiple images vertically into one tall strip.
///
/// Images are stacked top-to-bottom. If widths differ, narrower images are
/// centered on a background color detected from the first image's edge pixels.
pub fn webtoon_merge(images: &[DynamicImage]) -> DynamicImage {
    if images.len() == 1 {
        return images[0].clone();
    }

    let max_width = images.iter().map(|img| img.width()).max().unwrap_or(0);
    let total_height: u32 = images.iter().map(|img| img.height()).sum();

    // Detect background color from the top-left corner of the first image
    let bg_color = detect_background_color(&images[0]);

    let mut canvas = RgbImage::from_pixel(max_width, total_height, bg_color);
    let mut y_offset = 0u32;

    for img in images {
        let rgb = img.to_rgb8();
        let (w, h) = (rgb.width(), rgb.height());
        let x_offset = (max_width - w) / 2; // center narrower images

        for py in 0..h {
            for px in 0..w {
                canvas.put_pixel(x_offset + px, y_offset + py, *rgb.get_pixel(px, py));
            }
        }
        y_offset += h;
    }

    DynamicImage::ImageRgb8(canvas)
}

/// Detect the background color of an image from its edge pixels.
///
/// Samples the corners and edges to determine if the background is
/// predominantly white or black (or something else).
fn detect_background_color(img: &DynamicImage) -> Rgb<u8> {
    let rgb = img.to_rgb8();
    let (w, h) = (rgb.width(), rgb.height());
    if w == 0 || h == 0 {
        return Rgb([255, 255, 255]);
    }

    // Sample edge pixels: top row, bottom row, left column, right column
    let mut sum_r: u64 = 0;
    let mut sum_g: u64 = 0;
    let mut sum_b: u64 = 0;
    let mut count: u64 = 0;

    // Top row
    for x in 0..w {
        let p = rgb.get_pixel(x, 0);
        sum_r += p.0[0] as u64;
        sum_g += p.0[1] as u64;
        sum_b += p.0[2] as u64;
        count += 1;
    }
    // Bottom row
    for x in 0..w {
        let p = rgb.get_pixel(x, h - 1);
        sum_r += p.0[0] as u64;
        sum_g += p.0[1] as u64;
        sum_b += p.0[2] as u64;
        count += 1;
    }

    if count == 0 {
        return Rgb([255, 255, 255]);
    }

    let avg_r = (sum_r / count) as u8;
    let avg_g = (sum_g / count) as u8;
    let avg_b = (sum_b / count) as u8;

    // Classify: if average luminance is dark, use black; otherwise use white
    let luminance = (avg_r as u32 + avg_g as u32 + avg_b as u32) / 3;
    if luminance < 128 {
        Rgb([0, 0, 0])
    } else {
        Rgb([255, 255, 255])
    }
}

/// Split a tall strip image into device-height pages at natural gutters.
///
/// Searches for horizontal rows of low variance (gutters between panels)
/// within +/- 20% of the target height. When no good gutter is found,
/// splits at the target height with overlap: the bottom ~10% of each page
/// overlaps with the top of the next page, so no content is lost even if
/// the cut goes through a panel.
pub fn webtoon_split(strip: &DynamicImage, device_height: u32) -> Vec<DynamicImage> {
    let (w, h) = strip.dimensions();

    if h <= device_height {
        return vec![strip.clone()];
    }

    let gray = strip.to_luma8();
    let target = device_height;
    let margin = (target as f64 * 0.20) as u32;
    let overlap = (target as f64 * 0.10) as u32; // 10% overlap when no gutter found

    let mut pages = Vec::new();
    let mut y_start = 0u32;

    while y_start < h {
        let remaining = h - y_start;

        // If remaining content fits in one page (with some slack), take it all.
        // The slack accounts for overlap from the previous page: if the remaining
        // content is shorter than target + margin, just include it rather than
        // creating a tiny final page.
        if remaining <= target + margin {
            pages.push(strip.crop_imm(0, y_start, w, remaining));
            break;
        }

        // Search for best gutter in [target - margin, target + margin]
        let search_lo = target.saturating_sub(margin);
        let search_hi = (target + margin).min(remaining);

        let (best_y, gutter_found) = find_best_gutter(&gray, y_start, search_lo, search_hi, w);

        let cut_y = y_start + best_y;
        pages.push(strip.crop_imm(0, y_start, w, best_y));

        if gutter_found {
            // Clean gutter found - advance past it with no overlap
            y_start = cut_y;
        } else {
            // No good gutter - back up by the overlap amount so the next page
            // repeats the bottom portion of this page
            y_start = cut_y.saturating_sub(overlap);
        }
    }

    pages
}

/// Find the row with the lowest variance (best gutter) within a search range.
///
/// Scans rows from y_start + lo to y_start + hi and returns a tuple of
/// (offset_from_y_start, gutter_found). When `gutter_found` is false, the
/// returned offset is the target midpoint and the caller should apply
/// overlap to avoid cutting through content.
///
/// This works for both white gutters (all ~255) and dark/black gutters
/// (all ~0) since variance measures uniformity regardless of the mean
/// brightness.
///
/// To improve detection of gutters that span multiple consecutive rows (common
/// in webtoons with thick panel gaps), we average variance over a small window
/// of rows. This makes the detector more robust to single-row noise that might
/// appear inside a gutter band.
fn find_best_gutter(
    gray: &GrayImage,
    y_start: u32,
    lo: u32,
    hi: u32,
    width: u32,
) -> (u32, bool) {
    let target_mid = (lo + hi) / 2;
    let mut best_offset = target_mid;
    let mut best_score = f64::MAX;
    let img_height = gray.height();

    // Use a small window (5 rows) to average variance, making detection more
    // robust for thick gutters that may have slight noise in individual rows.
    let half_window: u32 = 2;

    for offset in lo..=hi {
        let y = y_start + offset;
        if y >= img_height {
            break;
        }

        // Average variance over a window of rows centered on y
        let win_lo = y.saturating_sub(half_window);
        let win_hi = (y + half_window + 1).min(img_height);
        let mut var_sum = 0.0;
        let mut count = 0u32;
        for wy in win_lo..win_hi {
            var_sum += row_variance(gray, wy, width);
            count += 1;
        }
        let avg_variance = if count > 0 { var_sum / count as f64 } else { f64::MAX };

        if avg_variance < best_score {
            best_score = avg_variance;
            best_offset = offset;
        }
    }

    // A "good" gutter has very low variance (near-uniform row).
    // Threshold: variance < 100.0 indicates a fairly uniform row.
    if best_score > 100.0 {
        // No good gutter found - return target midpoint with flag
        return (target_mid, false);
    }

    (best_offset, true)
}

/// Calculate the pixel variance of a single row.
fn row_variance(gray: &GrayImage, y: u32, width: u32) -> f64 {
    if width == 0 {
        return 0.0;
    }

    let mut sum: f64 = 0.0;
    let mut sum_sq: f64 = 0.0;

    for x in 0..width {
        let v = gray.get_pixel(x, y).0[0] as f64;
        sum += v;
        sum_sq += v * v;
    }

    let n = width as f64;
    let mean = sum / n;
    (sum_sq / n) - (mean * mean)
}

// ---------------------------------------------------------------------------
// Panel View: detection and markup
// ---------------------------------------------------------------------------

/// A rectangular panel region as percentages of the page dimensions.
#[derive(Debug, Clone, PartialEq)]
pub struct PanelRect {
    /// Left edge as percentage (0.0 - 100.0)
    pub x: f64,
    /// Top edge as percentage (0.0 - 100.0)
    pub y: f64,
    /// Width as percentage (0.0 - 100.0)
    pub w: f64,
    /// Height as percentage (0.0 - 100.0)
    pub h: f64,
}

/// Detect panel boundaries in a comic page image.
///
/// Algorithm:
/// 1. Convert to grayscale
/// 2. Find horizontal gutters (rows of low variance spanning the image width)
/// 3. For each horizontal strip between gutters, find vertical gutters
/// 4. Each resulting rectangle is a panel
///
/// Returns an empty Vec if no panels are detected (e.g., full-page splash).
pub fn detect_panels(img: &DynamicImage) -> Vec<PanelRect> {
    let gray = img.to_luma8();
    let (w, h) = gray.dimensions();
    if w < 20 || h < 20 {
        return Vec::new();
    }

    let variance_threshold: f64 = 50.0;
    let min_gutter_height = ((h as f64) * 0.005).max(2.0) as u32; // 0.5% of height, min 2px
    let min_gutter_width = ((w as f64) * 0.005).max(2.0) as u32;  // 0.5% of width, min 2px

    // Step 1: Find horizontal gutters
    let h_gutters = find_horizontal_gutters(&gray, w, h, variance_threshold, min_gutter_height);

    // Build horizontal strip boundaries from gutters
    let h_strips = strips_from_gutters(&h_gutters, h);

    // If we only have one horizontal strip (no horizontal gutters found),
    // try vertical gutters across the entire image. If none found either, return empty.
    if h_strips.len() <= 1 {
        let v_gutters = find_vertical_gutters(&gray, 0, h, w, variance_threshold, min_gutter_width);
        let v_strips = strips_from_gutters(&v_gutters, w);
        if v_strips.len() <= 1 {
            // No panels detected - full page splash
            return Vec::new();
        }
        // Single row, multiple columns
        return v_strips
            .iter()
            .map(|&(x_start, x_end)| PanelRect {
                x: (x_start as f64 / w as f64) * 100.0,
                y: 0.0,
                w: ((x_end - x_start) as f64 / w as f64) * 100.0,
                h: 100.0,
            })
            .collect();
    }

    // Step 2: For each horizontal strip, find vertical gutters
    let mut panels = Vec::new();
    for &(y_start, y_end) in &h_strips {
        let v_gutters = find_vertical_gutters(
            &gray, y_start, y_end, w, variance_threshold, min_gutter_width,
        );
        let v_strips = strips_from_gutters(&v_gutters, w);

        for &(x_start, x_end) in &v_strips {
            panels.push(PanelRect {
                x: (x_start as f64 / w as f64) * 100.0,
                y: (y_start as f64 / h as f64) * 100.0,
                w: ((x_end - x_start) as f64 / w as f64) * 100.0,
                h: ((y_end - y_start) as f64 / h as f64) * 100.0,
            });
        }
    }

    // Only return panels if we found more than one
    if panels.len() <= 1 {
        return Vec::new();
    }

    panels
}

/// Resolve the effective panel reading order string.
///
/// If an explicit reading order is provided, returns it. Otherwise returns
/// "horizontal-rl" when RTL mode is active, or "horizontal-lr" as the default.
pub fn resolve_panel_reading_order(explicit: Option<&str>, rtl: bool) -> &'static str {
    match explicit {
        Some("horizontal-lr") => "horizontal-lr",
        Some("horizontal-rl") => "horizontal-rl",
        Some("vertical-lr") => "vertical-lr",
        Some("vertical-rl") => "vertical-rl",
        Some(other) => {
            eprintln!("Warning: unknown panel-reading-order '{}', using default", other);
            if rtl { "horizontal-rl" } else { "horizontal-lr" }
        }
        None => {
            if rtl { "horizontal-rl" } else { "horizontal-lr" }
        }
    }
}

/// Sort panels according to the specified reading order.
///
/// The panels produced by `detect_panels` are in row-major left-to-right order
/// (horizontal-lr). This function re-sorts them for other reading orders:
/// - "horizontal-lr": left-to-right, then top-to-bottom (no change needed)
/// - "horizontal-rl": right-to-left, then top-to-bottom
/// - "vertical-lr": top-to-bottom, then left-to-right
/// - "vertical-rl": top-to-bottom, then right-to-left
///
/// Panels are grouped into rows/columns using a tolerance of 5% to account
/// for slight misalignment in detected panel edges.
pub fn sort_panels_by_reading_order(panels: &mut Vec<PanelRect>, reading_order: &str) {
    if panels.len() <= 1 {
        return;
    }

    let tolerance = 5.0; // percentage tolerance for grouping panels into rows/columns

    match reading_order {
        "horizontal-lr" => {
            // Primary: top-to-bottom (by y), Secondary: left-to-right (by x)
            // This is the default order from detect_panels, but sort explicitly
            panels.sort_by(|a, b| {
                let row_a = (a.y / tolerance).floor() as i64;
                let row_b = (b.y / tolerance).floor() as i64;
                row_a.cmp(&row_b).then_with(|| a.x.partial_cmp(&b.x).unwrap_or(std::cmp::Ordering::Equal))
            });
        }
        "horizontal-rl" => {
            // Primary: top-to-bottom (by y), Secondary: right-to-left (by x, descending)
            panels.sort_by(|a, b| {
                let row_a = (a.y / tolerance).floor() as i64;
                let row_b = (b.y / tolerance).floor() as i64;
                row_a.cmp(&row_b).then_with(|| b.x.partial_cmp(&a.x).unwrap_or(std::cmp::Ordering::Equal))
            });
        }
        "vertical-lr" => {
            // Primary: left-to-right (by x), Secondary: top-to-bottom (by y)
            panels.sort_by(|a, b| {
                let col_a = (a.x / tolerance).floor() as i64;
                let col_b = (b.x / tolerance).floor() as i64;
                col_a.cmp(&col_b).then_with(|| a.y.partial_cmp(&b.y).unwrap_or(std::cmp::Ordering::Equal))
            });
        }
        "vertical-rl" => {
            // Primary: right-to-left (by x, descending), Secondary: top-to-bottom (by y)
            panels.sort_by(|a, b| {
                let col_a = (a.x / tolerance).floor() as i64;
                let col_b = (b.x / tolerance).floor() as i64;
                col_b.cmp(&col_a).then_with(|| a.y.partial_cmp(&b.y).unwrap_or(std::cmp::Ordering::Equal))
            });
        }
        _ => {
            // Unknown reading order - leave as-is (horizontal-lr default)
        }
    }
}

/// Find horizontal gutters - consecutive runs of low-variance rows.
///
/// Returns a list of (start_y, end_y) pairs for each gutter.
fn find_horizontal_gutters(
    gray: &GrayImage,
    width: u32,
    height: u32,
    variance_threshold: f64,
    min_gutter_height: u32,
) -> Vec<(u32, u32)> {
    let mut gutters = Vec::new();
    let mut gutter_start: Option<u32> = None;

    for y in 0..height {
        let var = row_variance(gray, y, width);
        if var < variance_threshold {
            if gutter_start.is_none() {
                gutter_start = Some(y);
            }
        } else {
            if let Some(start) = gutter_start {
                let run_len = y - start;
                if run_len >= min_gutter_height {
                    gutters.push((start, y));
                }
                gutter_start = None;
            }
        }
    }
    // Handle gutter at bottom edge
    if let Some(start) = gutter_start {
        let run_len = height - start;
        if run_len >= min_gutter_height {
            gutters.push((start, height));
        }
    }

    gutters
}

/// Find vertical gutters within a horizontal strip of the image.
///
/// Scans columns from x=0 to x=width within rows [y_start, y_end).
/// Returns a list of (start_x, end_x) pairs for each gutter.
fn find_vertical_gutters(
    gray: &GrayImage,
    y_start: u32,
    y_end: u32,
    width: u32,
    variance_threshold: f64,
    min_gutter_width: u32,
) -> Vec<(u32, u32)> {
    let mut gutters = Vec::new();
    let mut gutter_start: Option<u32> = None;

    let strip_height = y_end - y_start;
    if strip_height == 0 {
        return gutters;
    }

    for x in 0..width {
        let var = col_variance_range(gray, x, y_start, y_end);
        if var < variance_threshold {
            if gutter_start.is_none() {
                gutter_start = Some(x);
            }
        } else {
            if let Some(start) = gutter_start {
                let run_len = x - start;
                if run_len >= min_gutter_width {
                    gutters.push((start, x));
                }
                gutter_start = None;
            }
        }
    }
    // Handle gutter at right edge
    if let Some(start) = gutter_start {
        let run_len = width - start;
        if run_len >= min_gutter_width {
            gutters.push((start, width));
        }
    }

    gutters
}

/// Calculate pixel variance of a column within a row range [y_start, y_end).
fn col_variance_range(gray: &GrayImage, x: u32, y_start: u32, y_end: u32) -> f64 {
    let n = (y_end - y_start) as f64;
    if n <= 0.0 {
        return 0.0;
    }
    let mut sum: f64 = 0.0;
    let mut sum_sq: f64 = 0.0;
    for y in y_start..y_end {
        let v = gray.get_pixel(x, y).0[0] as f64;
        sum += v;
        sum_sq += v * v;
    }
    let mean = sum / n;
    (sum_sq / n) - (mean * mean)
}

/// Convert a list of gutter intervals into content strip intervals.
///
/// Given gutters within [0, total_size), returns the content regions
/// between them. Gutters at the very edges are treated as borders
/// (content starts after them, ends before them).
fn strips_from_gutters(gutters: &[(u32, u32)], total_size: u32) -> Vec<(u32, u32)> {
    if gutters.is_empty() {
        return vec![(0, total_size)];
    }

    let mut strips = Vec::new();
    let mut pos = 0u32;

    for &(g_start, g_end) in gutters {
        if g_start > pos {
            strips.push((pos, g_start));
        }
        pos = g_end;
    }

    // Content after the last gutter
    if pos < total_size {
        strips.push((pos, total_size));
    }

    strips
}

/// Detect panels for each processed page image.
///
/// Returns a Vec parallel to `pages`, where each element is either
/// Some(panels) if panels were detected, or None for full-page splash pages.
fn detect_panels_for_pages(pages: &[ProcessedImage]) -> Vec<Option<Vec<PanelRect>>> {
    pages
        .par_iter()
        .map(|page| {
            let img = image::load_from_memory(&page.jpeg_data).ok()?;
            let panels = detect_panels(&img);
            if panels.is_empty() {
                None
            } else {
                Some(panels)
            }
        })
        .collect()
}

// ---------------------------------------------------------------------------
// ComicInfo.xml parsing
// ---------------------------------------------------------------------------

/// Find and parse ComicInfo.xml from the input source.
fn find_and_parse_comic_info(
    input: &Path,
    cbz_temp_dir: Option<&Path>,
) -> Option<ComicMetadata> {
    // Check in CBZ extraction directory first
    if let Some(temp_dir) = cbz_temp_dir {
        let path = temp_dir.join("ComicInfo.xml");
        if path.exists() {
            return parse_comic_info(&path).ok();
        }
        // Also check case-insensitive
        if let Ok(entries) = fs::read_dir(temp_dir) {
            for entry in entries.flatten() {
                let name = entry.file_name().to_string_lossy().to_lowercase();
                if name == "comicinfo.xml" {
                    return parse_comic_info(&entry.path()).ok();
                }
            }
        }
    }

    // Check in input directory
    if input.is_dir() {
        let path = input.join("ComicInfo.xml");
        if path.exists() {
            return parse_comic_info(&path).ok();
        }
        // Case-insensitive search
        if let Ok(entries) = fs::read_dir(input) {
            for entry in entries.flatten() {
                let name = entry.file_name().to_string_lossy().to_lowercase();
                if name == "comicinfo.xml" {
                    return parse_comic_info(&entry.path()).ok();
                }
            }
        }
    }

    None
}

/// Parse a ComicInfo.xml file into ComicMetadata.
pub fn parse_comic_info(path: &Path) -> Result<ComicMetadata, Box<dyn std::error::Error>> {
    let content = fs::read_to_string(path)?;
    parse_comic_info_xml(&content)
}

/// Parse ComicInfo.xml content string into ComicMetadata.
pub fn parse_comic_info_xml(xml: &str) -> Result<ComicMetadata, Box<dyn std::error::Error>> {
    use quick_xml::events::Event;
    use quick_xml::Reader;

    let mut reader = Reader::from_str(xml);
    let mut metadata = ComicMetadata::default();
    let mut current_tag = String::new();
    let mut buf = Vec::new();

    loop {
        match reader.read_event_into(&mut buf) {
            Ok(Event::Start(ref e)) => {
                current_tag = String::from_utf8_lossy(e.name().as_ref()).to_string();
            }
            Ok(Event::Text(ref e)) => {
                let text = e.unescape().unwrap_or_default().to_string();
                let text = text.trim().to_string();
                if text.is_empty() {
                    continue;
                }
                // ComicInfo.xml is nominally PascalCase but real-world files
                // from ComicTagger, Kavita, Kileko-Empire, etc. are inconsistent,
                // so match case-insensitively.
                match current_tag.to_ascii_lowercase().as_str() {
                    "title" => metadata.title = Some(text),
                    "series" => metadata.series = Some(text),
                    "number" => metadata.number = Some(text),
                    "writer" => {
                        // May contain comma-separated names
                        for name in text.split(',') {
                            let name = name.trim().to_string();
                            if !name.is_empty() {
                                metadata.writers.push(name);
                            }
                        }
                    }
                    "penciller" => {
                        for name in text.split(',') {
                            let name = name.trim().to_string();
                            if !name.is_empty() {
                                metadata.pencillers.push(name);
                            }
                        }
                    }
                    "inker" => {
                        for name in text.split(',') {
                            let name = name.trim().to_string();
                            if !name.is_empty() {
                                metadata.inkers.push(name);
                            }
                        }
                    }
                    "summary" => metadata.summary = Some(text),
                    "manga" => {
                        if text.eq_ignore_ascii_case("YesAndRightToLeft")
                            || text.eq_ignore_ascii_case("Yes")
                        {
                            metadata.manga_rtl = true;
                        }
                    }
                    "languageiso" => metadata.language = Some(text),
                    "year" => metadata.year = Some(text),
                    "month" => metadata.month = Some(text),
                    _ => {}
                }
            }
            Ok(Event::End(_)) => {
                current_tag.clear();
            }
            Ok(Event::Eof) => break,
            Err(e) => {
                eprintln!("Warning: error parsing ComicInfo.xml: {}", e);
                break;
            }
            _ => {}
        }
        buf.clear();
    }

    if metadata.title.is_some() || metadata.series.is_some() {
        eprintln!("Parsed ComicInfo.xml: {}", metadata.effective_title().unwrap_or_default());
    }
    if metadata.manga_rtl {
        eprintln!("ComicInfo.xml specifies manga (RTL) reading direction");
    }

    Ok(metadata)
}

/// Create a temporary directory for the fixed-layout EPUB content.
fn create_temp_dir(output: &Path) -> Result<PathBuf, Box<dyn std::error::Error>> {
    let stem = output.file_stem().unwrap_or_default().to_string_lossy();
    let parent = output.parent().unwrap_or(Path::new("."));
    let temp_dir = parent.join(format!(".kindling_comic_{}", stem));

    if temp_dir.exists() {
        fs::remove_dir_all(&temp_dir)?;
    }
    fs::create_dir_all(&temp_dir)?;

    Ok(temp_dir)
}

/// Write a fixed-layout EPUB structure to a temp directory.
///
/// Supports RTL page progression, ComicInfo.xml metadata, and Panel View markup.
fn write_fixed_layout_epub_v2(
    temp_dir: &Path,
    pages: &[ProcessedImage],
    profile: &DeviceProfile,
    rtl: bool,
    metadata: Option<&ComicMetadata>,
    panel_view: bool,
    options: &ComicOptions,
) -> Result<PathBuf, Box<dyn std::error::Error>> {
    let images_dir = temp_dir.join("images");
    fs::create_dir_all(&images_dir)?;

    // Write image files
    for page in pages {
        let filename = format!("page_{:04}.jpg", page.index);
        fs::write(images_dir.join(&filename), &page.jpeg_data)?;
    }

    // Check if any page actually has panel data
    let any_panels = panel_view && pages.iter().any(|p| p.panels.is_some());

    // Write XHTML pages
    for page in pages {
        let xhtml = build_page_xhtml(page.index, page.width, page.height, page.panels.as_deref(), options.kindlegen_parity);
        let filename = format!("page_{:04}.xhtml", page.index);
        fs::write(temp_dir.join(&filename), xhtml.as_bytes())?;
    }
    // CSS for KF8 fixed-layout rendering (kindle:flow:0001).
    let css = "@page {\nmargin: 0;\n}\nbody {\ndisplay: block;\nmargin: 0;\npadding: 0;\n}\n";
    fs::write(temp_dir.join("comic.css"), css.as_bytes())?;

    // Handle external cover image if provided
    let external_cover_id = if let Some(CoverSource::FilePath(ref path)) = options.cover {
        let cover_filename = "cover_override.jpg";
        let cover_data = fs::read(path).map_err(|e| {
            format!("Could not read cover image {}: {}", path.display(), e)
        })?;
        // Re-encode cover image as JPEG to ensure Kindle compatibility
        let cover_img = image::load_from_memory(&cover_data).map_err(|e| {
            format!("Could not decode cover image {}: {}", path.display(), e)
        })?;
        let cover_img = if options.cover_fill {
            cover_fill_crop(&cover_img, profile.width, profile.height)
        } else {
            cover_img
        };
        let cover_resized = cover_img.resize(profile.width, profile.height, FilterType::Lanczos3);
        let cover_jpeg = encode_jpeg(&cover_resized, options.jpeg_quality)?;
        fs::write(images_dir.join(cover_filename), &cover_jpeg)?;
        Some(cover_filename.to_string())
    } else {
        None
    };

    let uid = format!(
        "kindling-comic-{}",
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs()
    );

    // Write OPF
    let opf = build_comic_opf_v2(pages.len(), profile, rtl, metadata, any_panels, options, external_cover_id.as_deref(), &uid);
    let opf_path = temp_dir.join("content.opf");
    fs::write(&opf_path, opf.as_bytes())?;

    // Write NCX
    let ncx = build_comic_ncx(pages.len(), &uid);
    fs::write(temp_dir.join("toc.ncx"), ncx.as_bytes())?;

    Ok(opf_path)
}

/// Build the OPF manifest for the comic.
fn build_comic_opf_v2(
    num_pages: usize,
    profile: &DeviceProfile,
    rtl: bool,
    metadata: Option<&ComicMetadata>,
    panel_view: bool,
    options: &ComicOptions,
    external_cover_filename: Option<&str>,
    uid: &str,
) -> String {
    let mut manifest_items = String::new();
    let mut spine_items = String::new();

    // NCX + CSS
    manifest_items.push_str("    <item id=\"ncx\" href=\"toc.ncx\" media-type=\"application/x-dtbncx+xml\"/>\n");
    manifest_items.push_str("    <item id=\"css\" href=\"comic.css\" media-type=\"text/css\"/>\n");

    for i in 0..num_pages {
        manifest_items.push_str(&format!(
            "    <item id=\"page{:04}\" href=\"page_{:04}.xhtml\" media-type=\"application/xhtml+xml\"/>\n",
            i, i
        ));
        manifest_items.push_str(&format!(
            "    <item id=\"img{:04}\" href=\"images/page_{:04}.jpg\" media-type=\"image/jpeg\"/>\n",
            i, i
        ));
        spine_items.push_str(&format!(
            "    <itemref idref=\"page{:04}\"/>\n",
            i
        ));
    }

    // Handle cover: external file, page number override, or default (first page)
    let (cover_meta, cover_manifest_entry) = if let Some(ref cover_filename) = external_cover_filename {
        // External cover image file
        let entry = format!(
            "    <item id=\"cover_img\" href=\"images/{}\" media-type=\"image/jpeg\"/>\n",
            cover_filename
        );
        ("  <meta name=\"cover\" content=\"cover_img\"/>\n".to_string(), entry)
    } else if let Some(CoverSource::PageNumber(page_num)) = options.cover {
        // 1-based page number
        let idx = page_num.saturating_sub(1);
        if idx < num_pages {
            (format!("  <meta name=\"cover\" content=\"img{:04}\"/>\n", idx), String::new())
        } else {
            eprintln!("Warning: cover page {} exceeds page count {}, using first page", page_num, num_pages);
            if num_pages > 0 {
                ("  <meta name=\"cover\" content=\"img0000\"/>\n".to_string(), String::new())
            } else {
                (String::new(), String::new())
            }
        }
    } else if num_pages > 0 {
        ("  <meta name=\"cover\" content=\"img0000\"/>\n".to_string(), String::new())
    } else {
        (String::new(), String::new())
    };

    // Determine title: CLI override > ComicInfo.xml > fallback
    let title = if let Some(ref t) = options.title_override {
        t.clone()
    } else {
        metadata
            .and_then(|m| m.effective_title())
            .unwrap_or_else(|| "Comic".to_string())
    };

    // Determine creators: CLI override > ComicInfo.xml > DEFAULT_AUTHOR.
    // All creators are joined into a single <dc:creator> entry because the
    // OPF parser used downstream keeps only one creator, so multiple tags
    // would silently drop all but the last name (which is how EXTH 100 lost
    // the Vader Down writers in v0.7.4). A fallback author is critical:
    // Kindle silently refuses to index books with no author, so an empty
    // EXTH 100 is a library-invisibility bug.
    let mut creator_entries = String::new();
    let creator_value: String = if let Some(ref author) = options.author_override {
        author.clone()
    } else if let Some(meta) = metadata {
        let creators = meta.creators();
        if creators.is_empty() {
            DEFAULT_AUTHOR.to_string()
        } else {
            creators.join(", ")
        }
    } else {
        DEFAULT_AUTHOR.to_string()
    };
    creator_entries.push_str(&format!(
        "    <dc:creator>{}</dc:creator>\n",
        escape_xml(&creator_value)
    ));

    // Determine language: CLI override > ComicInfo.xml > default "en"
    let language = options
        .language
        .as_deref()
        .or_else(|| metadata.and_then(|m| m.language.as_deref()))
        .unwrap_or("en");

    // Determine description
    let mut description_entry = String::new();
    if let Some(meta) = metadata {
        if let Some(ref summary) = meta.summary {
            description_entry = format!(
                "    <dc:description>{}</dc:description>\n",
                escape_xml(summary)
            );
        }
    }

    // Page progression direction
    let ppd = if rtl { "rtl" } else { "ltr" };

    // Writing mode meta for RTL
    let writing_mode_meta = if rtl {
        "    <meta name=\"writing-mode\" content=\"horizontal-rl\"/>\n"
    } else {
        ""
    };

    // Panel View metadata
    let panel_view_meta = if panel_view {
        "    <meta name=\"book-type\" content=\"comic\"/>\n    <meta name=\"region-mag\" content=\"true\"/>\n"
    } else {
        ""
    };

    format!(
        r#"<?xml version="1.0" encoding="UTF-8"?>
<package version="3.0" xmlns="http://www.idpf.org/2007/opf" unique-identifier="uid">
  <metadata xmlns:dc="http://purl.org/dc/elements/1.1/">
    <dc:title>{title}</dc:title>
    <dc:language>{language}</dc:language>
    <dc:identifier id="uid">{uid}</dc:identifier>
{creator_entries}{description_entry}    <meta name="fixed-layout" content="true"/>
    <meta name="original-resolution" content="{width}x{height}"/>
    <meta property="rendition:layout">pre-paginated</meta>
    <meta property="rendition:orientation">auto</meta>
{writing_mode_meta}{panel_view_meta}{cover_meta}  </metadata>
  <manifest>
{cover_manifest_entry}{manifest_items}  </manifest>
  <spine toc="ncx" page-progression-direction="{ppd}">
{spine_items}  </spine>
</package>
"#,
        title = escape_xml(&title),
        language = escape_xml(language),
        uid = uid,
        width = profile.width,
        height = profile.height,
        cover_meta = cover_meta,
        cover_manifest_entry = cover_manifest_entry,
        creator_entries = creator_entries,
        description_entry = description_entry,
        manifest_items = manifest_items,
        spine_items = spine_items,
        ppd = ppd,
        writing_mode_meta = writing_mode_meta,
        panel_view_meta = panel_view_meta,
    )
}

/// Escape special XML characters.
fn escape_xml(s: &str) -> String {
    s.replace('&', "&amp;")
     .replace('<', "&lt;")
     .replace('>', "&gt;")
     .replace('"', "&quot;")
     .replace('\'', "&apos;")
}

/// Build an XHTML page for a single comic page, with optional Panel View markup.
///
/// Two shapes:
///
/// - Default ("better than kindlegen"): pretty-printed, XHTML 5-ish
///   with DOCTYPE + meta charset, inline container box-model styles on
///   body/div, `style="width:100%;height:100%;object-fit:contain"` on
///   the img so it scales to the canvas on any Kindle regardless of
///   the actual JPEG pixel dimensions, and "Page N" capitalized alt.
///
/// - kindlegen-parity: single-line, no DOCTYPE, no meta charset, flat
///   body/div without inline styles, img with `width="W" height="H"`
///   pixel attributes at the device-profile resolution, "page N"
///   lowercase alt. Matches kindlegen's KF8 comic output byte-for-byte
///   except for genuinely unavoidable deltas (compression seeds etc).
fn build_page_xhtml(
    page_index: usize,
    img_width: u32,
    img_height: u32,
    panels: Option<&[PanelRect]>,
    kindlegen_parity: bool,
) -> String {
    if kindlegen_parity {
        let panel_divs = match panels {
            Some(rects) if !rects.is_empty() => {
                let mut divs = String::new();
                divs.push_str(r#"<div id="panels" style="position:absolute;top:0;left:0;width:100%;height:100%">"#);
                for rect in rects {
                    divs.push_str(&format!(
                        r#"<div class="panel" style="position:absolute;left:{x:.1}%;top:{y:.1}%;width:{w:.1}%;height:{h:.1}%"></div>"#,
                        x = rect.x,
                        y = rect.y,
                        w = rect.w,
                        h = rect.h,
                    ));
                }
                divs.push_str("</div>");
                divs
            }
            _ => String::new(),
        };
        return format!(
            r#"<?xml version="1.0" encoding="UTF-8"?><html xmlns="http://www.w3.org/1999/xhtml"><head><title>Page {page_num}</title></head><body><div><img src="images/page_{index:04}.jpg" alt="page {page_num}" width="{w}" height="{h}"/></div>{panel_divs}</body></html>"#,
            page_num = page_index + 1,
            index = page_index,
            w = img_width,
            h = img_height,
            panel_divs = panel_divs,
        );
    }

    // Default ("better than kindlegen") template.
    let panel_divs = match panels {
        Some(rects) if !rects.is_empty() => {
            let mut divs = String::new();
            divs.push_str("  <div id=\"panels\" style=\"position:absolute;top:0;left:0;width:100%;height:100%\">\n");
            for rect in rects {
                divs.push_str(&format!(
                    "    <div class=\"panel\" style=\"position:absolute;left:{x:.1}%;top:{y:.1}%;width:{w:.1}%;height:{h:.1}%\"></div>\n",
                    x = rect.x,
                    y = rect.y,
                    w = rect.w,
                    h = rect.h,
                ));
            }
            divs.push_str("  </div>\n");
            divs
        }
        _ => String::new(),
    };

    // Fixed-layout template matching kindlegen's structure.
    // Viewport and img dimensions use ACTUAL image size (not device profile),
    // matching KCC's behavior. Using device profile dimensions causes cropping
    // when image aspect ratio differs from screen.
    format!(
        r#"<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head>
<title>Page {page_num}</title>
<link href="kindle:flow:0001?mime=text/css" type="text/css" rel="stylesheet"/>
<meta name="viewport" content="width={w}, height={h}"/>
</head><body style="background-color:#000000;">
<div style="text-align:center;">
<img width="{w}" height="{h}" src="images/page_{index:04}.jpg"/>
</div>
{panel_divs}</body></html>
"#,
        page_num = page_index + 1,
        index = page_index,
        w = img_width,
        h = img_height,
        panel_divs = panel_divs,
    )
}

/// Build a minimal NCX table of contents.
fn build_comic_ncx(num_pages: usize, uid: &str) -> String {
    let mut nav_points = String::new();
    for i in 0..num_pages {
        nav_points.push_str(&format!(
            r#"    <navPoint id="page{index:04}" playOrder="{order}">
      <navLabel><text>Page {page_num}</text></navLabel>
      <content src="page_{index:04}.xhtml"/>
    </navPoint>
"#,
            index = i,
            order = i + 1,
            page_num = i + 1,
        ));
    }

    format!(
        r#"<?xml version="1.0" encoding="UTF-8"?>
<ncx xmlns="http://www.daisy.org/z3986/2005/ncx/" version="2005-1">
  <head>
    <meta name="dtb:uid" content="{uid}"/>
    <meta name="dtb:depth" content="1"/>
    <meta name="dtb:totalPageCount" content="{num_pages}"/>
    <meta name="dtb:maxPageNumber" content="{num_pages}"/>
  </head>
  <docTitle><text>Comic</text></docTitle>
  <navMap>
{nav_points}  </navMap>
</ncx>
"#,
        num_pages = num_pages,
        nav_points = nav_points,
        uid = uid,
    )
}

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

    #[test]
    fn test_parse_comic_info_lowercase_tags() {
        // Regression: ComicInfo.xml from Kileko-Empire (Vader Down CBZ) uses
        // lowercase `<writer>` which was being dropped by the case-sensitive
        // parser, so the author never made it into EXTH 100 and the book
        // failed to index on Kindle.
        let xml = r#"<?xml version='1.0' encoding='utf-8'?>
<ComicInfo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <Series>Star Wars: Darth Vader Modern Era Epic Collection: Vader Down</Series>
    <LanguageISO>en</LanguageISO>
    <PageCount>407</PageCount>
    <writer>Kieron Gillen, Jason Aaron</writer>
    <Month>11</Month>
    <Year>2025</Year>
</ComicInfo>"#;
        let meta = parse_comic_info_xml(xml).expect("parse should succeed");
        assert_eq!(
            meta.series.as_deref(),
            Some("Star Wars: Darth Vader Modern Era Epic Collection: Vader Down"),
            "Series should be parsed from mixed-case tag"
        );
        assert!(
            meta.writers.iter().any(|w| w == "Kieron Gillen"),
            "Writers should include Kieron Gillen, got {:?}",
            meta.writers,
        );
        assert!(
            meta.writers.iter().any(|w| w == "Jason Aaron"),
            "Writers should include Jason Aaron, got {:?}",
            meta.writers,
        );
        assert_eq!(meta.language.as_deref(), Some("en"));
        assert_eq!(meta.year.as_deref(), Some("2025"));
        assert_eq!(meta.month.as_deref(), Some("11"));
    }

    #[test]
    fn test_parse_comic_info_manga_case_insensitive() {
        let xml = r#"<?xml version='1.0' encoding='utf-8'?>
<ComicInfo>
    <manga>yesandrighttoleft</manga>
</ComicInfo>"#;
        let meta = parse_comic_info_xml(xml).expect("parse should succeed");
        assert!(meta.manga_rtl, "manga RTL should be detected case-insensitively");
    }

    #[test]
    fn test_comic_opf_passes_validate() {
        // Write a minimal comic OPF to disk and confirm the KDP validator
        // accepts it. This guards against a regression where an OPF-level
        // problem (missing cover manifest entry, bad manifest reference,
        // etc.) would be introduced by the comic writer and only caught
        // by real Kindle devices, since the comic build path used to
        // skip validation entirely.
        let dir = std::env::temp_dir().join("kindling_comic_validate_test");
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();

        // Minimal 1x1 JPEG.
        let jpeg: Vec<u8> = vec![
            0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x10, 0x4A, 0x46, 0x49, 0x46, 0x00, 0x01,
            0x01, 0x01, 0x00, 0x48, 0x00, 0x48, 0x00, 0x00, 0xFF, 0xDB, 0x00, 0x43,
            0x00, 0x08, 0x06, 0x06, 0x07, 0x06, 0x05, 0x08, 0x07, 0x07, 0x07, 0x09,
            0x09, 0x08, 0x0A, 0x0C, 0x14, 0x0D, 0x0C, 0x0B, 0x0B, 0x0C, 0x19, 0x12,
            0x13, 0x0F, 0x14, 0x1D, 0x1A, 0x1F, 0x1E, 0x1D, 0x1A, 0x1C, 0x1C, 0x20,
            0x24, 0x2E, 0x27, 0x20, 0x22, 0x2C, 0x23, 0x1C, 0x1C, 0x28, 0x37, 0x29,
            0x2C, 0x30, 0x31, 0x34, 0x34, 0x34, 0x1F, 0x27, 0x39, 0x3D, 0x38, 0x32,
            0x3C, 0x2E, 0x33, 0x34, 0x32, 0xFF, 0xC0, 0x00, 0x0B, 0x08, 0x00, 0x01,
            0x00, 0x01, 0x01, 0x01, 0x11, 0x00, 0xFF, 0xC4, 0x00, 0x1F, 0x00, 0x00,
            0x01, 0x05, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
            0x09, 0x0A, 0x0B, 0xFF, 0xC4, 0x00, 0xB5, 0x10, 0x00, 0x02, 0x01, 0x03,
            0x03, 0x02, 0x04, 0x03, 0x05, 0x05, 0x04, 0x04, 0x00, 0x00, 0x01, 0x7D,
            0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12, 0x21, 0x31, 0x41, 0x06,
            0x13, 0x51, 0x61, 0x07, 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xA1, 0x08,
            0x23, 0x42, 0xB1, 0xC1, 0x15, 0x52, 0xD1, 0xF0, 0x24, 0x33, 0x62, 0x72,
            0x82, 0xFF, 0xDA, 0x00, 0x08, 0x01, 0x01, 0x00, 0x00, 0x3F, 0x00, 0xFB,
            0xD0, 0xFF, 0xD9,
        ];
        std::fs::write(dir.join("cover.jpg"), &jpeg).unwrap();
        std::fs::write(
            dir.join("page.xhtml"),
            r#"<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"><head><title>P</title>
<meta name="viewport" content="width=1072, height=1448"/></head>
<body><div><img src="cover.jpg" alt="p"/></div></body></html>"#,
        )
        .unwrap();

        let opf = r#"<?xml version="1.0" encoding="UTF-8"?>
<package version="3.0" xmlns="http://www.idpf.org/2007/opf" unique-identifier="uid">
  <metadata xmlns:dc="http://purl.org/dc/elements/1.1/">
    <dc:title>Test Comic</dc:title>
    <dc:language>en</dc:language>
    <dc:identifier id="uid">kindling-comic-test</dc:identifier>
    <dc:creator>Unknown</dc:creator>
    <meta name="fixed-layout" content="true"/>
    <meta name="original-resolution" content="1072x1448"/>
    <meta name="cover" content="cover-img"/>
  </metadata>
  <manifest>
    <item id="cover-img" href="cover.jpg" media-type="image/jpeg"/>
    <item id="page1" href="page.xhtml" media-type="application/xhtml+xml"/>
  </manifest>
  <spine>
    <itemref idref="page1"/>
  </spine>
</package>
"#;
        let opf_path = dir.join("content.opf");
        std::fs::write(&opf_path, opf).unwrap();

        let report = crate::validate::validate_opf(&opf_path)
            .expect("validate should parse the OPF");
        assert_eq!(
            report.error_count(),
            0,
            "comic OPF should have 0 errors, got: {:?}",
            report.findings,
        );

        let _ = std::fs::remove_dir_all(&dir);
    }
}