stet-graphics 0.2.1

Display list, ICC color, and graphics types shared by stet's PostScript interpreter and PDF reader
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
// stet - A PostScript Interpreter
// Copyright (c) 2026 Scott Bowman
// SPDX-License-Identifier: Apache-2.0 OR MIT

//! ICC color profile support via moxcms.
//!
//! Parses embedded ICC profiles from `[/ICCBased stream]` color spaces and
//! converts colors to sRGB. Also searches for system CMYK profiles to improve
//! DeviceCMYK → RGB conversion beyond the naive PLRM formula.

pub mod bpc;
mod perceptual;

use bpc::{
    BpcParams, apply_bpc_f64, apply_bpc_rgb_u8, compute_bpc_params, detect_source_black_point,
};
use moxcms::{
    CmsError, ColorProfile, DataColorSpace, Layout, RenderingIntent, TransformExecutor,
    TransformOptions,
};
use std::collections::HashMap;
use std::sync::Arc;

/// Re-export so callers in `stet-pdf-reader` (and other consumers
/// without a direct moxcms dependency) can specify the rendering intent
/// for [`IccCache::convert_color_with_intent`] etc. without taking a
/// moxcms dep themselves.
pub use moxcms::RenderingIntent as IccRenderingIntent;

/// Map a PDF gstate `rendering_intent` byte (0=Perceptual, 1=RelCol,
/// 2=Saturation, 3=AbsCol — the encoding used by
/// `stet-pdf-reader::content::graphics_state::PdfGraphicsState`) to the
/// corresponding [`IccRenderingIntent`]. Unknown values fall back to
/// Perceptual, matching the PDF spec's default.
#[inline]
pub fn intent_from_pdf_byte(b: u8) -> IccRenderingIntent {
    match b {
        1 => IccRenderingIntent::RelativeColorimetric,
        2 => IccRenderingIntent::Saturation,
        3 => IccRenderingIntent::AbsoluteColorimetric,
        _ => IccRenderingIntent::Perceptual,
    }
}

/// SHA-256 hash used as profile key.
pub type ProfileHash = [u8; 32];

/// Cache key for per-intent single-colour lookups: `(hash-prefix,
/// quantized_components, intent_byte)`.
type IntentColorKey = (u64, [u16; 4], u8);

/// Black Point Compensation mode for CMYK→sRGB conversion.
///
/// Reference renderers (Ghostscript, Acrobat, Firefox via lcms2) apply BPC by
/// default for relative-colorimetric CMYK→sRGB. moxcms 0.8.1 ships BPC
/// commented out, so without it K-heavy colors render visibly lighter than
/// reference renderers. See `docs/PLAN-BPC.md` for the full design.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum BpcMode {
    /// Skip BPC; matches stet's pre-fix behavior. Useful for proofing-style
    /// renders that should preserve actual densities, or for bit-for-bit
    /// reproduction of older baselines.
    Off,
    /// Always apply BPC during CMYK→sRGB conversion.
    On,
    /// Default — currently equivalent to `On`. Reserved for forward
    /// compatibility (eventually could honor PDF rendering-intent or
    /// output-intent hints).
    #[default]
    Auto,
}

impl BpcMode {
    /// True when BPC should be applied at conversion time.
    #[inline]
    pub fn is_enabled(self) -> bool {
        matches!(self, BpcMode::On | BpcMode::Auto)
    }
}

/// Construction-time options for [`IccCache`].
///
/// Bundles together the BPC mode and an optional pre-supplied source CMYK
/// profile (overriding the automatic system-profile search). Created via
/// [`IccCache::new_with_options`].
#[derive(Clone, Default)]
pub struct IccCacheOptions {
    /// BPC mode for CMYK→sRGB conversion.
    pub bpc_mode: BpcMode,
    /// Raw bytes of a source CMYK profile to register as the system profile.
    /// When `None`, the cache is created empty and the caller is responsible
    /// for invoking [`IccCache::search_system_cmyk_profile`] (or providing
    /// bytes some other way).
    pub source_cmyk_profile: Option<Vec<u8>>,
}

/// Identity Gray→RGB transform: maps each gray value to equal R=G=B.
/// Used as fallback when a Gray ICC profile can't produce a proper transform.
struct GrayToRgbIdentity;

impl TransformExecutor<u8> for GrayToRgbIdentity {
    fn transform(&self, src: &[u8], dst: &mut [u8]) -> Result<(), CmsError> {
        for (g, rgb) in src.iter().zip(dst.chunks_exact_mut(3)) {
            rgb[0] = *g;
            rgb[1] = *g;
            rgb[2] = *g;
        }
        Ok(())
    }
}

impl TransformExecutor<f64> for GrayToRgbIdentity {
    fn transform(&self, src: &[f64], dst: &mut [f64]) -> Result<(), CmsError> {
        for (g, rgb) in src.iter().zip(dst.chunks_exact_mut(3)) {
            rgb[0] = *g;
            rgb[1] = *g;
            rgb[2] = *g;
        }
        Ok(())
    }
}

/// `TransformExecutor` adapter that resolves CMYK → sRGB through an existing
/// `Clut4`. Used as stage 2 of the proofing chain so the chain output goes
/// through the same hand-rolled colorimetric path as direct DeviceCMYK
/// conversion, avoiding the moxcms over-saturation cited in
/// `perceptual.rs`.
struct Clut4ToRgb {
    clut4: Clut4,
}

impl TransformExecutor<u8> for Clut4ToRgb {
    fn transform(&self, src: &[u8], dst: &mut [u8]) -> Result<(), CmsError> {
        let pixel_count = dst.len() / 3;
        let rgb = apply_clut4_cmyk_to_rgb(&self.clut4, src, pixel_count);
        dst[..rgb.len()].copy_from_slice(&rgb);
        Ok(())
    }
}

impl TransformExecutor<f64> for Clut4ToRgb {
    fn transform(&self, src: &[f64], dst: &mut [f64]) -> Result<(), CmsError> {
        let pixel_count = dst.len() / 3;
        for px in 0..pixel_count {
            let c = src[px * 4];
            let m = src[px * 4 + 1];
            let y = src[px * 4 + 2];
            let k = src[px * 4 + 3];
            let (r, g, b) = sample_clut4_single_f64(&self.clut4, c, m, y, k);
            dst[px * 3] = r;
            dst[px * 3 + 1] = g;
            dst[px * 3 + 2] = b;
        }
        Ok(())
    }
}

/// Two-stage proofing transform: `source → intermediate (OutputIntent) → sRGB`.
///
/// PDF/X workflows specify a target device via `/OutputIntents`. Source
/// colours (DeviceCMYK, ICCBased CMYK/RGB/Gray, etc.) are color-managed
/// through that target before reaching the simulated display, so every
/// source space converges through the same final `OutputIntent → sRGB`
/// stage and a CMYK swatch designed to match a DeviceCMYK background
/// renders identically to it.
///
/// `intermediate_n` is the number of components in the OutputIntent's
/// colour space (typically 4 for CMYK). The intermediate buffer is sized
/// per `transform()` call from the destination pixel count.
struct ChainedTransform<T: Copy + Default + Send + Sync + 'static> {
    /// First leg: `source → OutputIntent`.
    stage1: Arc<dyn TransformExecutor<T> + Send + Sync>,
    /// Second leg: `OutputIntent → sRGB`. Reused from the OutputIntent
    /// profile's own cached transform so byte-identical output is
    /// produced for direct DeviceCMYK paints and the proofing chain.
    stage2: Arc<dyn TransformExecutor<T> + Send + Sync>,
    /// Number of components in the intermediate (OutputIntent) layout.
    intermediate_n: usize,
}

impl<T: Copy + Default + Send + Sync + 'static> TransformExecutor<T> for ChainedTransform<T> {
    fn transform(&self, src: &[T], dst: &mut [T]) -> Result<(), CmsError> {
        // Destination is always packed sRGB (3 components). Derive pixel
        // count from `dst.len()` so we don't have to know the source
        // component count here.
        let pixel_count = dst.len() / 3;
        let mid_len = pixel_count * self.intermediate_n;
        let mut mid = vec![T::default(); mid_len];
        self.stage1.transform(src, &mut mid)?;
        self.stage2.transform(&mid, dst)
    }
}

/// Pre-baked 4D CLUT sampling a CMYK ICC transform on a regular grid.
///
/// At profile-registration time we sample moxcms at `grid_n^4` evenly-spaced
/// CMYK points and store the sRGB output. At image-conversion time we do
/// K-slice plus 3D tetrahedral interpolation inside each slice. This is ~30×
/// faster than direct moxcms for LUT-based CMYK profiles (e.g., SWOP) while
/// staying well inside imperceptible ΔE for typical print-workflow inputs.
#[derive(Clone)]
struct Clut4 {
    /// Grid points per axis (typical: 17).
    grid_n: u8,
    /// Flat LUT in order (k, y, m, c) with C fastest, K slowest.
    /// Length = grid_n^4 * 3 bytes (packed sRGB).
    data: Arc<Vec<u8>>,
}

impl Clut4 {
    /// Construct a Clut4 from a pre-baked byte buffer with the same memory
    /// layout `bake_clut4` produces (K outermost, Y, M, C innermost; 3 bytes
    /// per grid point). Used by [`perceptual::bake_clut4_perceptual`] so its
    /// output is byte-compatible with [`apply_clut4_cmyk_to_rgb`].
    fn from_baked(grid_n: u8, data: Vec<u8>) -> Self {
        debug_assert_eq!(data.len(), (grid_n as usize).pow(4) * 3);
        Self {
            grid_n,
            data: Arc::new(data),
        }
    }
}

/// Cached ICC transform to sRGB (specific to source layout).
#[derive(Clone)]
struct CachedTransform {
    /// 8-bit transform for image data. When proofing is enabled and the
    /// source is RGB, this is the Perceptual-intent chain so existing
    /// callers (no intent plumbing yet) keep producing the GWG 13.0
    /// baseline byte-for-byte.
    transform_8bit: Arc<dyn TransformExecutor<u8> + Send + Sync>,
    /// f64 transform for single-color conversions. Same intent default
    /// as `transform_8bit`.
    transform_f64: Arc<dyn TransformExecutor<f64> + Send + Sync>,
    /// Per-intent proofing chains, indexed by ICC `RenderingIntent`
    /// discriminant: `[Perceptual=0, RelCol=1, Saturation=2, AbsCol=3]`.
    /// Populated only for n=3 RGB sources when proofing is enabled and
    /// the source has a viable A2B / OI B2A pair; `None` slots fall back
    /// to `transform_*bit` / `transform_*_f64` at lookup time. AbsCol
    /// currently shares the RelCol tables (pending step 4 BPC + AbsCol
    /// white-point handling).
    chain_per_intent_8bit: [Option<Arc<dyn TransformExecutor<u8> + Send + Sync>>; 4],
    chain_per_intent_f64: [Option<Arc<dyn TransformExecutor<f64> + Send + Sync>>; 4],
    /// Per-intent stage-1 only sampler (source RGB → OutputIntent CMYK,
    /// without the trailing CMYK→sRGB stage 2). Same indexing as the
    /// `chain_per_intent_*` arrays. Used by
    /// [`IccCache::convert_to_oi_cmyk`] so the PDF reader can record the
    /// chain's intermediate CMYK as `DeviceColor::native_cmyk`, which
    /// in turn lets the renderer's `cmyk_group_blend` gate fire on
    /// ICCBased RGB swatches inside a `/CS DeviceCMYK` page group
    /// (GWG 16.1).
    chain_stage1_per_intent: [Option<Arc<perceptual::HandRolledChainStage1Rgb>>; 4],
    /// Number of source components.
    n: u32,
    /// Whether the source profile is Lab (needs value normalization).
    is_lab: bool,
    /// Pre-baked 4D CLUT for fast CMYK→sRGB image conversion.
    /// Only built for `n == 4` profiles; None otherwise.
    clut4: Option<Clut4>,
    /// Cached Black Point Compensation parameters for this profile. Computed
    /// when `n == 4` and `IccCache::bpc_mode` is enabled. Applied as a
    /// post-correction on the moxcms output (sRGB → XYZ-D50 → BPC shift →
    /// back to sRGB) so K-heavy CMYK colours map to true zero black.
    bpc_params: Option<BpcParams>,
}

/// ICC color profile cache and transform manager.
#[derive(Clone)]
pub struct IccCache {
    /// SHA-256 hash → parsed ColorProfile.
    profiles: HashMap<ProfileHash, Arc<ColorProfile>>,
    /// Cached transforms: hash → CachedTransform.
    transforms: HashMap<ProfileHash, CachedTransform>,
    /// Single-color conversion cache: `(hash-prefix, quantized_components)
    /// → (r, g, b)`. Used by [`Self::convert_color`] (the legacy /
    /// default-Perceptual path). Uses first 8 bytes of hash as u64 key
    /// for compactness.
    color_cache: HashMap<(u64, [u16; 4]), (f64, f64, f64)>,
    /// Per-intent single-color conversion cache: `(hash-prefix,
    /// quantized_components, intent_byte) → (r, g, b)`. Populated by
    /// [`Self::convert_color_with_intent`] for non-Perceptual intents
    /// so step 3's per-intent renderer plumbing can stay cheap when a
    /// page calls the same conversion repeatedly under e.g. Saturation.
    color_cache_intent: HashMap<IntentColorKey, (f64, f64, f64)>,
    /// Default system CMYK profile hash (if found at startup).
    default_cmyk_hash: Option<ProfileHash>,
    /// Raw bytes of the system CMYK profile (for re-registration in render threads).
    system_cmyk_bytes: Option<Arc<Vec<u8>>>,
    /// Raw profile bytes for each registered profile (for PDF embedding).
    raw_bytes: HashMap<ProfileHash, Arc<Vec<u8>>>,
    /// sRGB output profile (created once).
    srgb_profile: ColorProfile,
    /// Cached sRGB→CMYK reverse transform (for RGB round-trip through CMYK page groups).
    reverse_cmyk_f64: Option<Arc<dyn TransformExecutor<f64> + Send + Sync>>,
    /// Black Point Compensation mode for CMYK→sRGB conversion. Set at
    /// construction time via [`IccCacheOptions`]; consulted by future BPC
    /// apply paths (commit 2 of `docs/PLAN-BPC.md`).
    bpc_mode: BpcMode,
    /// Enable PDF/X-style proofing: ICCBased source profiles convert through
    /// the default CMYK profile (the document's OutputIntent) before going
    /// to sRGB, so all source colour spaces converge through the same
    /// `OutputIntent → sRGB` final stage. Set by
    /// `PdfDocument::apply_output_intent_as_default_cmyk` when the PDF has
    /// an `/OutputIntents` entry; left `false` when only the system CMYK
    /// fallback is available, so non-PDF/X documents keep their direct
    /// `source → sRGB` conversion.
    proofing_enabled: bool,
    /// Per-intent Lab → OutputIntent CMYK samplers. Built lazily by
    /// [`Self::prepare_lab_to_oi_cmyk`] from the OI's `B2A*` LUTs so
    /// `convert_lab_to_oi_cmyk` can populate `DeviceColor::native_cmyk`
    /// for Lab fills with a direct `Lab → PCS → OI B2A → CMYK` value
    /// (matching Acrobat's ACE) instead of the sRGB→ICC-reverse approximation
    /// the parallel CMYK buffer would otherwise compute. Surfaced under
    /// CMYK-group blends — GWG 22.1's ColorBurn form over a Lab BG is the
    /// canonical case where the indirect path drifts visibly.
    lab_to_oi_per_intent: [Option<Arc<perceptual::LabToCmykSampler>>; 4],
}

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

/// Apply BPC to an sRGB triple if `params` is `Some`; otherwise return the
/// triple unchanged. Centralised so every conversion entry point stays in
/// sync.
#[inline]
fn bpc_post_correct(rgb: [f64; 3], params: Option<&BpcParams>) -> [f64; 3] {
    match params {
        Some(p) => apply_bpc_f64(rgb, p),
        None => rgb,
    }
}

impl IccCache {
    /// Create an empty ICC cache with default options (BPC `Auto`, no
    /// pre-supplied source CMYK profile).
    pub fn new() -> Self {
        Self::new_with_options(IccCacheOptions::default())
    }

    /// Create an ICC cache with the given options.
    ///
    /// When `opts.source_cmyk_profile` is `Some`, the bytes are registered as
    /// the system CMYK profile (overriding any later
    /// [`Self::search_system_cmyk_profile`] call). Otherwise the cache starts
    /// empty and the caller is expected to supply a profile separately.
    pub fn new_with_options(opts: IccCacheOptions) -> Self {
        let mut cache = Self {
            profiles: HashMap::new(),
            transforms: HashMap::new(),
            color_cache: HashMap::new(),
            color_cache_intent: HashMap::new(),
            default_cmyk_hash: None,
            system_cmyk_bytes: None,
            raw_bytes: HashMap::new(),
            srgb_profile: ColorProfile::new_srgb(),
            reverse_cmyk_f64: None,
            bpc_mode: opts.bpc_mode,
            proofing_enabled: false,
            lab_to_oi_per_intent: [None, None, None, None],
        };
        if let Some(bytes) = opts.source_cmyk_profile {
            cache.load_cmyk_profile_bytes(&bytes);
        }
        cache
    }

    /// Current Black Point Compensation mode.
    #[inline]
    pub fn bpc_mode(&self) -> BpcMode {
        self.bpc_mode
    }

    /// Compute the SHA-256 hash of an ICC profile without registering it.
    pub fn hash_profile(bytes: &[u8]) -> ProfileHash {
        use sha2::{Digest, Sha256};
        Sha256::digest(bytes).into()
    }

    /// Register an ICC profile from raw bytes. Returns the SHA-256 hash on success.
    pub fn register_profile(&mut self, bytes: &[u8]) -> Option<ProfileHash> {
        self.register_profile_with_n(bytes, None)
    }

    /// Register an ICC profile, validating that its color space matches the
    /// expected component count `expected_n`. When the profile's actual color
    /// space has a different number of components (e.g. an RGB profile stored
    /// with PDF `/N 1`), the profile is rejected so the caller can fall back
    /// to the alternate color space.
    pub fn register_profile_with_n(
        &mut self,
        bytes: &[u8],
        expected_n: Option<u32>,
    ) -> Option<ProfileHash> {
        use sha2::{Digest, Sha256};
        let hash: ProfileHash = Sha256::digest(bytes).into();

        // Already registered?
        if self.transforms.contains_key(&hash) {
            return Some(hash);
        }

        // Store raw bytes for PDF embedding
        self.raw_bytes
            .entry(hash)
            .or_insert_with(|| Arc::new(bytes.to_vec()));

        let profile = match ColorProfile::new_from_slice(bytes) {
            Ok(p) => p,
            Err(e) => {
                eprintln!("[ICC] Failed to parse profile: {e}");
                return None;
            }
        };

        let n = match profile.color_space {
            DataColorSpace::Gray => 1u32,
            DataColorSpace::Rgb => 3,
            DataColorSpace::Cmyk => 4,
            DataColorSpace::Lab => 3,
            _ => {
                eprintln!(
                    "[ICC] Unsupported profile color space: {:?}",
                    profile.color_space
                );
                return None;
            }
        };

        // Reject profile when its actual component count doesn't match the
        // PDF's /N declaration — the input data won't match the profile's
        // expected input layout.
        if let Some(expected) = expected_n {
            if n != expected {
                return None;
            }
        }

        let (src_layout_8, src_layout_f64) = match n {
            1 => (Layout::Gray, Layout::Gray),
            3 => (Layout::Rgb, Layout::Rgb),
            4 => (Layout::Rgba, Layout::Rgba),
            _ => return None,
        };

        let dst_layout_8 = Layout::Rgb;
        let dst_layout_f64 = Layout::Rgb;

        // Try multiple rendering intents — Perceptual first so the
        // moxcms-driven `transform_f64` Arc honours the profile's perceptual
        // table. Most CMYK paths route through the perceptual A2B0 CLUT
        // (`bake_clut4_perceptual`) instead, but a few sites still call the
        // f64 transform directly (e.g. `Luminosity` soft-mask conversion in
        // the renderer); for those sites, picking the Perceptual transform
        // here keeps the per-pixel result aligned with the CLUT path. ICC v4
        // profiles may only have A2B0, so this also covers those.
        let intents = [
            RenderingIntent::Perceptual,
            RenderingIntent::RelativeColorimetric,
            RenderingIntent::AbsoluteColorimetric,
            RenderingIntent::Saturation,
        ];

        let mut transform_8bit = None;
        for &intent in &intents {
            let options = TransformOptions {
                rendering_intent: intent,
                ..TransformOptions::default()
            };
            match profile.create_transform_8bit(
                src_layout_8,
                &self.srgb_profile,
                dst_layout_8,
                options,
            ) {
                Ok(t) => {
                    transform_8bit = Some(t);
                    break;
                }
                Err(_) => continue,
            }
        }
        let transform_8bit = match transform_8bit {
            Some(t) => t,
            None if n == 1 => {
                // Gray profiles that can't produce Gray→sRGB transforms (e.g.
                // minimal Linotype profiles with only a TRC): fall back to the
                // sRGB gray curve, which is functionally correct for most Gray
                // profiles encountered in PDFs.
                return self.register_gray_identity(hash, profile);
            }
            None => {
                eprintln!(
                    "[ICC] Failed to create 8-bit transform (cs={:?})",
                    profile.color_space
                );
                return None;
            }
        };

        let mut transform_f64 = None;
        for &intent in &intents {
            let options = TransformOptions {
                rendering_intent: intent,
                ..TransformOptions::default()
            };
            match profile.create_transform_f64(
                src_layout_f64,
                &self.srgb_profile,
                dst_layout_f64,
                options,
            ) {
                Ok(t) => {
                    transform_f64 = Some(t);
                    break;
                }
                Err(_) => continue,
            }
        }
        let transform_f64 = match transform_f64 {
            Some(t) => t,
            None if n == 1 => {
                // Same Gray fallback for f64 path
                return self.register_gray_identity(hash, profile);
            }
            None => {
                eprintln!(
                    "[ICC] Failed to create f64 transform (cs={:?})",
                    profile.color_space
                );
                return None;
            }
        };

        let is_lab = profile.color_space == DataColorSpace::Lab;

        // PDF/X proofing chain: when proofing is enabled and a non-OutputIntent
        // profile is being registered, route source colours through the
        // OutputIntent (`source → OutputIntent → sRGB`) so that an ICCBased
        // CMYK swatch designed to match a DeviceCMYK background renders
        // identically to it. The OutputIntent itself is registered with a
        // direct transform; subsequent profiles are chained.
        type ChainPair = (
            Arc<dyn TransformExecutor<u8> + Send + Sync>,
            Arc<dyn TransformExecutor<f64> + Send + Sync>,
        );
        let mut chain_per_intent_8bit: [Option<Arc<dyn TransformExecutor<u8> + Send + Sync>>; 4] =
            Default::default();
        let mut chain_per_intent_f64: [Option<Arc<dyn TransformExecutor<f64> + Send + Sync>>; 4] =
            Default::default();
        let mut chain_stage1_per_intent: [Option<Arc<perceptual::HandRolledChainStage1Rgb>>; 4] =
            Default::default();
        let chain_data: Option<ChainPair> = if self.proofing_enabled
            && let Some(oi_hash) = self.default_cmyk_hash
            && oi_hash != hash
            && let Some(oi_profile) = self.profiles.get(&oi_hash).cloned()
            && let Some(oi_cached) = self.transforms.get(&oi_hash)
            && oi_cached.n == 4
        {
            // OI is always CMYK in PDF/X workflows; intermediate is 4-component.
            let oi_layout_8 = Layout::Rgba;
            let oi_layout_f64 = Layout::Rgba;

            // Stage 2 (`OutputIntent → sRGB`): prefer OI's hand-rolled
            // CLUT4 over its moxcms transform so chain output matches
            // direct DeviceCMYK conversion at the byte level. The same
            // stage-2 is reused across every intent's chain.
            let stage2_8bit: Arc<dyn TransformExecutor<u8> + Send + Sync> =
                if let Some(oi_clut) = oi_cached.clut4.clone() {
                    Arc::new(Clut4ToRgb { clut4: oi_clut })
                } else {
                    oi_cached.transform_8bit.clone()
                };
            let stage2_f64: Arc<dyn TransformExecutor<f64> + Send + Sync> =
                if let Some(oi_clut) = oi_cached.clut4.clone() {
                    Arc::new(Clut4ToRgb { clut4: oi_clut })
                } else {
                    oi_cached.transform_f64.clone()
                };

            // Hand-rolled chain stage 1 for RGB sources. moxcms's
            // `create_transform` over-saturates sRGB-style first legs by
            // ~5–15% (visible as the GWG 16.1 "X" marks), so we compose
            // `source.A2B[i] → OI.B2A[i]` per-pixel using the same
            // primitives moxcms exposes. Per-pixel composition (vs. an
            // intermediate 17³ CLUT bake) avoids the quantization layer
            // that drifts GWG 13.0's BG-vs-X match by ~6 RGB levels. Only
            // n=3 (RGB) sources go through this path; CMYK sources keep
            // using moxcms (no diagnostic shows that leg drifting).
            //
            // For each of the four ICC rendering intents we try to build
            // a chain using that intent's tables on both sides. Intents
            // whose A2B / B2A tables are missing (or whose profile is in
            // an unsupported shape) skip silently and the slot stays
            // `None`; lookup-time callers fall back to moxcms.
            if n == 3 {
                use moxcms::RenderingIntent;
                for &intent in &[
                    RenderingIntent::Perceptual,
                    RenderingIntent::RelativeColorimetric,
                    RenderingIntent::Saturation,
                    RenderingIntent::AbsoluteColorimetric,
                ] {
                    let Some(stage1) =
                        perceptual::HandRolledChainStage1Rgb::new(&profile, &oi_profile, intent)
                    else {
                        continue;
                    };
                    let stage1_arc = Arc::new(stage1);
                    let chain_8: Arc<dyn TransformExecutor<u8> + Send + Sync> =
                        Arc::new(ChainedTransform {
                            stage1: stage1_arc.clone(),
                            stage2: stage2_8bit.clone(),
                            intermediate_n: 4,
                        });
                    let chain_f: Arc<dyn TransformExecutor<f64> + Send + Sync> =
                        Arc::new(ChainedTransform {
                            stage1: stage1_arc.clone(),
                            stage2: stage2_f64.clone(),
                            intermediate_n: 4,
                        });
                    let i = intent as usize;
                    chain_per_intent_8bit[i] = Some(chain_8);
                    chain_per_intent_f64[i] = Some(chain_f);
                    chain_stage1_per_intent[i] = Some(stage1_arc);
                }
            }

            // Default chain (used when the lookup path doesn't yet pass an
            // intent — the current state of `convert_color`). Picks the
            // Perceptual hand-rolled chain when available; otherwise falls
            // back to moxcms's transform-driven build, preserving the
            // n=4 CMYK source path.
            let perceptual_idx = moxcms::RenderingIntent::Perceptual as usize;
            if let (Some(c8), Some(cf)) = (
                chain_per_intent_8bit[perceptual_idx].clone(),
                chain_per_intent_f64[perceptual_idx].clone(),
            ) {
                Some((c8, cf))
            } else {
                let mut stage1_8bit_opt: Option<Arc<dyn TransformExecutor<u8> + Send + Sync>> =
                    None;
                let mut stage1_f64_opt: Option<Arc<dyn TransformExecutor<f64> + Send + Sync>> =
                    None;
                for &intent in &intents {
                    let options = TransformOptions {
                        rendering_intent: intent,
                        ..TransformOptions::default()
                    };
                    if let Ok(t) = profile.create_transform_8bit(
                        src_layout_8,
                        &oi_profile,
                        oi_layout_8,
                        options,
                    ) {
                        stage1_8bit_opt = Some(t);
                        break;
                    }
                }
                for &intent in &intents {
                    let options = TransformOptions {
                        rendering_intent: intent,
                        ..TransformOptions::default()
                    };
                    if let Ok(t) = profile.create_transform_f64(
                        src_layout_f64,
                        &oi_profile,
                        oi_layout_f64,
                        options,
                    ) {
                        stage1_f64_opt = Some(t);
                        break;
                    }
                }
                match (stage1_8bit_opt, stage1_f64_opt) {
                    (Some(s1_8), Some(s1_f)) => {
                        let chain_8: Arc<dyn TransformExecutor<u8> + Send + Sync> =
                            Arc::new(ChainedTransform {
                                stage1: s1_8,
                                stage2: stage2_8bit,
                                intermediate_n: 4,
                            });
                        let chain_f: Arc<dyn TransformExecutor<f64> + Send + Sync> =
                            Arc::new(ChainedTransform {
                                stage1: s1_f,
                                stage2: stage2_f64,
                                intermediate_n: 4,
                            });
                        Some((chain_8, chain_f))
                    }
                    _ => None,
                }
            }
        } else {
            None
        };

        // When the chain build succeeded, override the cached transforms with
        // the chain versions. The CLUT4 below is then baked from the chain
        // (for CMYK source profiles), so single-color and image conversions
        // share the same `OutputIntent → sRGB` final stage as DeviceCMYK.
        let (transform_8bit, transform_f64, chain_active) = match chain_data {
            Some((c8, cf)) => (c8, cf, true),
            None => (transform_8bit, transform_f64, false),
        };

        // For 4-channel (CMYK) profiles, pre-bake a 17^4 CLUT for fast image
        // conversion. Two paths produce the same Clut4 layout:
        //
        // 1. `bake_clut4_perceptual` samples the profile's own A2B1
        //    (colorimetric) table directly, decodes the legacy v2 PCS-Lab
        //    encoding, and clips out-of-gamut colours to the sRGB boundary.
        //    Output matches lcms2's `cmsDoTransform(RelCol)` to ±1 RGB level.
        //    Available for v2 mft2 CMYK profiles. BPC is computed inside the
        //    bake against this sampler's own (1,1,1,1) output so the source
        //    black-point matches what we're actually producing.
        // 2. `bake_clut4` invokes the 8-bit moxcms transform on a grid;
        //    fallback for profiles whose tables are missing or in a shape we
        //    don't yet handle (mAB, mft1, XYZ-PCS). BPC is calibrated against
        //    moxcms's transform output (`detect_source_black_point`).
        //
        // The runtime CLUT lookup is identical regardless of which path
        // produced the table.
        //
        // `bpc_params` is stored on `CachedTransform` for the moxcms-fallback
        // path's `convert_color` / `convert_color_readonly` callers when the
        // bake returned `None`. The hand-rolled sampler folds BPC in directly
        // and leaves this `None`; the cached `transform_f64` Arc is only
        // exercised in fallback contexts and shouldn't double-apply BPC.
        let bpc_enabled = n == 4 && self.bpc_mode.is_enabled();
        let mut bpc_params: Option<BpcParams> = None;
        let clut4 = if n == 4 && !chain_active {
            // Direct (non-proofing) CMYK profiles: pre-bake a CLUT for fast
            // image conversion.
            let c = perceptual::bake_clut4_perceptual(&profile, 17, bpc_enabled).or_else(|| {
                let params = if bpc_enabled {
                    detect_source_black_point(transform_8bit.as_ref())
                        .map(|sbp| compute_bpc_params(sbp, [0.0; 3], bpc::WP_D50))
                } else {
                    None
                };
                let r = bake_clut4(transform_8bit.as_ref(), 17, params.as_ref());
                bpc_params = params;
                r
            });
            if std::env::var_os("STET_ICC_VERIFY").is_some()
                && let Some(ref clut) = c
            {
                verify_clut4(clut, transform_8bit.as_ref(), bpc_params.as_ref());
            }
            c
        } else {
            // Chain-mode: do NOT pre-bake the source profile's CLUT. A
            // pre-baked source CLUT would compose two CLUT4 quantizations
            // (source-bake + stage 2's OutputIntent-bake) and drift a few
            // sRGB levels relative to direct DeviceCMYK paints. Routing every
            // call through the chain transform keeps just one CLUT
            // quantization (OutputIntent's, in stage 2), so a designed-equal
            // ICCBased CMYK swatch and DeviceCMYK background converge.
            None
        };

        self.profiles.insert(hash, Arc::new(profile));
        self.transforms.insert(
            hash,
            CachedTransform {
                transform_8bit,
                transform_f64,
                chain_per_intent_8bit,
                chain_per_intent_f64,
                chain_stage1_per_intent,
                n,
                is_lab,
                clut4,
                bpc_params,
            },
        );

        Some(hash)
    }

    /// Register a Gray profile with an identity Gray→RGB fallback transform.
    /// Used when the ICC library can't create a proper transform from the profile
    /// (e.g. minimal profiles with only a TRC and no A2B/B2A tables).
    fn register_gray_identity(
        &mut self,
        hash: ProfileHash,
        profile: ColorProfile,
    ) -> Option<ProfileHash> {
        self.profiles.insert(hash, Arc::new(profile));
        self.transforms.insert(
            hash,
            CachedTransform {
                transform_8bit: Arc::new(GrayToRgbIdentity),
                transform_f64: Arc::new(GrayToRgbIdentity),
                chain_per_intent_8bit: Default::default(),
                chain_per_intent_f64: Default::default(),
                chain_stage1_per_intent: Default::default(),
                n: 1,
                is_lab: false,
                clut4: None,
                bpc_params: None,
            },
        );
        Some(hash)
    }

    /// Convert RGB components through the proofing chain's stage 1 to
    /// the OutputIntent's CMYK ink values. Returns `None` when no
    /// hand-rolled chain exists for this profile (the document isn't
    /// PDF/X, or the profile shape is unsupported), in which case the
    /// caller should leave `DeviceColor::native_cmyk` as `None` and the
    /// renderer falls back to its sRGB-derived approximation. The
    /// `intent` parameter selects which per-intent chain to use; falls
    /// back to the Perceptual chain when the requested intent slot is
    /// empty.
    pub fn convert_to_oi_cmyk(
        &self,
        hash: &ProfileHash,
        components: &[f64],
        intent: RenderingIntent,
    ) -> Option<[f64; 4]> {
        let cached = self.transforms.get(hash)?;
        if cached.n != 3 {
            return None;
        }
        let stage1 = cached.chain_stage1_per_intent[intent as usize]
            .as_ref()
            .or(cached.chain_stage1_per_intent[RenderingIntent::Perceptual as usize].as_ref())?;
        let r = components.first().copied().unwrap_or(0.0).clamp(0.0, 1.0);
        let g = components.get(1).copied().unwrap_or(0.0).clamp(0.0, 1.0);
        let b = components.get(2).copied().unwrap_or(0.0).clamp(0.0, 1.0);
        Some(stage1.sample_cmyk_f64(r, g, b))
    }

    /// Convert a single color through an ICC profile to sRGB.
    /// Returns (r, g, b) in [0, 1] range.
    pub fn convert_color(
        &mut self,
        hash: &ProfileHash,
        components: &[f64],
    ) -> Option<(f64, f64, f64)> {
        let cached = self.transforms.get(hash)?;
        let n = cached.n as usize;
        let is_lab = cached.is_lab;

        // Normalize input values to [0,1] range.
        // Lab profiles need special mapping: L/100, (a+128)/255, (b+128)/255.
        let mut src = vec![0.0f64; n];
        for (i, s) in src.iter_mut().enumerate() {
            let v = components.get(i).copied().unwrap_or(0.0);
            *s = if is_lab {
                match i {
                    0 => (v / 100.0).clamp(0.0, 1.0),
                    _ => ((v + 128.0) / 255.0).clamp(0.0, 1.0),
                }
            } else {
                v.clamp(0.0, 1.0)
            };
        }

        // Quantize normalized values for cache key
        let hash_prefix = u64::from_le_bytes(hash[..8].try_into().ok()?);
        let mut quantized = [0u16; 4];
        for (i, &c) in src.iter().take(4).enumerate() {
            quantized[i] = (c * 65535.0).round() as u16;
        }

        // Check cache
        let cache_key = (hash_prefix, quantized);
        if let Some(&cached) = self.color_cache.get(&cache_key) {
            return Some(cached);
        }

        let result = if n == 4
            && let Some(clut) = cached.clut4.as_ref()
        {
            // Route single-color CMYK through the same baked CLUT image
            // conversions use, so a flat fill matches the surrounding gradient
            // stops byte-for-byte. BPC and the perceptual A2B0 sampling are
            // already folded into the CLUT.
            let (r, g, b) = sample_clut4_single_f64(clut, src[0], src[1], src[2], src[3]);
            (r, g, b)
        } else {
            let mut dst = [0.0f64; 3];
            if cached.transform_f64.transform(&src, &mut dst).is_err() {
                return None;
            }
            let dst = bpc_post_correct(dst, cached.bpc_params.as_ref());
            (
                dst[0].clamp(0.0, 1.0),
                dst[1].clamp(0.0, 1.0),
                dst[2].clamp(0.0, 1.0),
            )
        };

        // Cache (limit size to avoid unbounded growth)
        if self.color_cache.len() < 65536 {
            self.color_cache.insert(cache_key, result);
        }

        Some(result)
    }

    /// Cached single-color conversion under a specific rendering
    /// intent. Delegates to the legacy [`Self::convert_color`] for
    /// Perceptual (which uses the Perceptual chain stored in
    /// `transform_f64` and the Perceptual-keyed cache); for the other
    /// intents it goes through [`Self::convert_color_readonly_with_intent`]
    /// and caches per-intent.
    pub fn convert_color_with_intent(
        &mut self,
        hash: &ProfileHash,
        components: &[f64],
        intent: RenderingIntent,
    ) -> Option<(f64, f64, f64)> {
        if matches!(intent, RenderingIntent::Perceptual) {
            return self.convert_color(hash, components);
        }
        // Quantize for cache key. Have to recompute here because
        // `convert_color_readonly_with_intent` doesn't return the
        // quantized buffer. The arithmetic mirrors `convert_color`.
        let cached = self.transforms.get(hash)?;
        let n = cached.n as usize;
        let is_lab = cached.is_lab;
        let mut src = vec![0.0f64; n];
        for (i, s) in src.iter_mut().enumerate() {
            let v = components.get(i).copied().unwrap_or(0.0);
            *s = if is_lab {
                match i {
                    0 => (v / 100.0).clamp(0.0, 1.0),
                    _ => ((v + 128.0) / 255.0).clamp(0.0, 1.0),
                }
            } else {
                v.clamp(0.0, 1.0)
            };
        }
        let hash_prefix = u64::from_le_bytes(hash[..8].try_into().ok()?);
        let mut quantized = [0u16; 4];
        for (i, &c) in src.iter().take(4).enumerate() {
            quantized[i] = (c * 65535.0).round() as u16;
        }
        let cache_key = (hash_prefix, quantized, intent as u8);
        if let Some(&hit) = self.color_cache_intent.get(&cache_key) {
            return Some(hit);
        }
        let result = self.convert_color_readonly_with_intent(hash, components, intent)?;
        if self.color_cache_intent.len() < 65536 {
            self.color_cache_intent.insert(cache_key, result);
        }
        Some(result)
    }

    /// Convert a single color through an ICC profile using a specific
    /// rendering intent. Falls back to the cached default chain (built
    /// from the Perceptual tables) when no per-intent chain is
    /// available — that path matches [`Self::convert_color_readonly`]
    /// byte-for-byte and is the common case for non-PDF/X documents and
    /// CMYK source profiles.
    pub fn convert_color_readonly_with_intent(
        &self,
        hash: &ProfileHash,
        components: &[f64],
        intent: RenderingIntent,
    ) -> Option<(f64, f64, f64)> {
        let cached = self.transforms.get(hash)?;
        let n = cached.n as usize;
        let is_lab = cached.is_lab;

        let mut src = vec![0.0f64; n];
        for (i, s) in src.iter_mut().enumerate() {
            let v = components.get(i).copied().unwrap_or(0.0);
            *s = if is_lab {
                match i {
                    0 => (v / 100.0).clamp(0.0, 1.0),
                    _ => ((v + 128.0) / 255.0).clamp(0.0, 1.0),
                }
            } else {
                v.clamp(0.0, 1.0)
            };
        }

        // CMYK profiles: route through the pre-baked CLUT4 (no per-intent
        // variant exists on this path; intent-driven CMYK B2A selection
        // is deferred until the chain-side per-intent OI bake).
        if n == 4
            && let Some(clut) = cached.clut4.as_ref()
        {
            let (r, g, b) = sample_clut4_single_f64(clut, src[0], src[1], src[2], src[3]);
            return Some((r, g, b));
        }

        let transform = cached.chain_per_intent_f64[intent as usize]
            .as_ref()
            .unwrap_or(&cached.transform_f64);
        let mut dst = [0.0f64; 3];
        if transform.transform(&src, &mut dst).is_err() {
            return None;
        }

        let dst = bpc_post_correct(dst, cached.bpc_params.as_ref());
        Some((
            dst[0].clamp(0.0, 1.0),
            dst[1].clamp(0.0, 1.0),
            dst[2].clamp(0.0, 1.0),
        ))
    }

    /// Convert a single color through an ICC profile (read-only, no caching).
    ///
    /// Same as `convert_color` but takes `&self` instead of `&mut self`,
    /// suitable for use from immutable contexts like rendering.
    pub fn convert_color_readonly(
        &self,
        hash: &ProfileHash,
        components: &[f64],
    ) -> Option<(f64, f64, f64)> {
        let cached = self.transforms.get(hash)?;
        let n = cached.n as usize;
        let is_lab = cached.is_lab;

        let mut src = vec![0.0f64; n];
        for (i, s) in src.iter_mut().enumerate() {
            let v = components.get(i).copied().unwrap_or(0.0);
            *s = if is_lab {
                match i {
                    0 => (v / 100.0).clamp(0.0, 1.0),
                    _ => ((v + 128.0) / 255.0).clamp(0.0, 1.0),
                }
            } else {
                v.clamp(0.0, 1.0)
            };
        }

        if n == 4
            && let Some(clut) = cached.clut4.as_ref()
        {
            let (r, g, b) = sample_clut4_single_f64(clut, src[0], src[1], src[2], src[3]);
            return Some((r, g, b));
        }

        let mut dst = [0.0f64; 3];
        if cached.transform_f64.transform(&src, &mut dst).is_err() {
            return None;
        }

        let dst = bpc_post_correct(dst, cached.bpc_params.as_ref());
        Some((
            dst[0].clamp(0.0, 1.0),
            dst[1].clamp(0.0, 1.0),
            dst[2].clamp(0.0, 1.0),
        ))
    }

    /// Bulk-convert 8-bit image samples through an ICC profile to RGB
    /// using a specific rendering intent. Falls back to the cached
    /// default 8-bit transform (built from the Perceptual tables) when
    /// no per-intent chain is available — that path matches
    /// [`Self::convert_image_8bit`] byte-for-byte.
    pub fn convert_image_8bit_with_intent(
        &self,
        hash: &ProfileHash,
        samples: &[u8],
        pixel_count: usize,
        intent: RenderingIntent,
    ) -> Option<Vec<u8>> {
        let cached = self.transforms.get(hash)?;
        let n = cached.n as usize;
        let expected_len = pixel_count * n;
        if samples.len() < expected_len {
            return None;
        }

        // CMYK profiles route through the pre-baked CLUT4. Per-intent
        // CMYK B2A selection on this side of the chain is deferred —
        // step 4 will revisit when BPC + AbsCol land.
        if let Some(clut) = &cached.clut4 {
            return Some(apply_clut4_cmyk_to_rgb(
                clut,
                &samples[..expected_len],
                pixel_count,
            ));
        }

        let transform = cached.chain_per_intent_8bit[intent as usize]
            .as_ref()
            .unwrap_or(&cached.transform_8bit);
        let src = &samples[..expected_len];
        let mut dst = vec![0u8; pixel_count * 3];
        match transform.transform(src, &mut dst) {
            Ok(()) => {
                if let Some(p) = cached.bpc_params.as_ref() {
                    for px in dst.chunks_exact_mut(3) {
                        let out = apply_bpc_rgb_u8([px[0], px[1], px[2]], p);
                        px[0] = out[0];
                        px[1] = out[1];
                        px[2] = out[2];
                    }
                }
                Some(dst)
            }
            Err(e) => {
                eprintln!("[ICC] Image transform failed (intent {intent:?}): {e}");
                None
            }
        }
    }

    /// Bulk-convert 8-bit image samples through an ICC profile to RGB.
    /// Input: packed samples (Gray/RGB/CMYK depending on profile).
    /// Output: packed RGB bytes (3 bytes per pixel).
    pub fn convert_image_8bit(
        &self,
        hash: &ProfileHash,
        samples: &[u8],
        pixel_count: usize,
    ) -> Option<Vec<u8>> {
        let cached = self.transforms.get(hash)?;
        let n = cached.n as usize;
        let expected_len = pixel_count * n;
        if samples.len() < expected_len {
            return None;
        }

        // Fast path: pre-baked 4D CLUT for CMYK profiles. BPC is already
        // baked into the CLUT (when enabled), so no per-pixel correction
        // is needed here.
        if let Some(clut) = &cached.clut4 {
            return Some(apply_clut4_cmyk_to_rgb(
                clut,
                &samples[..expected_len],
                pixel_count,
            ));
        }

        let src = &samples[..expected_len];
        let mut dst = vec![0u8; pixel_count * 3];

        match cached.transform_8bit.transform(src, &mut dst) {
            Ok(()) => {
                // Apply BPC per pixel for non-CLUT bulk paths (CMYK profiles
                // whose CLUT bake failed; today no other layouts populate
                // bpc_params, so this is a no-op for RGB/Gray/Lab).
                if let Some(p) = cached.bpc_params.as_ref() {
                    for px in dst.chunks_exact_mut(3) {
                        let out = apply_bpc_rgb_u8([px[0], px[1], px[2]], p);
                        px[0] = out[0];
                        px[1] = out[1];
                        px[2] = out[2];
                    }
                }
                Some(dst)
            }
            Err(e) => {
                eprintln!("[ICC] Image transform failed: {e}");
                None
            }
        }
    }

    /// Search system paths for a CMYK ICC profile and register it.
    pub fn search_system_cmyk_profile(&mut self) {
        if let Some(bytes) = find_system_cmyk_profile()
            && let Some(hash) = self.register_profile(&bytes)
        {
            eprintln!("[ICC] Loaded system CMYK profile");
            self.system_cmyk_bytes = Some(Arc::new(bytes));
            self.default_cmyk_hash = Some(hash);
        }
    }

    /// Load a CMYK ICC profile from raw bytes (for environments without filesystem access).
    pub fn load_cmyk_profile_bytes(&mut self, bytes: &[u8]) {
        if let Some(hash) = self.register_profile(bytes) {
            self.system_cmyk_bytes = Some(Arc::new(bytes.to_vec()));
            self.default_cmyk_hash = Some(hash);
        }
    }

    /// Get the default CMYK profile hash, if a system CMYK profile was found.
    pub fn default_cmyk_hash(&self) -> Option<&ProfileHash> {
        self.default_cmyk_hash.as_ref()
    }

    /// Check if a profile hash has been registered.
    pub fn has_profile(&self, hash: &ProfileHash) -> bool {
        self.transforms.contains_key(hash)
    }

    /// Get the raw bytes of a registered ICC profile (for PDF embedding).
    pub fn get_profile_bytes(&self, hash: &ProfileHash) -> Option<Arc<Vec<u8>>> {
        self.raw_bytes.get(hash).cloned()
    }

    /// Get the raw bytes of the system CMYK profile (for re-registration in render threads).
    pub fn system_cmyk_bytes(&self) -> Option<&Arc<Vec<u8>>> {
        self.system_cmyk_bytes.as_ref()
    }

    /// Set the system CMYK profile from pre-loaded bytes and hash.
    ///
    /// Used by `--output-profile` to substitute the auto-detected system CMYK
    /// profile with a user-specified one.
    pub fn set_system_cmyk(&mut self, bytes: &[u8], hash: ProfileHash) {
        self.system_cmyk_bytes = Some(Arc::new(bytes.to_vec()));
        self.default_cmyk_hash = Some(hash);
    }

    /// Enable PDF/X-style proofing: ICCBased profiles registered while this
    /// flag is set route through the default CMYK profile (the OutputIntent)
    /// before reaching sRGB. See [`Self::proofing_enabled`].
    pub fn set_proofing_enabled(&mut self, enabled: bool) {
        self.proofing_enabled = enabled;
    }

    /// Whether PDF/X-style proofing is enabled. When `true`, source ICC
    /// profiles other than the default CMYK convert through the default
    /// CMYK ("OutputIntent") instead of going directly to sRGB. This makes
    /// per-swatch ICC colours and surrounding DeviceCMYK paints converge
    /// through the same final `OutputIntent → sRGB` stage. When `false`,
    /// every profile converts directly (the historical behaviour).
    pub fn proofing_enabled(&self) -> bool {
        self.proofing_enabled
    }

    /// Set the default CMYK profile hash (used when building render-thread caches).
    pub fn set_default_cmyk_hash(&mut self, hash: ProfileHash) {
        self.default_cmyk_hash = Some(hash);
    }

    /// Temporarily remove the default CMYK hash, returning the old value.
    /// Used to disable ICC CMYK conversion inside soft mask form rendering,
    /// where PLRM formulas produce correct luminosity values (ICC profiles
    /// map 100% K to non-zero RGB, breaking luminosity soft masks).
    pub fn suspend_default_cmyk(&mut self) -> Option<ProfileHash> {
        self.default_cmyk_hash.take()
    }

    /// Restore a previously suspended default CMYK hash.
    pub fn restore_default_cmyk(&mut self, hash: Option<ProfileHash>) {
        self.default_cmyk_hash = hash;
    }

    /// Convert CMYK to (r, g, b) using the default system CMYK profile.
    /// Returns None if no system CMYK profile is loaded.
    #[inline]
    pub fn convert_cmyk(&mut self, c: f64, m: f64, y: f64, k: f64) -> Option<(f64, f64, f64)> {
        let hash = *self.default_cmyk_hash.as_ref()?;
        self.convert_color(&hash, &[c, m, y, k])
    }

    /// Convert CMYK to (r, g, b) using the default system CMYK profile (read-only, no caching).
    /// Used by band renderers that only have `&self` access.
    pub fn convert_cmyk_readonly(&self, c: f64, m: f64, y: f64, k: f64) -> Option<(f64, f64, f64)> {
        let hash = self.default_cmyk_hash.as_ref()?;
        let cached = self.transforms.get(hash)?;
        let src = [
            c.clamp(0.0, 1.0),
            m.clamp(0.0, 1.0),
            y.clamp(0.0, 1.0),
            k.clamp(0.0, 1.0),
        ];
        if let Some(clut) = cached.clut4.as_ref() {
            // Sample the same baked CLUT image conversions use, so a flat fill
            // matches the surrounding gradient stops byte-for-byte. BPC and the
            // perceptual A2B0 sampling are already folded into the CLUT.
            let (r, g, b) = sample_clut4_single_f64(clut, src[0], src[1], src[2], src[3]);
            return Some((r, g, b));
        }
        let mut dst = [0.0f64; 3];
        if cached.transform_f64.transform(&src, &mut dst).is_err() {
            return None;
        }
        let dst = bpc_post_correct(dst, cached.bpc_params.as_ref());
        Some((
            dst[0].clamp(0.0, 1.0),
            dst[1].clamp(0.0, 1.0),
            dst[2].clamp(0.0, 1.0),
        ))
    }

    /// Build the lazy sRGB→CMYK reverse transform from the system CMYK profile.
    /// Returns `Some(())` if the transform is now present (built or already
    /// cached). Returns `None` if no system CMYK profile is registered or no
    /// rendering intent could create a transform.
    fn ensure_reverse_cmyk_transform(&mut self) -> Option<()> {
        if self.reverse_cmyk_f64.is_some() {
            return Some(());
        }
        let hash = *self.default_cmyk_hash.as_ref()?;
        let cmyk_profile = self.profiles.get(&hash)?.clone();
        let intents = [
            RenderingIntent::RelativeColorimetric,
            RenderingIntent::Perceptual,
            RenderingIntent::AbsoluteColorimetric,
            RenderingIntent::Saturation,
        ];
        for &intent in &intents {
            let options = TransformOptions {
                rendering_intent: intent,
                ..TransformOptions::default()
            };
            if let Ok(t) = self.srgb_profile.create_transform_f64(
                Layout::Rgb,
                &cmyk_profile,
                Layout::Rgba,
                options,
            ) {
                self.reverse_cmyk_f64 = Some(t);
                return Some(());
            }
        }
        None
    }

    /// Pre-warm the lazy sRGB→CMYK reverse transform. Should be called once on
    /// the build thread that owns `&mut IccCache`, after the system CMYK
    /// profile has been registered, so that band renderers (which only hold
    /// `&IccCache`) can use [`Self::convert_rgb_to_cmyk_readonly`] without
    /// having to mutate state.
    pub fn prepare_reverse_cmyk(&mut self) {
        let _ = self.ensure_reverse_cmyk_transform();
    }

    /// Pre-build per-intent `Lab → OutputIntent CMYK` samplers from the
    /// document's OutputIntent profile. Call once after the OI is registered
    /// so [`Self::convert_lab_to_oi_cmyk`] can run from `&IccCache`.
    /// No-op when no default CMYK profile is registered, when the profile
    /// shape doesn't expose B2A LUTs (shaper-matrix CMYK with no LUT, etc.),
    /// or when proofing is disabled.
    pub fn prepare_lab_to_oi_cmyk(&mut self) {
        let Some(hash) = self.default_cmyk_hash else {
            return;
        };
        let Some(profile) = self.profiles.get(&hash).cloned() else {
            return;
        };
        use moxcms::RenderingIntent;
        for &intent in &[
            RenderingIntent::Perceptual,
            RenderingIntent::RelativeColorimetric,
            RenderingIntent::Saturation,
            RenderingIntent::AbsoluteColorimetric,
        ] {
            let i = intent as usize;
            if self.lab_to_oi_per_intent[i].is_some() {
                continue;
            }
            if let Some(sampler) = perceptual::LabToCmykSampler::build(&profile, intent) {
                self.lab_to_oi_per_intent[i] = Some(Arc::new(sampler));
            }
        }
    }

    /// Convert a PDF Lab triplet (L\* ∈ [0, 100], a\*/b\* ∈ [-128, 127]) to
    /// OutputIntent CMYK using the OI's per-intent B2A table. Returns `None`
    /// when the per-intent sampler hasn't been built (call
    /// [`Self::prepare_lab_to_oi_cmyk`] first) or when the intent slot is
    /// empty (falls back to Perceptual when available).
    ///
    /// Used by `lab_to_device_color` to populate `DeviceColor::native_cmyk`
    /// so the renderer's parallel CMYK buffer holds the same direct
    /// `Lab → OI CMYK` value Acrobat's ACE produces. Without this, the
    /// renderer falls back to `convert_rgb_to_cmyk_readonly` (sRGB → ICC
    /// reverse), which drifts visibly under CMYK-group blends. GWG 22.1's
    /// ColorBurn form over a Lab BG is the canonical surfacing case.
    pub fn convert_lab_to_oi_cmyk(
        &self,
        l_star: f64,
        a_star: f64,
        b_star: f64,
        intent: IccRenderingIntent,
    ) -> Option<[f64; 4]> {
        let sampler = self.lab_to_oi_per_intent[intent as usize]
            .as_ref()
            .or(self.lab_to_oi_per_intent[IccRenderingIntent::Perceptual as usize].as_ref())?;
        Some(sampler.sample_pdf_lab(l_star, a_star, b_star))
    }

    /// Convert an sRGB color to CMYK using the system CMYK profile, without
    /// mutating any state. Returns `None` when the reverse transform has not
    /// been pre-built (call [`Self::prepare_reverse_cmyk`] first) or when no
    /// system CMYK profile is registered.
    ///
    /// The returned components are clamped to `[0, 1]`.
    pub fn convert_rgb_to_cmyk_readonly(&self, r: f64, g: f64, b: f64) -> Option<[f64; 4]> {
        let reverse = self.reverse_cmyk_f64.as_ref()?;
        let src_rgb = [r.clamp(0.0, 1.0), g.clamp(0.0, 1.0), b.clamp(0.0, 1.0)];
        let mut cmyk = [0.0f64; 4];
        reverse.transform(&src_rgb, &mut cmyk).ok()?;
        Some([
            cmyk[0].clamp(0.0, 1.0),
            cmyk[1].clamp(0.0, 1.0),
            cmyk[2].clamp(0.0, 1.0),
            cmyk[3].clamp(0.0, 1.0),
        ])
    }

    /// Round-trip an RGB color through the system CMYK profile: sRGB→CMYK→sRGB.
    /// Used when compositing in a DeviceCMYK page group — saturated RGB colors
    /// become more muted after passing through the CMYK gamut.
    /// Returns None if no CMYK profile is loaded.
    pub fn round_trip_rgb_via_cmyk(&mut self, r: f64, g: f64, b: f64) -> Option<(f64, f64, f64)> {
        self.ensure_reverse_cmyk_transform()?;
        let hash = *self.default_cmyk_hash.as_ref()?;
        let reverse = self.reverse_cmyk_f64.as_ref()?;

        // sRGB → CMYK
        let src_rgb = [r.clamp(0.0, 1.0), g.clamp(0.0, 1.0), b.clamp(0.0, 1.0)];
        let mut cmyk = [0.0f64; 4];
        reverse.transform(&src_rgb, &mut cmyk).ok()?;

        // CMYK → sRGB (via existing forward transform)
        let forward = self.transforms.get(&hash)?;
        let mut dst = [0.0f64; 3];
        forward.transform_f64.transform(&cmyk, &mut dst).ok()?;

        let dst = bpc_post_correct(dst, forward.bpc_params.as_ref());
        Some((
            dst[0].clamp(0.0, 1.0),
            dst[1].clamp(0.0, 1.0),
            dst[2].clamp(0.0, 1.0),
        ))
    }

    /// Disable all ICC color management — clears all profiles, transforms,
    /// and caches. Equivalent to the CLI's `--no-icc` flag.
    pub fn disable(&mut self) {
        self.profiles.clear();
        self.transforms.clear();
        self.color_cache.clear();
        self.raw_bytes.clear();
        self.default_cmyk_hash = None;
        self.system_cmyk_bytes = None;
        self.reverse_cmyk_f64 = None;
    }
}

/// Bake a 4D CLUT by sampling an 8-bit CMYK→sRGB transform on a regular grid.
///
/// Generates `grid_n^4` CMYK sample points (each channel stepping `0..=255` in
/// `grid_n` steps), invokes moxcms once on the full batch, and stores the
/// packed sRGB output. Storage order is K outermost, then Y, M, C innermost,
/// matching the interpolation access pattern in `apply_clut4_cmyk_to_rgb`.
///
/// Returns `None` if the transform invocation fails — callers fall back to
/// direct moxcms calls per image.
fn bake_clut4(
    transform: &(dyn TransformExecutor<u8> + Send + Sync),
    grid_n: u8,
    bpc_params: Option<&BpcParams>,
) -> Option<Clut4> {
    let n = grid_n as usize;
    if !(2..=33).contains(&n) {
        return None;
    }
    let total = n * n * n * n;
    // Sample grid: for each (k, y, m, c) grid index, emit bytes (c, m, y, k).
    // moxcms consumes this as packed 4-channel input.
    let mut src = Vec::with_capacity(total * 4);
    let step = |i: usize| -> u8 {
        // Spread grid indices evenly across 0..=255 (endpoints inclusive).
        ((i as u32 * 255) / (n as u32 - 1)) as u8
    };
    for k in 0..n {
        let kv = step(k);
        for y in 0..n {
            let yv = step(y);
            for m in 0..n {
                let mv = step(m);
                for c in 0..n {
                    let cv = step(c);
                    src.extend_from_slice(&[cv, mv, yv, kv]);
                }
            }
        }
    }
    let mut dst = vec![0u8; total * 3];
    transform.transform(&src, &mut dst).ok()?;

    // Bake BPC into every grid point so runtime CLUT lookup stays at zero
    // per-pixel cost.
    if let Some(p) = bpc_params {
        for px in dst.chunks_exact_mut(3) {
            let out = apply_bpc_rgb_u8([px[0], px[1], px[2]], p);
            px[0] = out[0];
            px[1] = out[1];
            px[2] = out[2];
        }
    }

    Some(Clut4 {
        grid_n,
        data: Arc::new(dst),
    })
}

/// Single-pixel CMYK→sRGB lookup against the baked CLUT, with f64 inputs and
/// outputs. Performs the same K-bracket × 3D tetrahedral interpolation as the
/// bulk image path, but in floating point so a flat fill (which would otherwise
/// quantize the input to u8) matches a gradient stop's byte output to within
/// the CLUT's grid-interpolation error.
fn sample_clut4_single_f64(clut: &Clut4, c: f64, m: f64, y: f64, k: f64) -> (f64, f64, f64) {
    let n = clut.grid_n as usize;
    let nm1 = (n - 1) as f64;
    let lut = clut.data.as_slice();
    let stride_c: usize = 3;
    let stride_m: usize = n * stride_c;
    let stride_y: usize = n * stride_m;
    let stride_k: usize = n * stride_y;

    #[inline]
    fn axis(v: f64, nm1: f64, n: usize) -> (usize, usize, f64) {
        let scaled = v.clamp(0.0, 1.0) * nm1;
        let lo = scaled.floor();
        let frac = scaled - lo;
        let lo_i = lo as usize;
        let hi_i = (lo_i + 1).min(n - 1);
        (lo_i, hi_i, frac)
    }

    let (ci, ci1, fc) = axis(c, nm1, n);
    let (mi, mi1, fm) = axis(m, nm1, n);
    let (yi, yi1, fy) = axis(y, nm1, n);
    let (ki, ki1, fk) = axis(k, nm1, n);

    // Pick tetrahedron vertices (Kasson '94) — same logic as the u8 path.
    let (a_dxmy, b_dxmy, w1, w2, w3) = if fc >= fm {
        if fm >= fy {
            ((1, 0, 0), (1, 1, 0), fc, fm, fy)
        } else if fc >= fy {
            ((1, 0, 0), (1, 0, 1), fc, fy, fm)
        } else {
            ((0, 0, 1), (1, 0, 1), fy, fc, fm)
        }
    } else if fc >= fy {
        ((0, 1, 0), (1, 1, 0), fm, fc, fy)
    } else if fm >= fy {
        ((0, 1, 0), (0, 1, 1), fm, fy, fc)
    } else {
        ((0, 0, 1), (0, 1, 1), fy, fm, fc)
    };

    let corner = |d: (u8, u8, u8)| -> usize {
        let (dc, dm, dy) = d;
        let cx = if dc == 0 { ci } else { ci1 };
        let mx = if dm == 0 { mi } else { mi1 };
        let yx = if dy == 0 { yi } else { yi1 };
        yx * stride_y + mx * stride_m + cx * stride_c
    };

    let o000 = corner((0, 0, 0));
    let o111 = corner((1, 1, 1));
    let oa = corner(a_dxmy);
    let ob = corner(b_dxmy);

    let base_lo = ki * stride_k;
    let base_hi = ki1 * stride_k;

    let tetra_channel = |base: usize, ch: usize| -> f64 {
        let v000 = lut[base + o000 + ch] as f64;
        let va = lut[base + oa + ch] as f64;
        let vb = lut[base + ob + ch] as f64;
        let v111 = lut[base + o111 + ch] as f64;
        v000 + (va - v000) * w1 + (vb - va) * w2 + (v111 - vb) * w3
    };

    let r_lo = tetra_channel(base_lo, 0);
    let g_lo = tetra_channel(base_lo, 1);
    let b_lo = tetra_channel(base_lo, 2);
    let (r_hi, g_hi, b_hi) = if ki == ki1 {
        (r_lo, g_lo, b_lo)
    } else {
        (
            tetra_channel(base_hi, 0),
            tetra_channel(base_hi, 1),
            tetra_channel(base_hi, 2),
        )
    };

    let inv_fk = 1.0 - fk;
    let r = (r_lo * inv_fk + r_hi * fk) / 255.0;
    let g = (g_lo * inv_fk + g_hi * fk) / 255.0;
    let b = (b_lo * inv_fk + b_hi * fk) / 255.0;
    (r.clamp(0.0, 1.0), g.clamp(0.0, 1.0), b.clamp(0.0, 1.0))
}

/// Convert an 8-bit packed CMYK buffer to 8-bit packed sRGB using the baked
/// 4D CLUT. For each pixel: bracket the K axis into two slices, run 3D
/// tetrahedral (Kasson) interpolation on (C,M,Y) in each slice, then linearly
/// blend the two results by the K fraction.
///
/// This preserves the profile's behavior across the K axis (UCR/black-point
/// transitions) while giving image-rate throughput.
fn apply_clut4_cmyk_to_rgb(clut: &Clut4, src: &[u8], pixel_count: usize) -> Vec<u8> {
    let n = clut.grid_n as usize;
    let nm1 = (n - 1) as u32;
    let lut = clut.data.as_slice();

    // Strides in bytes within the flat LUT (K outermost, then Y, M; C innermost).
    let stride_c: usize = 3;
    let stride_m: usize = n * stride_c;
    let stride_y: usize = n * stride_m;
    let stride_k: usize = n * stride_y;

    let mut out = vec![0u8; pixel_count * 3];

    // Per-axis: quantize byte → (lo_idx, hi_idx, frac_in_0_255).
    #[inline(always)]
    fn axis(v: u8, nm1: u32) -> (usize, usize, u32) {
        let scaled = v as u32 * nm1;
        let lo = scaled / 255;
        let frac = scaled - lo * 255;
        let hi = if lo < nm1 { lo + 1 } else { lo };
        (lo as usize, hi as usize, frac)
    }

    for i in 0..pixel_count {
        let o = i * 4;
        let c = src[o];
        let m = src[o + 1];
        let y = src[o + 2];
        let k = src[o + 3];

        let (ci, ci1, fc) = axis(c, nm1);
        let (mi, mi1, fm) = axis(m, nm1);
        let (yi, yi1, fy) = axis(y, nm1);
        let (ki, ki1, fk) = axis(k, nm1);

        // Pick tetrahedron vertices and sorted weights ONCE per pixel
        // (previously done per channel — 3× waste). Kasson '94:
        //   out = V000 + (Va - V000)*w1 + (Vb - Va)*w2 + (V111 - Vb)*w3
        // with w1 >= w2 >= w3 and Va, Vb the two intermediate corners.
        let (a_dxmy, b_dxmy, w1, w2, w3) = if fc >= fm {
            if fm >= fy {
                // C,M,Y
                ((1, 0, 0), (1, 1, 0), fc, fm, fy)
            } else if fc >= fy {
                // C,Y,M
                ((1, 0, 0), (1, 0, 1), fc, fy, fm)
            } else {
                // Y,C,M
                ((0, 0, 1), (1, 0, 1), fy, fc, fm)
            }
        } else if fc >= fy {
            // M,C,Y
            ((0, 1, 0), (1, 1, 0), fm, fc, fy)
        } else if fm >= fy {
            // M,Y,C
            ((0, 1, 0), (0, 1, 1), fm, fy, fc)
        } else {
            // Y,M,C
            ((0, 0, 1), (0, 1, 1), fy, fm, fc)
        };

        // Map tetrahedron corner selector (dc, dm, dy) → LUT offset within a K slice.
        let corner = |d: (u8, u8, u8)| -> usize {
            let (dc, dm, dy) = d;
            let cx = if dc == 0 { ci } else { ci1 };
            let mx = if dm == 0 { mi } else { mi1 };
            let yx = if dy == 0 { yi } else { yi1 };
            yx * stride_y + mx * stride_m + cx * stride_c
        };

        let o000 = corner((0, 0, 0));
        let o111 = corner((1, 1, 1));
        let oa = corner(a_dxmy);
        let ob = corner(b_dxmy);

        // Two K slices, 3 channels. Compute inline (no closures, no per-channel branching).
        let base_lo = ki * stride_k;
        let base_hi = ki1 * stride_k;

        // Per-channel tetrahedral formula in integer:
        //   accum = v000*255 + (va - v000)*w1 + (vb - va)*w2 + (v111 - vb)*w3
        // accum is in units of (value * 255), in range [0, 255*255].
        let tetra_channel = |base: usize, ch: usize| -> i32 {
            let v000 = lut[base + o000 + ch] as i32;
            let va = lut[base + oa + ch] as i32;
            let vb = lut[base + ob + ch] as i32;
            let v111 = lut[base + o111 + ch] as i32;
            v000 * 255 + (va - v000) * w1 as i32 + (vb - va) * w2 as i32 + (v111 - vb) * w3 as i32
        };

        let r_lo = tetra_channel(base_lo, 0);
        let g_lo = tetra_channel(base_lo, 1);
        let b_lo = tetra_channel(base_lo, 2);
        let (r_hi, g_hi, b_hi) = if ki == ki1 {
            (r_lo, g_lo, b_lo)
        } else {
            (
                tetra_channel(base_hi, 0),
                tetra_channel(base_hi, 1),
                tetra_channel(base_hi, 2),
            )
        };

        // Linear blend across K slices and rescale to u8.
        let inv_fk = (255 - fk) as i32;
        let fk_i = fk as i32;
        let round = 255 * 255 / 2;
        let finish = |lo: i32, hi: i32| -> u8 {
            let combined = lo * inv_fk + hi * fk_i + round;
            let v = combined / (255 * 255);
            v.clamp(0, 255) as u8
        };

        let di = i * 3;
        out[di] = finish(r_lo, r_hi);
        out[di + 1] = finish(g_lo, g_hi);
        out[di + 2] = finish(b_lo, b_hi);
    }

    out
}

/// Validate a baked CLUT against the direct moxcms transform over a
/// pseudorandom sample of CMYK inputs. Reports median and max per-channel
/// deviation (in u8 units) to stderr. Invoked only when `STET_ICC_VERIFY` is
/// set in the environment.
fn verify_clut4(
    clut: &Clut4,
    transform: &(dyn TransformExecutor<u8> + Send + Sync),
    bpc_params: Option<&BpcParams>,
) {
    const N_SAMPLES: usize = 4096;
    let mut rng: u64 = 0xa8b3c4d5e6f70819;
    let mut next = || {
        rng = rng
            .wrapping_mul(6364136223846793005)
            .wrapping_add(1442695040888963407);
        rng
    };
    let mut cmyk = Vec::with_capacity(N_SAMPLES * 4);
    for _ in 0..N_SAMPLES {
        let r = next();
        cmyk.extend_from_slice(&[
            (r & 0xff) as u8,
            ((r >> 8) & 0xff) as u8,
            ((r >> 16) & 0xff) as u8,
            ((r >> 24) & 0xff) as u8,
        ]);
    }
    let mut reference = vec![0u8; N_SAMPLES * 3];
    if transform.transform(&cmyk, &mut reference).is_err() {
        eprintln!("[ICC VERIFY] reference transform failed");
        return;
    }
    // Mirror the CLUT bake's BPC step in the reference path so the
    // comparison measures interpolation error, not whether BPC was applied.
    if let Some(p) = bpc_params {
        for px in reference.chunks_exact_mut(3) {
            let out = apply_bpc_rgb_u8([px[0], px[1], px[2]], p);
            px[0] = out[0];
            px[1] = out[1];
            px[2] = out[2];
        }
    }
    let interp = apply_clut4_cmyk_to_rgb(clut, &cmyk, N_SAMPLES);
    // Per-pixel Euclidean distance in 8-bit sRGB (crude ΔE proxy).
    let mut dists: Vec<f64> = Vec::with_capacity(N_SAMPLES);
    let mut max_ch: u8 = 0;
    for i in 0..N_SAMPLES {
        let dr = interp[i * 3] as i32 - reference[i * 3] as i32;
        let dg = interp[i * 3 + 1] as i32 - reference[i * 3 + 1] as i32;
        let db = interp[i * 3 + 2] as i32 - reference[i * 3 + 2] as i32;
        let d = ((dr * dr + dg * dg + db * db) as f64).sqrt();
        dists.push(d);
        max_ch = max_ch
            .max(dr.unsigned_abs() as u8)
            .max(dg.unsigned_abs() as u8)
            .max(db.unsigned_abs() as u8);
    }
    dists.sort_by(|a, b| a.partial_cmp(b).unwrap());
    let median = dists[N_SAMPLES / 2];
    let p99 = dists[(N_SAMPLES * 99) / 100];
    let max = dists[N_SAMPLES - 1];
    eprintln!(
        "[ICC VERIFY] N=17 CLUT vs direct moxcms (sRGB u8): median={:.2}, p99={:.2}, max={:.2}, max_per_channel={}",
        median, p99, max, max_ch
    );
}

/// Search system paths for CMYK ICC profile bytes without parsing or logging.
///
/// Returns the raw bytes suitable for passing to the viewer for ICC-aware rendering.
pub fn find_system_cmyk_profile_bytes() -> Option<Arc<Vec<u8>>> {
    find_system_cmyk_profile().map(Arc::new)
}

/// Search common system paths for a CMYK ICC profile.
fn find_system_cmyk_profile() -> Option<Vec<u8>> {
    #[cfg(target_os = "linux")]
    {
        let paths = [
            "/usr/share/color/icc/ghostscript/default_cmyk.icc",
            "/usr/share/color/icc/ghostscript/ps_cmyk.icc",
            "/usr/share/color/icc/colord/FOGRA39L_coated.icc",
        ];
        for path in &paths {
            if let Ok(bytes) = std::fs::read(path) {
                return Some(bytes);
            }
        }
        // Glob for SWOP profiles
        if let Ok(entries) = glob::glob("/usr/share/color/icc/colord/SWOP*.icc") {
            for entry in entries.flatten() {
                if let Ok(bytes) = std::fs::read(&entry) {
                    return Some(bytes);
                }
            }
        }
    }

    #[cfg(target_os = "macos")]
    {
        let dirs = [
            "/Library/ColorSync/Profiles",
            "/System/Library/ColorSync/Profiles",
        ];
        if let Some(home) = std::env::var_os("HOME") {
            let home_dir = std::path::PathBuf::from(home).join("Library/ColorSync/Profiles");
            if let Some(bytes) = scan_dir_for_cmyk_icc(&home_dir) {
                return Some(bytes);
            }
        }
        for dir in &dirs {
            if let Some(bytes) = scan_dir_for_cmyk_icc(std::path::Path::new(dir)) {
                return Some(bytes);
            }
        }
    }

    #[cfg(target_os = "windows")]
    {
        if let Some(sysroot) = std::env::var_os("SYSTEMROOT") {
            let dir = std::path::PathBuf::from(sysroot).join("System32/spool/drivers/color");
            if let Some(bytes) = scan_dir_for_cmyk_icc(&dir) {
                return Some(bytes);
            }
        }
    }

    None
}

/// Scan a directory for ICC files with CMYK color space.
#[cfg(any(target_os = "macos", target_os = "windows"))]
fn scan_dir_for_cmyk_icc(dir: &std::path::Path) -> Option<Vec<u8>> {
    let entries = std::fs::read_dir(dir).ok()?;
    for entry in entries.flatten() {
        let path = entry.path();
        let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("");
        if ext.eq_ignore_ascii_case("icc") || ext.eq_ignore_ascii_case("icm") {
            if let Ok(bytes) = std::fs::read(&path) {
                // Check ICC header: color space at offset 16, 'CMYK' = 0x434D594B
                if bytes.len() >= 20 && &bytes[16..20] == b"CMYK" {
                    return Some(bytes);
                }
            }
        }
    }
    None
}

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

    #[test]
    fn test_icc_cache_new() {
        let cache = IccCache::new();
        assert!(cache.default_cmyk_hash.is_none());
        assert!(cache.profiles.is_empty());
        assert_eq!(cache.bpc_mode(), BpcMode::Auto);
    }

    #[test]
    fn test_icc_cache_options_default_matches_new() {
        let cache = IccCache::new_with_options(IccCacheOptions::default());
        assert_eq!(cache.bpc_mode(), BpcMode::Auto);
        assert!(cache.default_cmyk_hash.is_none());
    }

    #[test]
    fn test_icc_cache_options_bpc_off() {
        let cache = IccCache::new_with_options(IccCacheOptions {
            bpc_mode: BpcMode::Off,
            source_cmyk_profile: None,
        });
        assert_eq!(cache.bpc_mode(), BpcMode::Off);
        assert!(!cache.bpc_mode().is_enabled());
    }

    #[test]
    fn test_icc_cache_options_preloads_cmyk_profile() {
        // Skip when no system CMYK profile is available.
        let Some(cmyk_bytes) = find_system_cmyk_profile() else {
            return;
        };
        let cache = IccCache::new_with_options(IccCacheOptions {
            bpc_mode: BpcMode::On,
            source_cmyk_profile: Some(cmyk_bytes.clone()),
        });
        assert!(cache.default_cmyk_hash().is_some());
        assert_eq!(cache.bpc_mode(), BpcMode::On);
    }

    #[test]
    fn test_bpc_darkens_pure_k_per_color() {
        // Skip when no system CMYK profile is available.
        let Some(cmyk_bytes) = find_system_cmyk_profile() else {
            return;
        };

        // Without BPC: K=1 through default_cmyk.icc lands near RGB(55, 53, 53)
        // — the profile's as-mapped black projected through moxcms's sRGB B2A.
        let mut off = IccCache::new_with_options(IccCacheOptions {
            bpc_mode: BpcMode::Off,
            source_cmyk_profile: Some(cmyk_bytes.clone()),
        });
        let off_rgb = off.convert_cmyk(0.0, 0.0, 0.0, 1.0).unwrap();

        // With BPC: K=1 must land significantly darker. Adobe Acrobat (lcms2)
        // produces RGB(35, 31, 32). moxcms's sRGB B2A handles very-dark XYZ
        // slightly differently from lcms2, so our post-correct lands a few
        // levels brighter than Acrobat — the meaningful invariant is "K=1 is
        // visibly darker than the no-BPC baseline by a substantial margin."
        let mut on = IccCache::new_with_options(IccCacheOptions {
            bpc_mode: BpcMode::On,
            source_cmyk_profile: Some(cmyk_bytes),
        });
        let on_rgb = on.convert_cmyk(0.0, 0.0, 0.0, 1.0).unwrap();

        // Precondition: this test only exercises BPC's darkening effect, which
        // requires a profile whose black point has non-zero luminance. Some
        // system-supplied CMYK profiles (e.g. macOS's default ColorSync CMYK)
        // already map K=1 to (near-)zero XYZ, so BPC has nothing to correct
        // and off == on. Skip in that case — there's no regression to anchor
        // here, just a profile that doesn't benefit from BPC.
        if (on_rgb.1 - off_rgb.1).abs() < 0.005 {
            eprintln!(
                "Skipping: system CMYK profile's black point is already ~zero; \
                 BPC is a no-op here. off={off_rgb:?} on={on_rgb:?}"
            );
            return;
        }

        assert!(
            on_rgb.1 + 0.03 < off_rgb.1,
            "BPC should darken K=1 by ≥0.03 (~8 RGB levels): off={off_rgb:?} on={on_rgb:?}"
        );
        // And the resulting RGB should be in the "deep gray" range — well
        // under 0.25 (RGB ≤ ~64) on every channel.
        assert!(
            on_rgb.0 < 0.25 && on_rgb.1 < 0.25 && on_rgb.2 < 0.25,
            "Expected deep gray after BPC, got {on_rgb:?}"
        );
    }

    #[test]
    fn test_bpc_white_anchored_per_color() {
        // Skip when no system CMYK profile is available.
        let Some(cmyk_bytes) = find_system_cmyk_profile() else {
            return;
        };
        let mut cache = IccCache::new_with_options(IccCacheOptions {
            bpc_mode: BpcMode::On,
            source_cmyk_profile: Some(cmyk_bytes),
        });
        // CMYK white (no ink) must still render as sRGB white under BPC.
        let (r, g, b) = cache.convert_cmyk(0.0, 0.0, 0.0, 0.0).unwrap();
        assert!(r > 0.99 && g > 0.99 && b > 0.99, "({r}, {g}, {b})");
    }

    #[test]
    fn test_bpc_image_clut_path_darkens_pure_k() {
        // Skip when no system CMYK profile is available.
        let Some(cmyk_bytes) = find_system_cmyk_profile() else {
            return;
        };

        // Build a 1-pixel CMYK image at K=1 and route it through the CLUT.
        // Without BPC vs with BPC, the K=1 pixel must shift darker, mirroring
        // the per-color path behaviour.
        let off = IccCache::new_with_options(IccCacheOptions {
            bpc_mode: BpcMode::Off,
            source_cmyk_profile: Some(cmyk_bytes.clone()),
        });
        let on = IccCache::new_with_options(IccCacheOptions {
            bpc_mode: BpcMode::On,
            source_cmyk_profile: Some(cmyk_bytes),
        });
        let off_hash = *off.default_cmyk_hash().unwrap();
        let on_hash = *on.default_cmyk_hash().unwrap();

        let pixel = [0u8, 0, 0, 255]; // C=0 M=0 Y=0 K=255
        let off_rgb = off.convert_image_8bit(&off_hash, &pixel, 1).unwrap();
        let on_rgb = on.convert_image_8bit(&on_hash, &pixel, 1).unwrap();

        // Precondition, same as `test_bpc_darkens_pure_k_per_color`: BPC only
        // shifts pixels when the profile's black point has non-zero luminance.
        // Skip when the system profile already maps K=1 to near-zero XYZ.
        if (on_rgb[1] as i32 - off_rgb[1] as i32).abs() <= 1 {
            eprintln!(
                "Skipping: system CMYK profile's black point is already ~zero; \
                 BPC is a no-op here. off={off_rgb:?} on={on_rgb:?}"
            );
            return;
        }

        // BPC must darken the green channel by ≥8 RGB levels (mirrors the
        // per-color path's anchor in test_bpc_darkens_pure_k_per_color).
        assert!(
            (on_rgb[1] as i32) + 8 < (off_rgb[1] as i32),
            "CLUT BPC should darken K=1 image green by ≥8 levels: off={off_rgb:?} on={on_rgb:?}"
        );
        // And land in the deep-gray range.
        assert!(
            on_rgb[0] < 64 && on_rgb[1] < 64 && on_rgb[2] < 64,
            "Expected deep gray after CLUT BPC, got {on_rgb:?}"
        );
    }

    #[test]
    fn test_bpc_off_image_matches_per_color_off() {
        // With --bpc off, the bulk image path's K=1 output must match the
        // per-color path's K=1 output (within u8 quantization). Anchors that
        // disabling BPC reproduces stet's pre-fix behaviour bit-for-bit on
        // the dominant CMYK image path.
        let Some(cmyk_bytes) = find_system_cmyk_profile() else {
            return;
        };
        let mut cache = IccCache::new_with_options(IccCacheOptions {
            bpc_mode: BpcMode::Off,
            source_cmyk_profile: Some(cmyk_bytes),
        });
        let hash = *cache.default_cmyk_hash().unwrap();

        let pixel = [0u8, 0, 0, 255];
        let img = cache.convert_image_8bit(&hash, &pixel, 1).unwrap();
        let (r, g, b) = cache.convert_cmyk(0.0, 0.0, 0.0, 1.0).unwrap();
        let pc = [
            (r * 255.0).round() as i32,
            (g * 255.0).round() as i32,
            (b * 255.0).round() as i32,
        ];
        // CLUT interpolation drift can introduce ±1 vs the direct f64 path.
        assert!((img[0] as i32 - pc[0]).abs() <= 2, "img={img:?} pc={pc:?}");
        assert!((img[1] as i32 - pc[1]).abs() <= 2, "img={img:?} pc={pc:?}");
        assert!((img[2] as i32 - pc[2]).abs() <= 2, "img={img:?} pc={pc:?}");
    }

    #[test]
    fn test_register_invalid_profile() {
        let mut cache = IccCache::new();
        assert!(cache.register_profile(b"not a valid ICC profile").is_none());
    }

    #[test]
    fn test_srgb_identity_transform() {
        // Create an sRGB profile, register it, and verify identity-ish conversion
        let srgb = ColorProfile::new_srgb();
        let bytes = srgb.encode().unwrap();
        let mut cache = IccCache::new();
        let hash = cache.register_profile(&bytes).unwrap();

        // Red should stay approximately red
        let (r, g, b) = cache.convert_color(&hash, &[1.0, 0.0, 0.0]).unwrap();
        assert!((r - 1.0).abs() < 0.02, "r={r}");
        assert!(g < 0.02, "g={g}");
        assert!(b < 0.02, "b={b}");

        // White
        let (r, g, b) = cache.convert_color(&hash, &[1.0, 1.0, 1.0]).unwrap();
        assert!((r - 1.0).abs() < 0.02);
        assert!((g - 1.0).abs() < 0.02);
        assert!((b - 1.0).abs() < 0.02);
    }

    #[test]
    fn test_srgb_image_transform() {
        let srgb = ColorProfile::new_srgb();
        let bytes = srgb.encode().unwrap();
        let mut cache = IccCache::new();
        let hash = cache.register_profile(&bytes).unwrap();

        // 2 pixels: red, green
        let src = [255u8, 0, 0, 0, 255, 0];
        let result = cache.convert_image_8bit(&hash, &src, 2).unwrap();
        assert_eq!(result.len(), 6);
        // Red pixel should be approximately (255, 0, 0)
        assert!(result[0] > 240);
        assert!(result[1] < 15);
        assert!(result[2] < 15);
    }

    #[test]
    fn test_convert_rgb_to_cmyk_readonly() {
        // Skip when no system CMYK profile is available (CI without ICC packs).
        let Some(cmyk_bytes) = find_system_cmyk_profile() else {
            return;
        };
        let mut cache = IccCache::new();
        let hash = cache.register_profile(&cmyk_bytes).unwrap();
        cache.set_default_cmyk_hash(hash);

        // Before pre-warming the reverse transform must be unavailable.
        assert!(cache.convert_rgb_to_cmyk_readonly(0.0, 0.0, 0.0).is_none());

        cache.prepare_reverse_cmyk();

        // Pure black sRGB should land deep in K (any reasonable CMYK profile
        // produces a high K component).
        let cmyk = cache
            .convert_rgb_to_cmyk_readonly(0.0, 0.0, 0.0)
            .expect("reverse transform should be available after prepare");
        assert!(
            cmyk[3] > 0.5,
            "expected K>0.5 for sRGB black, got cmyk={cmyk:?}"
        );

        // Pure white sRGB should land near (0,0,0,0) — minimal ink.
        let cmyk = cache
            .convert_rgb_to_cmyk_readonly(1.0, 1.0, 1.0)
            .expect("reverse transform should be available");
        for (i, v) in cmyk.iter().enumerate() {
            assert!(*v < 0.05, "expected near-zero ink at chan {i}, got {v}");
        }
    }

    /// White CMYK (0,0,0,0) routed through the perceptual CLUT must land at
    /// pure white sRGB. Catches scaling errors in the PCS-Lab decode (the
    /// most likely place to introduce a uniform brightness shift).
    #[test]
    fn test_perceptual_clut_white_anchor() {
        let Some(cmyk_bytes) = find_system_cmyk_profile() else {
            return;
        };
        let mut cache = IccCache::new_with_options(IccCacheOptions {
            bpc_mode: BpcMode::Off,
            source_cmyk_profile: Some(cmyk_bytes),
        });
        let rgb = cache.convert_cmyk(0.0, 0.0, 0.0, 0.0).unwrap();
        // Tolerate a few u8 levels of grid-interpolation drift; the bound
        // catches order-of-magnitude bugs (a ~0.5x scale would land at ~127).
        assert!(
            rgb.0 > 0.97 && rgb.1 > 0.97 && rgb.2 > 0.97,
            "CMYK white should map near sRGB white, got {rgb:?}"
        );
    }

    /// Single-color CLUT lookup must agree with bulk image conversion to
    /// within u8 quantization on the same input. Anchors the requirement
    /// that flat CMYK fills match adjacent gradient stops byte-for-byte.
    #[test]
    fn test_perceptual_clut_single_matches_bulk() {
        let Some(cmyk_bytes) = find_system_cmyk_profile() else {
            return;
        };
        let mut cache = IccCache::new_with_options(IccCacheOptions {
            bpc_mode: BpcMode::On,
            source_cmyk_profile: Some(cmyk_bytes),
        });
        let hash = *cache.default_cmyk_hash().unwrap();
        // A handful of saturated and midtone CMYK samples.
        let samples: &[(u8, u8, u8, u8)] = &[
            (0, 0, 0, 0),
            (255, 0, 0, 0),
            (0, 255, 0, 0),
            (0, 0, 255, 0),
            (0, 0, 0, 255),
            (38, 255, 255, 0), // ≈ (0.15, 1.0, 1.0, 0.0) — the GWG demo input
            (128, 128, 128, 0),
        ];
        let pixels: Vec<u8> = samples
            .iter()
            .flat_map(|&(c, m, y, k)| [c, m, y, k])
            .collect();
        let bulk = cache
            .convert_image_8bit(&hash, &pixels, samples.len())
            .unwrap();
        for (i, &(c, m, y, k)) in samples.iter().enumerate() {
            let single = cache
                .convert_color(
                    &hash,
                    &[
                        c as f64 / 255.0,
                        m as f64 / 255.0,
                        y as f64 / 255.0,
                        k as f64 / 255.0,
                    ],
                )
                .unwrap();
            let single_u8 = [
                (single.0 * 255.0).round() as i32,
                (single.1 * 255.0).round() as i32,
                (single.2 * 255.0).round() as i32,
            ];
            let b = &bulk[i * 3..i * 3 + 3];
            for ch in 0..3 {
                let delta = (single_u8[ch] - b[ch] as i32).abs();
                assert!(
                    delta <= 2,
                    "single vs bulk mismatch at sample {i} chan {ch}: \
                     single={single_u8:?} bulk={:?} delta={delta}",
                    [b[0], b[1], b[2]]
                );
            }
        }
    }
}