fovea-io 0.1.1

Feature-gated PNG, JPEG, and BMP codecs for fovea images
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
//! JPEG decoding and encoding.
//!
//! # Decoding
//!
//! The primary entry point is [`decode`], which takes a byte slice and returns
//! a [`JpegDecoded`] — a struct containing the pixel data as a [`JpegImage`]
//! and ancillary information as [`JpegMetadata`].
//!
//! For streaming sources, use [`decode_reader`] which accepts any `impl Read`.
//! Both paths produce identical results — `decode_reader` buffers the stream
//! internally and delegates to `decode`.
//!
//! | JPEG configuration         | [`JpegImage`] variant | Pixel type      |
//! |----------------------------|-----------------------|-----------------|
//! | 8-bit grayscale            | `SrgbMono8`           | [`SrgbMono8`]   |
//! | 12-bit grayscale (ext.)    | `SrgbMono16`          | [`SrgbMono16`]  |
//! | 8-bit RGB                  | `Srgb8`               | [`Srgb8`]       |
//! | CMYK                       | —                     | rejected        |
//!
//! # Encoding
//!
//! Use [`encode`] (to `Vec<u8>`) or [`encode_writer`] (to any `impl Write`)
//! to produce JPEG data.  Only pixel types implementing the sealed
//! [`JpegPixel`] trait can be encoded — currently [`SrgbMono8`] and
//! [`Srgb8`].  Attempting to encode other types (e.g. `Rgb8`, `Srgba8`)
//! is a compile-time error.
//!
//! [`encode_jpeg_image`] dispatches over [`JpegImage`] variants for
//! convenient roundtripping.
//!
//! # EXIF parsing
//!
//! A curated set of ~15 EXIF tags is parsed into [`JpegExifInfo`] using a
//! built-in TIFF IFD parser with no external dependencies.  Tags extracted:
//!
//! - **IFD0:** orientation, make, model, software, datetime
//! - **EXIF sub-IFD:** exposure time, f-number, ISO, focal length,
//!   datetime original
//! - **GPS sub-IFD:** latitude, longitude, altitude (converted to decimal
//!   degrees / metres)
//!
//! Raw EXIF bytes are also retained in [`JpegMetadata::raw_exif`] for users
//! who need vendor-specific or niche tags via a dedicated EXIF library.
//!
//! # Design rationale
//!
//! - **`JpegImage` is exhaustive** (no `#[non_exhaustive]`).  It is the spec
//!   sheet for what a JPEG file can produce.  Adding a variant (e.g. CMYK)
//!   is a genuine semantic change that callers must handle — a compile error
//!   is the correct response.
//!
//! - **`JpegDecoded` is `#[non_exhaustive]`**.  It is a return-only struct
//!   that may gain fields (e.g. decode warnings) in the future without
//!   breaking downstream code.
//!
//! - **Always sRGB.**  JPEG is defined as sRGB by JFIF 1.02.  Even when an
//!   ICC profile is embedded, decoded sample values are gamma-encoded.
//!   Returning linear pixel types would be a type-level lie — the compiler
//!   would then allow linear-math operations on gamma-encoded data,
//!   producing silently wrong results.
//!
//! - **No CMYK.**  CMYK → sRGB conversion requires an ICC profile and a
//!   colour management engine.  Naive conversion is incorrect for most
//!   real-world CMYK profiles.  CMYK JPEGs are rejected with
//!   [`IoError::UnsupportedFeature`].
//!
//! - **EXIF is parsed into typed fields**, not returned as an opaque blob.
//!   Raw EXIF bytes are also retained for users who need vendor-specific or
//!   niche tags.
//!
//! - **Orientation is NOT auto-applied.**  EXIF orientation is metadata, not
//!   pixel data.  Auto-applying it would mean the returned image silently
//!   differs from the raw JPEG samples — violating explicit data layout.
//!
//! - **`Srgba8` is excluded from [`JpegPixel`].**  JPEG has no alpha
//!   channel.  Silently dropping alpha would be a lossy conversion hidden
//!   inside the I/O layer, violating design principle §4 (conversions are
//!   named).  Strip alpha explicitly before encoding.

use crate::IoError;
use fovea::image::{Image, ImageView};
use fovea::pixel::{Srgb8, SrgbMono8, SrgbMono16};

// ═══════════════════════════════════════════════════════════════════════════════
// JpegImage — per-codec exhaustive output enum
// ═══════════════════════════════════════════════════════════════════════════════

/// Decoded JPEG pixel data.
///
/// Each variant corresponds to a JPEG pixel format decoded by `jpeg-decoder`.
/// All variants use sRGB pixel types because JPEG is inherently gamma-encoded
/// (JFIF 1.02 defines JPEG as sRGB).
///
/// | `jpeg-decoder` format | Channels | Variant      | Pixel type    |
/// |-----------------------|----------|--------------|---------------|
/// | `PixelFormat::L8`     | 1 × u8   | `SrgbMono8`  | `SrgbMono8`   |
/// | `PixelFormat::L16`    | 1 × u16  | `SrgbMono16` | `SrgbMono16`  |
/// | `PixelFormat::RGB24`  | 3 × u8   | `Srgb8`      | `Srgb8`       |
/// | `PixelFormat::CMYK32` | 4 × u8   | —            | rejected      |
///
/// This enum is deliberately **not** `#[non_exhaustive]`.  It is the spec
/// sheet; adding a variant is semver-major.
///
/// The `Debug` impl shows the variant name and image dimensions (e.g.
/// `Srgb8(320x240)`) without dumping pixel data.
///
/// # Examples
///
/// ```
/// # use fovea::image::Image;
/// # use fovea::pixel::{Srgb8, SrgbMono8, SrgbMono16};
/// use fovea_io::jpeg::JpegImage;
///
/// // Construct each variant:
/// let mono8 = JpegImage::SrgbMono8(Image::fill(2, 2, SrgbMono8::new(128)));
/// let mono16 = JpegImage::SrgbMono16(Image::fill(4, 3, SrgbMono16::new(1000)));
/// let rgb = JpegImage::Srgb8(Image::fill(320, 240, Srgb8::new(0, 0, 0)));
///
/// // Debug shows variant + dimensions, not pixel data:
/// assert_eq!(format!("{:?}", mono8), "SrgbMono8(2x2)");
/// assert_eq!(format!("{:?}", mono16), "SrgbMono16(4x3)");
/// assert_eq!(format!("{:?}", rgb), "Srgb8(320x240)");
/// ```
pub enum JpegImage {
    /// 8-bit sRGB grayscale (JFIF luminance-only).
    SrgbMono8(Image<SrgbMono8>),
    /// 16-bit sRGB grayscale (12-bit JPEG extended, decoded to 16-bit).
    SrgbMono16(Image<SrgbMono16>),
    /// 8-bit sRGB truecolour (the overwhelmingly common case).
    Srgb8(Image<Srgb8>),
}

impl JpegImage {
    /// Width in pixels, regardless of variant.
    ///
    /// # Examples
    ///
    /// ```
    /// use fovea_io::jpeg::JpegImage;
    /// use fovea::image::Image;
    /// use fovea::pixel::Srgb8;
    ///
    /// let img = JpegImage::Srgb8(Image::fill(320, 240, Srgb8::new(0, 0, 0)));
    /// assert_eq!(img.width(), 320);
    /// ```
    #[must_use]
    pub fn width(&self) -> usize {
        use fovea::image::ImageView;
        match self {
            JpegImage::SrgbMono8(img) => img.width(),
            JpegImage::SrgbMono16(img) => img.width(),
            JpegImage::Srgb8(img) => img.width(),
        }
    }

    /// Height in pixels, regardless of variant.
    #[must_use]
    pub fn height(&self) -> usize {
        use fovea::image::ImageView;
        match self {
            JpegImage::SrgbMono8(img) => img.height(),
            JpegImage::SrgbMono16(img) => img.height(),
            JpegImage::Srgb8(img) => img.height(),
        }
    }

    /// Image size (`width × height`), regardless of variant.
    ///
    /// # Examples
    ///
    /// ```
    /// use fovea_io::jpeg::JpegImage;
    /// use fovea::image::Image;
    /// use fovea::pixel::Srgb8;
    ///
    /// let img = JpegImage::Srgb8(Image::fill(320, 240, Srgb8::new(0, 0, 0)));
    /// let sz = img.size();
    /// assert_eq!(sz.width, 320);
    /// assert_eq!(sz.height, 240);
    /// ```
    #[must_use]
    pub fn size(&self) -> fovea::Size {
        use fovea::image::ImageView;
        match self {
            JpegImage::SrgbMono8(img) => img.size(),
            JpegImage::SrgbMono16(img) => img.size(),
            JpegImage::Srgb8(img) => img.size(),
        }
    }
}

impl std::fmt::Debug for JpegImage {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            JpegImage::SrgbMono8(img) => {
                write!(f, "SrgbMono8({}x{})", img.width(), img.height())
            }
            JpegImage::SrgbMono16(img) => {
                write!(f, "SrgbMono16({}x{})", img.width(), img.height())
            }
            JpegImage::Srgb8(img) => write!(f, "Srgb8({}x{})", img.width(), img.height()),
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// JpegExifInfo — curated EXIF tag fields
// ═══════════════════════════════════════════════════════════════════════════════

/// A curated set of EXIF tags parsed into typed Rust fields.
///
/// The selection covers tags that matter for image processing, display
/// correctness, provenance, and scientific/industrial workflows.  All fields
/// are `Option<T>` because any EXIF tag may be absent or malformed.
///
/// # Design choices
///
/// - **Rationals stay as `(u32, u32)` tuples** for exposure, f-number, focal
///   length.  Users who want `f64` can compute `num as f64 / den as f64`.
///
/// - **GPS coordinates are `f64` decimal degrees.**  `f64` gives
///   sub-millimetre precision and matches standard geospatial representations.
///
/// - **Timestamps stay as `String`.** EXIF timestamps follow `"YYYY:MM:DD
///   HH:MM:SS"`.  A `String` preserves the exact EXIF value.
///
/// # Examples
///
/// ```ignore
/// // Construction requires being inside the defining crate due to
/// // #[non_exhaustive].  In practice, obtain via `jpeg::decode()`.
/// use fovea_io::jpeg::JpegExifInfo;
///
/// let info = JpegExifInfo {
///     orientation: Some(1),
///     datetime: Some("2025:01:15 12:30:00".to_string()),
///     camera_make: Some("Canon".to_string()),
///     ..Default::default()
/// };
/// assert_eq!(info.orientation, Some(1));
/// assert_eq!(info.camera_make.as_deref(), Some("Canon"));
/// ```
#[non_exhaustive]
#[derive(Debug, Clone, Default, PartialEq)]
pub struct JpegExifInfo {
    // ── Display correctness ──────────────────────────────────────────
    /// EXIF orientation tag (0x0112).  Values 1–8.
    /// Describes how the stored pixel grid relates to the intended
    /// display orientation (rotation + mirror).
    pub orientation: Option<u8>,

    // ── Timestamps ───────────────────────────────────────────────────
    /// File modification time (IFD0 tag 0x0132).
    /// Format: `"YYYY:MM:DD HH:MM:SS"` per EXIF spec.
    pub datetime: Option<String>,
    /// Original capture time (EXIF sub-IFD tag 0x9003).
    /// This is the shutter-release moment — more reliable than `datetime`.
    pub datetime_original: Option<String>,

    // ── Camera identification ────────────────────────────────────────
    /// Camera manufacturer (IFD0 tag 0x010F).
    pub camera_make: Option<String>,
    /// Camera model (IFD0 tag 0x0110).
    pub camera_model: Option<String>,
    /// Software that produced the file (IFD0 tag 0x0131).
    pub software: Option<String>,

    // ── Exposure parameters (scientific / industrial) ────────────────
    /// Exposure time in seconds as a rational (tag 0x829A).
    /// E.g. `(1, 250)` means 1/250 s.
    pub exposure_time: Option<(u32, u32)>,
    /// F-number as a rational (tag 0x829D).
    /// E.g. `(28, 10)` means f/2.8.
    pub f_number: Option<(u32, u32)>,
    /// ISO speed (tag 0x8827).
    pub iso_speed: Option<u16>,
    /// Focal length in mm as a rational (tag 0x920A).
    /// E.g. `(50, 1)` means 50 mm.
    pub focal_length: Option<(u32, u32)>,

    // ── Geospatial ───────────────────────────────────────────────────
    /// GPS latitude in decimal degrees.
    /// Positive = North, negative = South.
    /// Converted from EXIF DMS rationals + N/S reference.
    pub gps_latitude: Option<f64>,
    /// GPS longitude in decimal degrees.
    /// Positive = East, negative = West.
    /// Converted from EXIF DMS rationals + E/W reference.
    pub gps_longitude: Option<f64>,
    /// GPS altitude in metres.
    /// Positive = above sea level, negative = below.
    /// Converted from EXIF rational + altitude reference byte.
    pub gps_altitude: Option<f64>,
}

// ═══════════════════════════════════════════════════════════════════════════════
// JpegColorSpace — what the colour-space markers told us
// ═══════════════════════════════════════════════════════════════════════════════

/// Colour-space signalling extracted from a JPEG file.
///
/// JPEG has fewer colour-space signalling mechanisms than PNG.  The pixel
/// type in [`JpegImage`] already encodes the transfer-function assumption
/// (always sRGB).  This enum signals whether an ICC profile is present.
///
/// This enum is deliberately **not** `#[non_exhaustive]` — it is a spec
/// sheet.  Adding Adobe RGB signalling (APP14 marker) would be a genuine
/// semantic change requiring a semver-major bump.
///
/// # Examples
///
/// ```
/// use fovea_io::jpeg::JpegColorSpace;
///
/// let cs = JpegColorSpace::Srgb;
/// assert_eq!(cs, JpegColorSpace::Srgb);
/// assert_ne!(cs, JpegColorSpace::IccTagged);
///
/// // Copy semantics:
/// let cs2 = cs;
/// assert_eq!(cs, cs2);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum JpegColorSpace {
    /// Standard JFIF — sRGB assumed (no embedded ICC profile).
    Srgb,
    /// An ICC profile is present (see `JpegMetadata::icc_profile`).
    IccTagged,
}

// ═══════════════════════════════════════════════════════════════════════════════
// JpegPixelDensity — JFIF APP0 pixel density
// ═══════════════════════════════════════════════════════════════════════════════

/// Pixel density information from the JFIF APP0 marker.
///
/// JFIF defines three kinds of density information: DPI, dots per centimetre,
/// and unitless aspect ratio.
///
/// # Examples
///
/// ```
/// use fovea_io::jpeg::JpegPixelDensity;
///
/// let dpi = JpegPixelDensity::Dpi { x: 300, y: 300 };
/// let dpcm = JpegPixelDensity::Dpcm { x: 118, y: 118 };
/// let aspect = JpegPixelDensity::AspectRatio { x: 1, y: 1 };
///
/// assert_eq!(dpi, JpegPixelDensity::Dpi { x: 300, y: 300 });
/// assert_ne!(dpi, dpcm);
///
/// // Copy semantics:
/// let dpi2 = dpi;
/// assert_eq!(dpi, dpi2);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum JpegPixelDensity {
    /// Pixels per inch.
    Dpi {
        /// Horizontal density.
        x: u16,
        /// Vertical density.
        y: u16,
    },
    /// Pixels per centimetre.
    Dpcm {
        /// Horizontal density.
        x: u16,
        /// Vertical density.
        y: u16,
    },
    /// Aspect ratio only (unitless).
    AspectRatio {
        /// Horizontal aspect.
        x: u16,
        /// Vertical aspect.
        y: u16,
    },
}

// ═══════════════════════════════════════════════════════════════════════════════
// JpegBitDepth — source sample precision
// ═══════════════════════════════════════════════════════════════════════════════

/// Source bit depth of a JPEG file.
///
/// JPEG supports exactly two sample precisions: 8-bit (baseline/progressive)
/// and 12-bit (extended).  A `u8` field would admit 254 invalid states.
/// Per design principle §1 (types are the spec), a two-valued domain is a
/// two-variant enum.
///
/// # Examples
///
/// ```
/// use fovea_io::jpeg::JpegBitDepth;
///
/// let depth = JpegBitDepth::Eight;
/// assert_eq!(depth, JpegBitDepth::Eight);
/// assert_ne!(depth, JpegBitDepth::Twelve);
///
/// // Copy semantics:
/// let depth2 = depth;
/// assert_eq!(depth, depth2);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum JpegBitDepth {
    /// Baseline / progressive JPEG — 8-bit samples.
    Eight,
    /// JPEG Extended — 12-bit samples (decoded to 16-bit by `jpeg-decoder`).
    Twelve,
}

// ═══════════════════════════════════════════════════════════════════════════════
// JpegMetadata — ancillary information beyond pixel data
// ═══════════════════════════════════════════════════════════════════════════════

/// Ancillary metadata extracted from a JPEG file.
///
/// Returned as part of [`JpegDecoded`].  Fields are optional — only populated
/// when the corresponding markers exist in the file.
///
/// # Examples
///
/// ```ignore
/// // Construction requires being inside the defining crate due to
/// // #[non_exhaustive].  In practice, obtain via `jpeg::decode()`.
/// use fovea_io::jpeg::{JpegMetadata, JpegColorSpace, JpegBitDepth};
///
/// let meta = JpegMetadata {
///     exif: None,
///     raw_exif: None,
///     icc_profile: None,
///     pixel_density: None,
///     comments: vec!["Hello, world!".to_string()],
///     source_bit_depth: JpegBitDepth::Eight,
///     color_space: JpegColorSpace::Srgb,
/// };
/// assert_eq!(meta.source_bit_depth, JpegBitDepth::Eight);
/// assert_eq!(meta.comments.len(), 1);
/// ```
#[non_exhaustive]
#[derive(Debug, Clone)]
pub struct JpegMetadata {
    /// Parsed EXIF information (curated tag subset).
    pub exif: Option<JpegExifInfo>,
    /// Raw EXIF bytes from the APP1 marker, for users who need niche tags.
    pub raw_exif: Option<Box<[u8]>>,
    /// ICC profile bytes from the APP2 marker.
    pub icc_profile: Option<Box<[u8]>>,
    /// Pixel density from the JFIF APP0 marker.
    pub pixel_density: Option<JpegPixelDensity>,
    /// Comment strings from COM markers.
    pub comments: Vec<String>,
    /// Source bit depth — either 8-bit (baseline/progressive) or 12-bit (extended).
    pub source_bit_depth: JpegBitDepth,
    /// Colour-space signalling.
    pub color_space: JpegColorSpace,
}

// ═══════════════════════════════════════════════════════════════════════════════
// JpegDecoded — the complete decode result
// ═══════════════════════════════════════════════════════════════════════════════

/// The complete result of decoding a JPEG file.
///
/// Contains both the pixel data ([`JpegImage`]) and ancillary metadata
/// ([`JpegMetadata`]).  This struct is `#[non_exhaustive]` so that new
/// fields (e.g. decode warnings) can be added without a semver-major bump.
///
/// # Examples
///
/// ```ignore
/// // Construction requires being inside the defining crate due to
/// // #[non_exhaustive].  In practice, obtain via `jpeg::decode()`.
/// # use fovea::image::Image;
/// # use fovea::pixel::Srgb8;
/// use fovea_io::jpeg::{JpegDecoded, JpegImage, JpegMetadata, JpegColorSpace, JpegBitDepth};
///
/// let decoded = JpegDecoded {
///     image: JpegImage::Srgb8(Image::fill(1, 1, Srgb8::new(0, 0, 0))),
///     metadata: JpegMetadata {
///         exif: None,
///         raw_exif: None,
///         icc_profile: None,
///         pixel_density: None,
///         comments: vec![],
///         source_bit_depth: JpegBitDepth::Eight,
///         color_space: JpegColorSpace::Srgb,
///     },
/// };
/// // Fields are directly accessible:
/// let _img = decoded.image;
/// let _meta = decoded.metadata;
/// ```
#[derive(Debug)]
#[non_exhaustive]
pub struct JpegDecoded {
    /// The decoded pixel data.
    pub image: JpegImage,
    /// Ancillary metadata (EXIF, ICC, comments, …).
    pub metadata: JpegMetadata,
}

// ═══════════════════════════════════════════════════════════════════════════════
// TIFF / EXIF internals — private helpers for parsing EXIF APP1 data
// ═══════════════════════════════════════════════════════════════════════════════

/// Byte order of a TIFF stream.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ByteOrder {
    /// Little-endian (`II` — Intel).
    Little,
    /// Big-endian (`MM` — Motorola).
    Big,
}

/// Bounds-checked reader over a TIFF byte stream with a fixed byte order.
///
/// All offset-based accessors return `Option<T>` — out-of-bounds reads
/// produce `None` rather than panicking.  No unsafe code.
struct TiffReader<'a> {
    data: &'a [u8],
    order: ByteOrder,
}

impl<'a> TiffReader<'a> {
    /// Create a new reader over `data` with the given byte order.
    fn new(data: &'a [u8], order: ByteOrder) -> Self {
        Self { data, order }
    }

    /// Total length of the underlying data.
    #[allow(dead_code)]
    fn len(&self) -> usize {
        self.data.len()
    }

    /// Read a single byte at `offset`.
    fn u8_at(&self, offset: usize) -> Option<u8> {
        self.data.get(offset).copied()
    }

    /// Read a 16-bit unsigned integer at `offset`, respecting byte order.
    fn u16_at(&self, offset: usize) -> Option<u16> {
        let bytes: &[u8] = self.data.get(offset..offset.checked_add(2)?)?;
        let arr: [u8; 2] = [bytes[0], bytes[1]];
        Some(match self.order {
            ByteOrder::Little => u16::from_le_bytes(arr),
            ByteOrder::Big => u16::from_be_bytes(arr),
        })
    }

    /// Read a 32-bit unsigned integer at `offset`, respecting byte order.
    fn u32_at(&self, offset: usize) -> Option<u32> {
        let bytes: &[u8] = self.data.get(offset..offset.checked_add(4)?)?;
        let arr: [u8; 4] = [bytes[0], bytes[1], bytes[2], bytes[3]];
        Some(match self.order {
            ByteOrder::Little => u32::from_le_bytes(arr),
            ByteOrder::Big => u32::from_be_bytes(arr),
        })
    }

    /// Read a TIFF RATIONAL (two consecutive u32s: numerator, denominator)
    /// at `offset`, respecting byte order.
    fn rational_at(&self, offset: usize) -> Option<(u32, u32)> {
        let num = self.u32_at(offset)?;
        let den = self.u32_at(offset.checked_add(4)?)?;
        Some((num, den))
    }
}

// ── IFD entry reader (task 2.2) ──────────────────────────────────────────────

/// Maximum number of IFD entries we'll read.  Prevents DoS on malformed
/// data that claims millions of entries.
const MAX_IFD_ENTRIES: u16 = 1000;

/// A raw IFD entry parsed from a TIFF stream.
///
/// If the value fits in 4 bytes (based on type × count), `value_or_offset`
/// holds the value directly (left-aligned in the 4-byte field).  Otherwise
/// it is a byte offset into the TIFF stream where the value is stored.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct IfdEntry {
    /// EXIF/TIFF tag number (e.g. 0x0112 = Orientation).
    tag: u16,
    /// TIFF data type (1=BYTE, 2=ASCII, 3=SHORT, 4=LONG, 5=RATIONAL, …).
    tiff_type: u16,
    /// Number of values of the given type.
    count: u32,
    /// The value itself (if it fits in 4 bytes) or an offset to the value.
    value_or_offset: u32,
}

/// Read all IFD entries starting at `ifd_offset` in the TIFF stream.
///
/// Returns an empty `Vec` if the offset is out of bounds or the entry
/// count is zero.  Caps the entry count at [`MAX_IFD_ENTRIES`].
fn read_ifd_entries(reader: &TiffReader<'_>, ifd_offset: usize) -> Vec<IfdEntry> {
    let count = match reader.u16_at(ifd_offset) {
        Some(c) => c.min(MAX_IFD_ENTRIES),
        None => return Vec::new(),
    };

    let mut entries = Vec::with_capacity(count as usize);
    for i in 0..count as usize {
        // Each IFD entry is 12 bytes, starting 2 bytes after ifd_offset.
        let base = match ifd_offset
            .checked_add(2)
            .and_then(|b| b.checked_add(i.checked_mul(12)?))
        {
            Some(b) => b,
            None => break,
        };

        let tag = match reader.u16_at(base) {
            Some(v) => v,
            None => break,
        };
        let tiff_type = match reader.u16_at(base + 2) {
            Some(v) => v,
            None => break,
        };
        let count = match reader.u32_at(base + 4) {
            Some(v) => v,
            None => break,
        };
        let value_or_offset = match reader.u32_at(base + 8) {
            Some(v) => v,
            None => break,
        };

        entries.push(IfdEntry {
            tag,
            tiff_type,
            count,
            value_or_offset,
        });
    }

    entries
}

// ── ASCII string reader (task 2.3) ───────────────────────────────────────────

/// Read an ASCII string value from the TIFF stream.
///
/// `offset` is the byte offset where the string data starts.
/// `count` is the total byte length including the trailing NUL (per TIFF spec).
///
/// - Trims trailing NUL bytes.
/// - Accepts valid UTF-8 as-is (covers both ASCII and UTF-8 encoded strings).
/// - Falls back to Latin-1 → UTF-8 conversion for non-UTF-8 data (common in
///   real-world EXIF from European cameras).
///
/// Returns `None` if the range is out of bounds or the result is empty after
/// trimming.
fn read_ascii(reader: &TiffReader<'_>, offset: usize, count: u32) -> Option<String> {
    let count = count as usize;
    if count == 0 {
        return None;
    }
    let end = offset.checked_add(count)?;
    let bytes = reader.data.get(offset..end)?;

    // Trim trailing NUL bytes (there may be more than one in malformed data).
    let trimmed = match bytes.iter().rposition(|&b| b != 0) {
        Some(last) => &bytes[..=last],
        None => return None, // all NULs or empty
    };

    if trimmed.is_empty() {
        return None;
    }

    // Try UTF-8 first (covers ASCII and UTF-8).
    if let Ok(s) = std::str::from_utf8(trimmed) {
        return Some(s.to_string());
    }

    // Fall back to Latin-1: each byte maps to its Unicode code point.
    let s: String = trimmed.iter().map(|&b| b as char).collect();
    Some(s)
}

/// Read an ASCII string from an IFD entry, handling both inline (≤ 4 bytes)
/// and offset-referenced values.
///
/// TIFF type 2 = ASCII.  If `count ≤ 4`, the bytes live in the
/// `value_or_offset` field itself (left-aligned, in stream byte order).
/// Otherwise, `value_or_offset` is an offset into the TIFF data.
fn read_ifd_ascii(
    reader: &TiffReader<'_>,
    count: u32,
    value_or_offset: u32,
    entry_value_offset: usize,
) -> Option<String> {
    if count <= 4 {
        // Value is stored inline in the 4-byte value_or_offset field.
        // `entry_value_offset` points to the raw bytes of that field in the stream.
        read_ascii(reader, entry_value_offset, count)
    } else {
        read_ascii(reader, value_or_offset as usize, count)
    }
}

// ── GPS coordinate converter (task 2.4) ──────────────────────────────────────

/// TIFF type constants used when interpreting IFD entry types.
const TIFF_TYPE_BYTE: u16 = 1;
const TIFF_TYPE_ASCII: u16 = 2;
const TIFF_TYPE_SHORT: u16 = 3;
#[allow(dead_code)]
const TIFF_TYPE_LONG: u16 = 4;
const TIFF_TYPE_RATIONAL: u16 = 5;

/// Convert GPS DMS (degrees/minutes/seconds) rationals to decimal degrees.
///
/// Each component is a TIFF RATIONAL `(numerator, denominator)`.
/// `ref_char` is the ASCII reference: `b'N'`/`b'S'` for latitude,
/// `b'E'`/`b'W'` for longitude.
///
/// Returns `None` if:
/// - Any denominator is zero
/// - Minutes ≥ 60 or seconds ≥ 60
/// - Degrees ≥ 360
/// - `ref_char` is not one of `N`, `S`, `E`, `W`
fn dms_to_decimal(
    degrees: (u32, u32),
    minutes: (u32, u32),
    seconds: (u32, u32),
    ref_char: u8,
) -> Option<f64> {
    // Validate denominators.
    if degrees.1 == 0 || minutes.1 == 0 || seconds.1 == 0 {
        return None;
    }

    let deg = degrees.0 as f64 / degrees.1 as f64;
    let min = minutes.0 as f64 / minutes.1 as f64;
    let sec = seconds.0 as f64 / seconds.1 as f64;

    // Range validation.
    if deg >= 360.0 || min >= 60.0 || sec >= 60.0 {
        return None;
    }

    let sign = match ref_char {
        b'N' | b'E' => 1.0,
        b'S' | b'W' => -1.0,
        _ => return None,
    };

    Some(sign * (deg + min / 60.0 + sec / 3600.0))
}

// ── Top-level EXIF parser (task 2.5) ─────────────────────────────────────────

/// Parse an APP1 EXIF payload into a [`JpegExifInfo`].
///
/// `raw` is the full APP1 payload starting with `Exif\0\0`.
///
/// Returns `Some(JpegExifInfo)` if the TIFF header is valid (even if all
/// tag fields end up `None`).  Returns `None` if the header is invalid
/// or the data is not EXIF.
///
/// # Best-effort parsing
///
/// Individual malformed tags are silently skipped — a corrupt orientation
/// tag does not prevent GPS data from being read.  Only a fundamentally
/// invalid TIFF header causes the entire parse to fail.
#[allow(dead_code)]
fn parse_exif(raw: &[u8]) -> Option<JpegExifInfo> {
    // Validate Exif header prefix.
    if raw.len() < 14 {
        return None;
    }
    if &raw[0..6] != b"Exif\0\0" {
        return None;
    }
    parse_tiff_exif(&raw[6..])
}

/// Parse EXIF data from a raw TIFF stream (no `Exif\0\0` prefix).
///
/// This is the shared implementation used by both [`parse_exif`] (which
/// strips the 6-byte prefix first) and the decode path (where
/// `jpeg_decoder::Decoder::exif_data()` returns data starting at the
/// TIFF header directly).
fn parse_tiff_exif(tiff: &[u8]) -> Option<JpegExifInfo> {
    if tiff.len() < 8 {
        // Need at least: 2 (byte order) + 2 (magic) + 4 (IFD0 offset)
        return None;
    }

    // ── Detect byte order ────────────────────────────────────────────
    let order = match &tiff[0..2] {
        b"II" => ByteOrder::Little,
        b"MM" => ByteOrder::Big,
        _ => return None,
    };

    let reader = TiffReader::new(tiff, order);

    // ── Validate TIFF magic number (42) ──────────────────────────────
    let magic = reader.u16_at(2)?;
    if magic != 42 {
        return None;
    }

    // ── Read IFD0 offset ─────────────────────────────────────────────
    let ifd0_offset = reader.u32_at(4)? as usize;

    let mut info = JpegExifInfo::default();
    let mut exif_ifd_offset: Option<usize> = None;
    let mut gps_ifd_offset: Option<usize> = None;

    // ── Walk IFD0 ────────────────────────────────────────────────────
    let ifd0_entries = read_ifd_entries(&reader, ifd0_offset);
    for (i, entry) in ifd0_entries.iter().enumerate() {
        let IfdEntry {
            tag,
            tiff_type,
            count,
            value_or_offset,
        } = *entry;
        // Byte offset of the value/offset field for this entry in the TIFF stream.
        let entry_val_off = ifd0_offset + 2 + i * 12 + 8;

        match tag {
            // Orientation (SHORT, count=1)
            0x0112 => {
                if tiff_type == TIFF_TYPE_SHORT && count == 1 {
                    if let Some(v) = reader.u16_at(entry_val_off) {
                        if (1..=8).contains(&v) {
                            info.orientation = Some(v as u8);
                        }
                    }
                }
            }
            // Make (ASCII)
            0x010F => {
                if tiff_type == TIFF_TYPE_ASCII {
                    info.camera_make =
                        read_ifd_ascii(&reader, count, value_or_offset, entry_val_off);
                }
            }
            // Model (ASCII)
            0x0110 => {
                if tiff_type == TIFF_TYPE_ASCII {
                    info.camera_model =
                        read_ifd_ascii(&reader, count, value_or_offset, entry_val_off);
                }
            }
            // Software (ASCII)
            0x0131 => {
                if tiff_type == TIFF_TYPE_ASCII {
                    info.software = read_ifd_ascii(&reader, count, value_or_offset, entry_val_off);
                }
            }
            // DateTime (ASCII, 20 bytes)
            0x0132 => {
                if tiff_type == TIFF_TYPE_ASCII {
                    info.datetime = read_ifd_ascii(&reader, count, value_or_offset, entry_val_off);
                }
            }
            // ExifIFDPointer (LONG)
            0x8769 => {
                if count == 1 {
                    exif_ifd_offset = Some(value_or_offset as usize);
                }
            }
            // GPSInfoPointer (LONG)
            0x8825 => {
                if count == 1 {
                    gps_ifd_offset = Some(value_or_offset as usize);
                }
            }
            _ => {}
        }
    }

    // ── Walk EXIF sub-IFD ────────────────────────────────────────────
    if let Some(exif_off) = exif_ifd_offset {
        let exif_entries = read_ifd_entries(&reader, exif_off);
        for (i, entry) in exif_entries.iter().enumerate() {
            let IfdEntry {
                tag,
                tiff_type,
                count,
                value_or_offset,
            } = *entry;
            let entry_val_off = exif_off + 2 + i * 12 + 8;

            match tag {
                // ExposureTime (RATIONAL)
                0x829A => {
                    if tiff_type == TIFF_TYPE_RATIONAL && count == 1 {
                        info.exposure_time = reader.rational_at(value_or_offset as usize);
                    }
                }
                // FNumber (RATIONAL)
                0x829D => {
                    if tiff_type == TIFF_TYPE_RATIONAL && count == 1 {
                        info.f_number = reader.rational_at(value_or_offset as usize);
                    }
                }
                // ISOSpeedRatings (SHORT)
                0x8827 => {
                    if tiff_type == TIFF_TYPE_SHORT && count == 1 {
                        info.iso_speed = reader.u16_at(entry_val_off);
                    }
                }
                // DateTimeOriginal (ASCII)
                0x9003 => {
                    if tiff_type == TIFF_TYPE_ASCII {
                        info.datetime_original =
                            read_ifd_ascii(&reader, count, value_or_offset, entry_val_off);
                    }
                }
                // FocalLength (RATIONAL)
                0x920A => {
                    if tiff_type == TIFF_TYPE_RATIONAL && count == 1 {
                        info.focal_length = reader.rational_at(value_or_offset as usize);
                    }
                }
                _ => {}
            }
        }
    }

    // ── Walk GPS sub-IFD ─────────────────────────────────────────────
    if let Some(gps_off) = gps_ifd_offset {
        let gps_entries = read_ifd_entries(&reader, gps_off);

        // Collect raw GPS tag values; we need all of them before conversion.
        let mut lat_ref: Option<u8> = None;
        let mut lat_dms: Option<[(u32, u32); 3]> = None;
        let mut lon_ref: Option<u8> = None;
        let mut lon_dms: Option<[(u32, u32); 3]> = None;
        let mut alt_ref: Option<u8> = None;
        let mut alt_rational: Option<(u32, u32)> = None;

        for (i, entry) in gps_entries.iter().enumerate() {
            let IfdEntry {
                tag,
                tiff_type,
                count,
                value_or_offset,
            } = *entry;
            let entry_val_off = gps_off + 2 + i * 12 + 8;

            match tag {
                // GPSLatitudeRef (ASCII, 2 bytes: "N\0" or "S\0")
                0x0001 => {
                    if tiff_type == TIFF_TYPE_ASCII && count == 2 {
                        lat_ref = reader.u8_at(entry_val_off);
                    }
                }
                // GPSLatitude (3 × RATIONAL = 24 bytes, always offset-referenced)
                0x0002 => {
                    if tiff_type == TIFF_TYPE_RATIONAL && count == 3 {
                        let off = value_or_offset as usize;
                        if let (Some(d), Some(m), Some(s)) = (
                            reader.rational_at(off),
                            reader.rational_at(off + 8),
                            reader.rational_at(off + 16),
                        ) {
                            lat_dms = Some([d, m, s]);
                        }
                    }
                }
                // GPSLongitudeRef (ASCII, 2 bytes: "E\0" or "W\0")
                0x0003 => {
                    if tiff_type == TIFF_TYPE_ASCII && count == 2 {
                        lon_ref = reader.u8_at(entry_val_off);
                    }
                }
                // GPSLongitude (3 × RATIONAL)
                0x0004 => {
                    if tiff_type == TIFF_TYPE_RATIONAL && count == 3 {
                        let off = value_or_offset as usize;
                        if let (Some(d), Some(m), Some(s)) = (
                            reader.rational_at(off),
                            reader.rational_at(off + 8),
                            reader.rational_at(off + 16),
                        ) {
                            lon_dms = Some([d, m, s]);
                        }
                    }
                }
                // GPSAltitudeRef (BYTE, count=1: 0 = above, 1 = below sea level)
                0x0005 => {
                    if tiff_type == TIFF_TYPE_BYTE && count == 1 {
                        alt_ref = reader.u8_at(entry_val_off);
                    }
                }
                // GPSAltitude (RATIONAL)
                0x0006 => {
                    if tiff_type == TIFF_TYPE_RATIONAL && count == 1 {
                        alt_rational = reader.rational_at(value_or_offset as usize);
                    }
                }
                _ => {}
            }
        }

        // Convert GPS latitude.
        if let (Some(ref_ch), Some(dms)) = (lat_ref, lat_dms) {
            info.gps_latitude = dms_to_decimal(dms[0], dms[1], dms[2], ref_ch);
        }

        // Convert GPS longitude.
        if let (Some(ref_ch), Some(dms)) = (lon_ref, lon_dms) {
            info.gps_longitude = dms_to_decimal(dms[0], dms[1], dms[2], ref_ch);
        }

        // Convert GPS altitude.
        if let Some((num, den)) = alt_rational {
            if den != 0 {
                let alt = num as f64 / den as f64;
                let sign = match alt_ref {
                    Some(1) => -1.0,
                    _ => 1.0, // 0 or absent → above sea level
                };
                info.gps_altitude = Some(sign * alt);
            }
        }
    }

    Some(info)
}

// ═══════════════════════════════════════════════════════════════════════════════
// JPEG marker scanners — raw byte scanning for markers not exposed by
// jpeg-decoder (COM comments, JFIF APP0 pixel density)
// ═══════════════════════════════════════════════════════════════════════════════

/// Scan raw JPEG bytes for COM (comment) markers and extract their text.
///
/// COM markers are `FF FE` followed by a 2-byte big-endian length (which
/// includes the 2 length bytes themselves).  Scanning stops at the SOS
/// marker (`FF DA`) — there's no need to scan entropy-coded data.
///
/// Text is decoded as UTF-8 when valid, with a lossless Latin-1 fallback
/// for non-UTF-8 data — consistent with the EXIF ASCII tag decoder (see
/// D12).  This avoids the information loss of `from_utf8_lossy` which
/// replaces non-UTF-8 bytes with U+FFFD.
fn scan_com_markers(data: &[u8]) -> Vec<String> {
    let mut comments = Vec::new();
    // JPEG files start with FF D8.  Skip to the first marker.
    if data.len() < 2 || data[0] != 0xFF || data[1] != 0xD8 {
        return comments;
    }
    let mut pos = 2;

    while pos + 1 < data.len() {
        // Scan for marker prefix.
        if data[pos] != 0xFF {
            pos += 1;
            continue;
        }

        // Skip fill bytes (consecutive 0xFF).
        while pos + 1 < data.len() && data[pos + 1] == 0xFF {
            pos += 1;
        }
        if pos + 1 >= data.len() {
            break;
        }

        let marker = data[pos + 1];
        pos += 2; // skip past FF XX

        match marker {
            // SOS — stop scanning (rest is entropy data).
            0xDA => break,
            // Standalone markers with no payload.
            0x00 | 0x01 | 0xD0..=0xD7 => continue,
            // COM marker (0xFE).
            0xFE => {
                if pos + 2 > data.len() {
                    break;
                }
                let len = u16::from_be_bytes([data[pos], data[pos + 1]]) as usize;
                if len < 2 {
                    break; // invalid length
                }
                let payload_len = len - 2;
                let payload_start = pos + 2;
                if payload_start + payload_len > data.len() {
                    break; // truncated
                }
                let payload = &data[payload_start..payload_start + payload_len];
                let text = if let Ok(s) = std::str::from_utf8(payload) {
                    s.to_string()
                } else {
                    // Latin-1 fallback: each byte maps to its Unicode code point.
                    payload.iter().map(|&b| b as char).collect()
                };
                comments.push(text);
                pos = payload_start + payload_len;
            }
            // Any other marker with a length field — skip over it.
            _ => {
                if pos + 2 > data.len() {
                    break;
                }
                let len = u16::from_be_bytes([data[pos], data[pos + 1]]) as usize;
                if len < 2 || pos + len > data.len() {
                    break;
                }
                pos += len;
            }
        }
    }

    comments
}

/// Scan raw JPEG bytes for the JFIF APP0 marker and extract pixel density.
///
/// JFIF APP0 layout after `FF E0`:
/// - 2 bytes: length (BE, includes itself)
/// - 5 bytes: identifier `JFIF\0`
/// - 2 bytes: version (major, minor)
/// - 1 byte: density units (0 = aspect, 1 = DPI, 2 = DPCM)
/// - 2 bytes: X density (BE)
/// - 2 bytes: Y density (BE)
///
/// Returns `None` if no valid JFIF APP0 is found.
fn scan_jfif_density(data: &[u8]) -> Option<JpegPixelDensity> {
    // JPEG must start with FF D8.
    if data.len() < 2 || data[0] != 0xFF || data[1] != 0xD8 {
        return None;
    }
    let mut pos = 2;

    // The JFIF APP0 marker should be the very first marker after SOI,
    // but we scan a few markers in case there's padding.
    while pos + 1 < data.len() {
        if data[pos] != 0xFF {
            pos += 1;
            continue;
        }
        // Skip fill bytes.
        while pos + 1 < data.len() && data[pos + 1] == 0xFF {
            pos += 1;
        }
        if pos + 1 >= data.len() {
            break;
        }

        let marker = data[pos + 1];
        pos += 2;

        match marker {
            0xDA => break, // SOS — stop
            0x00 | 0x01 | 0xD0..=0xD7 => continue,
            0xE0 => {
                // APP0 — check if it's JFIF.
                if pos + 2 > data.len() {
                    return None;
                }
                let len = u16::from_be_bytes([data[pos], data[pos + 1]]) as usize;
                if len < 2 || pos + len > data.len() {
                    return None;
                }
                let segment = &data[pos + 2..pos + len];
                // Check JFIF identifier: "JFIF\0" (5 bytes) + version (2) + units (1) + Xd (2) + Yd (2) = 12 bytes minimum
                if segment.len() >= 12 && &segment[0..5] == b"JFIF\0" {
                    let units = segment[7];
                    let x_density = u16::from_be_bytes([segment[8], segment[9]]);
                    let y_density = u16::from_be_bytes([segment[10], segment[11]]);
                    return match units {
                        1 => Some(JpegPixelDensity::Dpi {
                            x: x_density,
                            y: y_density,
                        }),
                        2 => Some(JpegPixelDensity::Dpcm {
                            x: x_density,
                            y: y_density,
                        }),
                        _ => Some(JpegPixelDensity::AspectRatio {
                            x: x_density,
                            y: y_density,
                        }),
                    };
                }
                pos += len;
            }
            _ => {
                if pos + 2 > data.len() {
                    break;
                }
                let len = u16::from_be_bytes([data[pos], data[pos + 1]]) as usize;
                if len < 2 || pos + len > data.len() {
                    break;
                }
                pos += len;
            }
        }
    }

    None
}

// ═══════════════════════════════════════════════════════════════════════════════
// Decoding — public API (Phase 3)
// ═══════════════════════════════════════════════════════════════════════════════

/// Map a `jpeg_decoder::Error` into [`IoError`].
fn decode_error(e: jpeg_decoder::Error) -> IoError {
    match e {
        jpeg_decoder::Error::Io(io) => IoError::Io(io),
        other => IoError::DecodeFailed {
            source: Box::new(other),
        },
    }
}

/// Decode a JPEG image from an in-memory byte slice.
///
/// Returns a [`JpegDecoded`] containing the pixel data as a [`JpegImage`]
/// and ancillary metadata as a [`JpegMetadata`].
///
/// This is the preferred entry point when the entire file is available in
/// memory.  It scans the raw bytes for COM comment markers and JFIF APP0
/// pixel density *before* handing the data to `jpeg-decoder`, giving a
/// richer [`JpegMetadata`] than [`decode_reader`].
///
/// # Errors
///
/// - [`IoError::DecodeFailed`] — the data is not a valid JPEG or is
///   corrupt beyond recovery.
/// - [`IoError::UnsupportedFeature`] — the JPEG uses CMYK colour, which
///   this library deliberately rejects (see design decision D7).
/// - [`IoError::Io`] — an I/O error during decoding (unlikely from bytes).
///
/// # Examples
///
/// ```no_run
/// # use fovea_io::jpeg::{self, JpegImage};
/// let bytes = std::fs::read("photo.jpg").unwrap();
/// let decoded = jpeg::decode(&bytes).unwrap();
///
/// match decoded.image {
///     JpegImage::Srgb8(image) => { /* work with Image<Srgb8> */ }
///     JpegImage::SrgbMono8(image) => { /* 8-bit grayscale */ }
///     JpegImage::SrgbMono16(image) => { /* 12-bit extended, decoded to 16 */ }
/// }
/// ```
pub fn decode(data: &[u8]) -> Result<JpegDecoded, IoError> {
    // ── Pre-scan raw bytes for markers the decoder doesn't expose ─────
    let comments = scan_com_markers(data);
    let pixel_density = scan_jfif_density(data);

    // ── Run the JPEG decoder ─────────────────────────────────────────
    let mut decoder = jpeg_decoder::Decoder::new(std::io::Cursor::new(data));
    let pixels = decoder.decode().map_err(decode_error)?;
    let info = decoder.info().ok_or_else(|| IoError::DecodeFailed {
        source: "jpeg decoder produced no image info after successful decode".into(),
    })?;

    let width = info.width as usize;
    let height = info.height as usize;

    // ── Convert pixels → JpegImage ───────────────────────────────────
    let (image, source_bit_depth) = pixels_to_image(pixels, width, height, info.pixel_format)?;

    // ── Build metadata ───────────────────────────────────────────────
    let metadata = build_metadata(&decoder, source_bit_depth, comments, pixel_density);

    Ok(JpegDecoded { image, metadata })
}

/// Decode a JPEG image from a streaming reader.
///
/// Buffers the entire stream into memory and then delegates to [`decode`],
/// so both paths produce identical [`JpegDecoded`] results — including
/// COM comments and JFIF pixel density.  `jpeg-decoder` already buffers
/// the entire stream internally for decoding, so buffering up-front adds
/// no net memory cost.
///
/// # Errors
///
/// Same error conditions as [`decode`], plus [`IoError::Io`] for read
/// failures.
///
/// # Examples
///
/// ```no_run
/// # use fovea_io::jpeg::{self, JpegImage};
/// let file = std::fs::File::open("photo.jpg").unwrap();
/// let reader = std::io::BufReader::new(file);
/// let decoded = jpeg::decode_reader(reader).unwrap();
///
/// match decoded.image {
///     JpegImage::Srgb8(image) => { /* work with Image<Srgb8> */ }
///     _ => { /* handle remaining variants */ }
/// }
/// ```
pub fn decode_reader(mut reader: impl std::io::Read) -> Result<JpegDecoded, IoError> {
    let mut buf = Vec::new();
    reader.read_to_end(&mut buf)?;
    decode(&buf)
}

/// Convert raw decoder output to a [`JpegImage`], returning the image and
/// the source bit depth.
fn pixels_to_image(
    pixels: Vec<u8>,
    width: usize,
    height: usize,
    pixel_format: jpeg_decoder::PixelFormat,
) -> Result<(JpegImage, JpegBitDepth), IoError> {
    match pixel_format {
        jpeg_decoder::PixelFormat::L8 => {
            let img = Image::from_raw_bytes(width, height, pixels).map_err(|_| {
                IoError::DecodeFailed {
                    source: "pixel count does not match image dimensions (L8)".into(),
                }
            })?;
            Ok((JpegImage::SrgbMono8(img), JpegBitDepth::Eight))
        }
        jpeg_decoder::PixelFormat::L16 => {
            // jpeg-decoder stores 16-bit luminance as native-endian u16 pairs.
            let pixel_vec: Vec<SrgbMono16> = pixels
                .chunks_exact(2)
                .map(|b| SrgbMono16::new(u16::from_ne_bytes([b[0], b[1]])))
                .collect();
            let img =
                Image::from_vec(width, height, pixel_vec).map_err(|_| IoError::DecodeFailed {
                    source: "pixel count does not match image dimensions (L16)".into(),
                })?;
            Ok((JpegImage::SrgbMono16(img), JpegBitDepth::Twelve))
        }
        jpeg_decoder::PixelFormat::RGB24 => {
            let img = Image::from_raw_bytes(width, height, pixels).map_err(|_| {
                IoError::DecodeFailed {
                    source: "pixel count does not match image dimensions (RGB24)".into(),
                }
            })?;
            Ok((JpegImage::Srgb8(img), JpegBitDepth::Eight))
        }
        jpeg_decoder::PixelFormat::CMYK32 => Err(IoError::UnsupportedFeature {
            reason: "CMYK JPEG is not supported — convert to RGB before loading",
        }),
    }
}

/// Build a [`JpegMetadata`] from decoder state and pre-scanned data.
fn build_metadata<R: std::io::Read>(
    decoder: &jpeg_decoder::Decoder<R>,
    source_bit_depth: JpegBitDepth,
    comments: Vec<String>,
    pixel_density: Option<JpegPixelDensity>,
) -> JpegMetadata {
    // ── EXIF ─────────────────────────────────────────────────────────
    // jpeg-decoder returns EXIF data starting at the TIFF header (no
    // `Exif\0\0` prefix), so we use `parse_tiff_exif` directly.
    let raw_exif_data = decoder.exif_data();
    let exif = raw_exif_data.and_then(parse_tiff_exif);
    let raw_exif = raw_exif_data.map(|d| d.to_vec().into_boxed_slice());

    // ── ICC profile ──────────────────────────────────────────────────
    let icc_profile = decoder.icc_profile().map(|v| v.into_boxed_slice());

    // ── Colour space ─────────────────────────────────────────────────
    let color_space = if icc_profile.is_some() {
        JpegColorSpace::IccTagged
    } else {
        JpegColorSpace::Srgb
    };

    JpegMetadata {
        exif,
        raw_exif,
        icc_profile,
        pixel_density,
        comments,
        source_bit_depth,
        color_space,
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Encoding — types
// ═══════════════════════════════════════════════════════════════════════════════

/// Chroma subsampling factor for JPEG encoding.
///
/// Controls the trade-off between colour fidelity and file size.
/// `F1x1` (4:4:4) preserves full chroma resolution; `F2x2` (4:2:0) halves
/// both dimensions, producing the smallest files.
///
/// # Examples
///
/// ```
/// use fovea_io::jpeg::JpegSamplingFactor;
///
/// let factor = JpegSamplingFactor::F1x1;
/// assert_eq!(factor, JpegSamplingFactor::F1x1);
/// assert_ne!(factor, JpegSamplingFactor::F2x2);
///
/// // Copy semantics:
/// let factor2 = factor;
/// assert_eq!(factor, factor2);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum JpegSamplingFactor {
    /// 4:4:4 — no chroma subsampling.  Best quality, largest file.
    F1x1,
    /// 4:2:2 — horizontal chroma halved.
    F2x1,
    /// 4:2:0 — both dimensions halved.  Smallest file.
    F2x2,
}

/// Options for JPEG encoding.
///
/// `#[non_exhaustive]` so that new fields (e.g. optimise Huffman tables)
/// can be added without a semver-major bump.
///
/// # Examples
///
/// ```
/// use fovea_io::jpeg::{JpegEncodeOptions, JpegSamplingFactor};
///
/// // Use defaults (quality 85, encoder-default sampling, not progressive):
/// let opts = JpegEncodeOptions::default();
/// assert_eq!(opts.quality, 85);
/// assert!(!opts.progressive);
///
/// // Custom options via mutation:
/// let mut opts = JpegEncodeOptions::default();
/// opts.quality = 95;
/// opts.sampling_factor = Some(JpegSamplingFactor::F1x1);
/// opts.progressive = true;
/// assert_eq!(opts.quality, 95);
/// ```
//
// Note: ICC profile (`APP2`) embedding and `COM` comment emission are
// intentionally **not** part of the encode options yet. The previous
// `icc_profile` / `comments` fields silently dropped their data (the
// encoder never wrote them), which violates design principles §4 and §7–§8
// (no silent data loss; I/O must preserve format fidelity). Because the
// struct is `#[non_exhaustive]`, those fields can be reintroduced with a
// real implementation later without a semver-major bump.
#[non_exhaustive]
#[derive(Debug, Clone)]
pub struct JpegEncodeOptions {
    /// Quality factor (1–100).  Default: 85.
    pub quality: u8,
    /// Chroma subsampling.  Default: `None` (encoder default, typically 4:2:0).
    pub sampling_factor: Option<JpegSamplingFactor>,
    /// Progressive encoding.  Default: `false`.
    pub progressive: bool,
}

impl Default for JpegEncodeOptions {
    fn default() -> Self {
        Self {
            quality: 85,
            sampling_factor: None,
            progressive: false,
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// JpegPixel — sealed encode trait (Phase 4, task 4.3)
// ═══════════════════════════════════════════════════════════════════════════════

mod jpeg_pixel_sealed {
    /// Sealed supertrait — prevents out-of-crate implementations of
    /// [`JpegPixel`](super::JpegPixel).
    pub trait Sealed {}
}

/// Maps a pixel type to its `jpeg-encoder` colour type.
///
/// This trait is **sealed**: it is implemented for exactly the pixel types
/// that JPEG can represent without lossy conversion.  Attempting to encode
/// a type that does not implement `JpegPixel` is a compile-time error.
///
/// # Implementors
///
/// | Pixel type  | `jpeg_encoder::ColorType` | Notes              |
/// |-------------|---------------------------|--------------------|
/// | `SrgbMono8` | `Luma`                    | Grayscale JPEG     |
/// | `Srgb8`     | `Rgb`                     | Standard RGB JPEG  |
///
/// `Srgba8` is deliberately **excluded**.  JPEG does not support alpha;
/// encoding `Srgba8` would silently discard the alpha channel — a lossy
/// conversion that violates design principle §4.  Strip alpha explicitly
/// before encoding.
///
/// `Rgb8` and `Mono8` (linear) are excluded because JPEG is sRGB by
/// definition.  Encoding linear data as sRGB would be a type-level lie.
///
/// # Compile-time enforcement
///
/// ```compile_fail
/// # use fovea::image::Image;
/// # use fovea::pixel::Rgb8;
/// # use fovea_io::jpeg::{self, JpegEncodeOptions};
/// // ERROR: `Rgb8` does not implement `JpegPixel`.
/// // JPEG is sRGB — encode `Srgb8` instead.
/// let img = Image::fill(1, 1, Rgb8::new(0, 0, 0));
/// let _ = jpeg::encode(&img, &JpegEncodeOptions::default());
/// ```
///
/// ```compile_fail
/// # use fovea::image::Image;
/// # use fovea::pixel::Mono8;
/// # use fovea_io::jpeg::{self, JpegEncodeOptions};
/// // ERROR: `Mono8` does not implement `JpegPixel`.
/// let img = Image::fill(1, 1, Mono8::new(0));
/// let _ = jpeg::encode(&img, &JpegEncodeOptions::default());
/// ```
///
/// ```compile_fail
/// # use fovea::image::Image;
/// # use fovea::pixel::Srgba8;
/// # use fovea_io::jpeg::{self, JpegEncodeOptions};
/// // ERROR: `Srgba8` does not implement `JpegPixel`.
/// // JPEG has no alpha channel — strip alpha first.
/// let img = Image::fill(1, 1, Srgba8::new(0, 0, 0, 255));
/// let _ = jpeg::encode(&img, &JpegEncodeOptions::default());
/// ```
///
/// ```compile_fail
/// # use fovea::image::Image;
/// # use fovea::pixel::Rgb16;
/// # use fovea_io::jpeg::{self, JpegEncodeOptions};
/// // ERROR: `Rgb16` does not implement `JpegPixel`.
/// let img = Image::fill(1, 1, Rgb16::new(0, 0, 0));
/// let _ = jpeg::encode(&img, &JpegEncodeOptions::default());
/// ```
pub trait JpegPixel: jpeg_pixel_sealed::Sealed + fovea::pixel::PlainPixel {
    /// `jpeg-encoder` colour type for this pixel.
    const JPEG_COLOR_TYPE: jpeg_encoder::ColorType;
}

macro_rules! impl_jpeg_pixel {
    ($ty:ty, $color:expr) => {
        impl jpeg_pixel_sealed::Sealed for $ty {}
        impl JpegPixel for $ty {
            const JPEG_COLOR_TYPE: jpeg_encoder::ColorType = $color;
        }
    };
}

impl_jpeg_pixel!(SrgbMono8, jpeg_encoder::ColorType::Luma);
impl_jpeg_pixel!(Srgb8, jpeg_encoder::ColorType::Rgb);

// ═══════════════════════════════════════════════════════════════════════════════
// Encoding — public API (Phase 4)
// ═══════════════════════════════════════════════════════════════════════════════

/// Map a `jpeg_encoder::EncodingError` into [`IoError`].
fn encode_error(e: jpeg_encoder::EncodingError) -> IoError {
    match e {
        jpeg_encoder::EncodingError::IoError(io) => IoError::Io(io),
        other => IoError::EncodeFailed {
            source: Box::new(other),
        },
    }
}

/// Encode an image to an in-memory JPEG byte vector.
///
/// Only pixel types that implement [`JpegPixel`] can be encoded — currently
/// [`SrgbMono8`] and [`Srgb8`].  Attempting to encode other types (e.g.
/// `Rgb8`, `Srgba8`) is a compile-time error.
///
/// # Errors
///
/// - [`IoError::EncodeFailed`] — the encoder reports an error (e.g. quality
///   out of range after clamping).
/// - [`IoError::Io`] — an I/O error during encoding (unlikely to `Vec<u8>`).
///
/// # Examples
///
/// ```no_run
/// # use fovea::image::Image;
/// # use fovea::pixel::Srgb8;
/// # use fovea_io::jpeg::{self, JpegEncodeOptions};
/// let image = Image::fill(320, 240, Srgb8::new(128, 64, 32));
/// let bytes = jpeg::encode(&image, &JpegEncodeOptions::default()).unwrap();
/// std::fs::write("output.jpg", bytes).unwrap();
/// ```
pub fn encode<P: JpegPixel>(
    image: &(impl fovea::image::ImageView<Pixel = P> + fovea::image::PlainImage),
    options: &JpegEncodeOptions,
) -> Result<Vec<u8>, IoError> {
    let mut buf = Vec::new();
    encode_writer(image, &mut buf, options)?;
    Ok(buf)
}

/// Encode an image to a streaming writer.
///
/// This is the core encoding function — [`encode`] is a convenience
/// wrapper that writes into a `Vec<u8>`.
///
/// # Errors
///
/// - [`IoError::EncodeFailed`] — the encoder reports an error.
/// - [`IoError::Io`] — the underlying writer fails.
///
/// # Examples
///
/// ```no_run
/// # use fovea::image::Image;
/// # use fovea::pixel::Srgb8;
/// # use fovea_io::jpeg::{self, JpegEncodeOptions};
/// let image = Image::fill(320, 240, Srgb8::new(128, 64, 32));
/// let mut out = Vec::new();
/// jpeg::encode_writer(&image, &mut out, &JpegEncodeOptions::default()).unwrap();
/// ```
pub fn encode_writer<P: JpegPixel>(
    image: &(impl fovea::image::ImageView<Pixel = P> + fovea::image::PlainImage),
    writer: impl std::io::Write,
    options: &JpegEncodeOptions,
) -> Result<(), IoError> {
    // ── JPEG spec dimension limit ────────────────────────────────────
    // The SOFn marker encodes width and height as 16-bit unsigned
    // big-endian values (ITU-T T.81 §B.2.2). Anything above 65535 cannot
    // be represented in a spec-compliant JPEG. A naked `as u16` cast
    // silently wraps (e.g. 65_536 → 0), which the encoder then rejects
    // as a zero-dimension image — a confusing error for the caller.
    // Validate up front and surface a clear, codec-agnostic error.
    if image.width() > u16::MAX as usize || image.height() > u16::MAX as usize {
        return Err(IoError::UnsupportedFeature {
            reason: "JPEG dimensions exceed 65535 (u16::MAX) per ITU-T T.81 §B.2.2",
        });
    }
    let width = image.width() as u16;
    let height = image.height() as u16;

    // Clamp quality to valid range (1–100).
    let quality = options.quality.clamp(1, 100);

    let mut encoder = jpeg_encoder::Encoder::new(writer, quality);

    // ── Sampling factor ──────────────────────────────────────────────
    if let Some(sf) = options.sampling_factor {
        let sampling = match sf {
            JpegSamplingFactor::F1x1 => jpeg_encoder::SamplingFactor::F_1_1,
            JpegSamplingFactor::F2x1 => jpeg_encoder::SamplingFactor::F_2_1,
            JpegSamplingFactor::F2x2 => jpeg_encoder::SamplingFactor::F_2_2,
        };
        encoder.set_sampling_factor(sampling);
    }

    // ── Progressive mode ─────────────────────────────────────────────
    if options.progressive {
        encoder.set_progressive(true);
    }

    // ── Write image data ─────────────────────────────────────────────
    let bytes: &[u8] = image.as_bytes();
    encoder
        .encode(bytes, width, height, P::JPEG_COLOR_TYPE)
        .map_err(encode_error)?;

    Ok(())
}

/// Encode a [`JpegImage`] back to JPEG bytes.
///
/// Convenience wrapper that dispatches over all [`JpegImage`] variants.
/// Useful for roundtripping and generic tooling.
///
/// Note: `SrgbMono16` (12-bit JPEG) cannot be re-encoded because
/// `jpeg-encoder` only supports 8-bit encoding.  This variant returns
/// [`IoError::UnsupportedFeature`].
///
/// # Errors
///
/// - [`IoError::EncodeFailed`] — the encoder reports an error.
/// - [`IoError::UnsupportedFeature`] — the image is `SrgbMono16` (16-bit
///   data cannot be encoded to baseline JPEG).
///
/// # Examples
///
/// ```no_run
/// # use fovea_io::jpeg::{self, JpegEncodeOptions};
/// let decoded = jpeg::decode(&std::fs::read("photo.jpg").unwrap()).unwrap();
/// let bytes = jpeg::encode_jpeg_image(&decoded.image, &JpegEncodeOptions::default()).unwrap();
/// std::fs::write("copy.jpg", bytes).unwrap();
/// ```
pub fn encode_jpeg_image(
    image: &JpegImage,
    options: &JpegEncodeOptions,
) -> Result<Vec<u8>, IoError> {
    match image {
        JpegImage::SrgbMono8(img) => encode(img, options),
        JpegImage::SrgbMono16(_) => Err(IoError::UnsupportedFeature {
            reason: "16-bit grayscale (12-bit JPEG) cannot be re-encoded to baseline JPEG",
        }),
        JpegImage::Srgb8(img) => encode(img, options),
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Tests
// ═══════════════════════════════════════════════════════════════════════════════

#[cfg(test)]
mod tests {
    use super::*;
    use fovea::image::ImageView;
    use std::mem;

    // ── Minimal JPEG builder (for decode tests) ──────────────────────

    /// Build a minimal valid JFIF JPEG byte stream.
    ///
    /// This generates a baseline JPEG with the given dimensions, pixel
    /// format (grayscale or RGB), and optional APP0/COM/APP1 segments.
    /// We use `jpeg-encoder` to produce valid entropy data, then
    /// optionally prepend extra markers.
    fn build_jpeg_rgb(width: u16, height: u16, r: u8, g: u8, b: u8) -> Vec<u8> {
        let w = width as usize;
        let h = height as usize;
        let mut pixels = Vec::with_capacity(w * h * 3);
        for _ in 0..w * h {
            pixels.push(r);
            pixels.push(g);
            pixels.push(b);
        }
        let mut buf = Vec::new();
        let encoder = jpeg_encoder::Encoder::new(&mut buf, 90);
        encoder
            .encode(&pixels, width, height, jpeg_encoder::ColorType::Rgb)
            .unwrap();
        buf
    }

    fn build_jpeg_gray(width: u16, height: u16, value: u8) -> Vec<u8> {
        let w = width as usize;
        let h = height as usize;
        let pixels = vec![value; w * h];
        let mut buf = Vec::new();
        let encoder = jpeg_encoder::Encoder::new(&mut buf, 90);
        encoder
            .encode(&pixels, width, height, jpeg_encoder::ColorType::Luma)
            .unwrap();
        buf
    }

    /// Inject a COM marker into an existing JPEG byte stream right after SOI.
    fn inject_com_marker(jpeg: &[u8], text: &str) -> Vec<u8> {
        assert!(jpeg.len() >= 2 && jpeg[0] == 0xFF && jpeg[1] == 0xD8);
        let text_bytes = text.as_bytes();
        let seg_len = (text_bytes.len() + 2) as u16; // +2 for the length field
        let mut out = Vec::with_capacity(jpeg.len() + 4 + text_bytes.len());
        out.extend_from_slice(&jpeg[..2]); // SOI
        out.push(0xFF);
        out.push(0xFE); // COM marker
        out.extend_from_slice(&seg_len.to_be_bytes());
        out.extend_from_slice(text_bytes);
        out.extend_from_slice(&jpeg[2..]); // rest of JPEG
        out
    }

    /// Inject a JFIF APP0 segment with specified density into a JPEG.
    fn inject_jfif_app0(jpeg: &[u8], units: u8, x: u16, y: u16) -> Vec<u8> {
        assert!(jpeg.len() >= 2 && jpeg[0] == 0xFF && jpeg[1] == 0xD8);
        let mut segment = Vec::new();
        segment.extend_from_slice(b"JFIF\0"); // identifier
        segment.push(1); // version major
        segment.push(2); // version minor
        segment.push(units);
        segment.extend_from_slice(&x.to_be_bytes());
        segment.extend_from_slice(&y.to_be_bytes());
        segment.push(0); // thumbnail width
        segment.push(0); // thumbnail height
        let seg_len = (segment.len() + 2) as u16;
        let mut out = Vec::with_capacity(jpeg.len() + 4 + segment.len());
        out.extend_from_slice(&jpeg[..2]); // SOI
        out.push(0xFF);
        out.push(0xE0); // APP0 marker
        out.extend_from_slice(&seg_len.to_be_bytes());
        out.extend_from_slice(&segment);
        out.extend_from_slice(&jpeg[2..]); // rest
        out
    }

    // ── JpegImage — enum compactness ─────────────────────────────────────

    /// All three variants are `Image<T>` (thin pointer + size), so the
    /// enum should stay compact.
    #[test]
    fn jpeg_image_enum_is_compact() {
        let srgb8_size = mem::size_of::<Image<Srgb8>>();
        let mono8_size = mem::size_of::<Image<SrgbMono8>>();
        let mono16_size = mem::size_of::<Image<SrgbMono16>>();
        let enum_size = mem::size_of::<JpegImage>();

        // The enum should be at most the size of the largest variant + tag + padding.
        // All variants are the same underlying shape, so the enum shouldn't be
        // drastically larger than any single variant.
        let max_variant = srgb8_size.max(mono8_size).max(mono16_size);
        assert!(
            enum_size <= max_variant + 16,
            "JpegImage enum is unexpectedly large: {enum_size} bytes \
             (max variant is {max_variant} bytes)"
        );
    }

    // ── JpegImage — Debug impl ───────────────────────────────────────────

    #[test]
    fn jpeg_image_debug_srgb_mono8() {
        let img = JpegImage::SrgbMono8(Image::fill(10, 20, SrgbMono8::new(0)));
        assert_eq!(format!("{:?}", img), "SrgbMono8(10x20)");
    }

    #[test]
    fn jpeg_image_debug_srgb_mono16() {
        let img = JpegImage::SrgbMono16(Image::fill(5, 15, SrgbMono16::new(0)));
        assert_eq!(format!("{:?}", img), "SrgbMono16(5x15)");
    }

    #[test]
    fn jpeg_image_debug_srgb8() {
        let img = JpegImage::Srgb8(Image::fill(320, 240, Srgb8::new(0, 0, 0)));
        assert_eq!(format!("{:?}", img), "Srgb8(320x240)");
    }

    #[test]
    fn jpeg_image_debug_1x1() {
        let img = JpegImage::Srgb8(Image::fill(1, 1, Srgb8::new(0, 0, 0)));
        assert_eq!(format!("{:?}", img), "Srgb8(1x1)");
    }

    #[test]
    fn jpeg_image_debug_all_variants() {
        // Ensure all branches of the Debug match are covered.
        let variants: Vec<JpegImage> = vec![
            JpegImage::SrgbMono8(Image::fill(1, 1, SrgbMono8::new(0))),
            JpegImage::SrgbMono16(Image::fill(2, 3, SrgbMono16::new(0))),
            JpegImage::Srgb8(Image::fill(4, 5, Srgb8::new(0, 0, 0))),
        ];
        let expected = ["SrgbMono8(1x1)", "SrgbMono16(2x3)", "Srgb8(4x5)"];
        for (v, e) in variants.iter().zip(expected.iter()) {
            assert_eq!(format!("{:?}", v), *e);
        }
    }

    // ── JpegExifInfo — constructibility and default ──────────────────────

    #[test]
    fn jpeg_exif_info_default_all_none() {
        let info = JpegExifInfo::default();
        assert_eq!(info.orientation, None);
        assert_eq!(info.datetime, None);
        assert_eq!(info.datetime_original, None);
        assert_eq!(info.camera_make, None);
        assert_eq!(info.camera_model, None);
        assert_eq!(info.software, None);
        assert_eq!(info.exposure_time, None);
        assert_eq!(info.f_number, None);
        assert_eq!(info.iso_speed, None);
        assert_eq!(info.focal_length, None);
        assert_eq!(info.gps_latitude, None);
        assert_eq!(info.gps_longitude, None);
        assert_eq!(info.gps_altitude, None);
    }

    #[test]
    fn jpeg_exif_info_fully_populated() {
        let info = JpegExifInfo {
            orientation: Some(6),
            datetime: Some("2025:01:15 12:30:00".to_string()),
            datetime_original: Some("2025:01:15 12:29:59".to_string()),
            camera_make: Some("Canon".to_string()),
            camera_model: Some("EOS R5".to_string()),
            software: Some("Lightroom 13.0".to_string()),
            exposure_time: Some((1, 250)),
            f_number: Some((28, 10)),
            iso_speed: Some(400),
            focal_length: Some((50, 1)),
            gps_latitude: Some(48.8566),
            gps_longitude: Some(2.3522),
            gps_altitude: Some(35.0),
        };
        assert_eq!(info.orientation, Some(6));
        assert_eq!(info.datetime.as_deref(), Some("2025:01:15 12:30:00"));
        assert_eq!(
            info.datetime_original.as_deref(),
            Some("2025:01:15 12:29:59")
        );
        assert_eq!(info.camera_make.as_deref(), Some("Canon"));
        assert_eq!(info.camera_model.as_deref(), Some("EOS R5"));
        assert_eq!(info.software.as_deref(), Some("Lightroom 13.0"));
        assert_eq!(info.exposure_time, Some((1, 250)));
        assert_eq!(info.f_number, Some((28, 10)));
        assert_eq!(info.iso_speed, Some(400));
        assert_eq!(info.focal_length, Some((50, 1)));
        assert!((info.gps_latitude.unwrap() - 48.8566).abs() < 1e-10);
        assert!((info.gps_longitude.unwrap() - 2.3522).abs() < 1e-10);
        assert!((info.gps_altitude.unwrap() - 35.0).abs() < 1e-10);
    }

    #[test]
    fn jpeg_exif_info_partial_fields() {
        let info = JpegExifInfo {
            orientation: Some(1),
            camera_make: Some("Nikon".to_string()),
            ..Default::default()
        };
        assert_eq!(info.orientation, Some(1));
        assert_eq!(info.camera_make.as_deref(), Some("Nikon"));
        assert_eq!(info.camera_model, None);
        assert_eq!(info.exposure_time, None);
        assert_eq!(info.gps_latitude, None);
    }

    #[test]
    fn jpeg_exif_info_clone() {
        let info = JpegExifInfo {
            orientation: Some(3),
            datetime: Some("2025:06:01 08:00:00".to_string()),
            ..Default::default()
        };
        let cloned = info.clone();
        assert_eq!(info, cloned);
    }

    #[test]
    fn jpeg_exif_info_debug() {
        let info = JpegExifInfo::default();
        let dbg = format!("{:?}", info);
        assert!(dbg.contains("JpegExifInfo"));
        assert!(dbg.contains("orientation: None"));
    }

    #[test]
    fn jpeg_exif_info_partial_eq() {
        let a = JpegExifInfo {
            orientation: Some(1),
            ..Default::default()
        };
        let b = JpegExifInfo {
            orientation: Some(1),
            ..Default::default()
        };
        let c = JpegExifInfo {
            orientation: Some(2),
            ..Default::default()
        };
        assert_eq!(a, b);
        assert_ne!(a, c);
    }

    #[test]
    fn jpeg_exif_info_gps_negative_values() {
        // South latitude, West longitude, below sea level.
        let info = JpegExifInfo {
            gps_latitude: Some(-33.8688),
            gps_longitude: Some(-151.2093),
            gps_altitude: Some(-10.5),
            ..Default::default()
        };
        assert!(info.gps_latitude.unwrap() < 0.0);
        assert!(info.gps_longitude.unwrap() < 0.0);
        assert!(info.gps_altitude.unwrap() < 0.0);
    }

    #[test]
    fn jpeg_exif_info_exposure_rational_precision() {
        // Ensure rationals preserve exact fractions.
        let info = JpegExifInfo {
            exposure_time: Some((1, 8000)),
            f_number: Some((14, 10)),
            focal_length: Some((200, 1)),
            ..Default::default()
        };
        let (num, den) = info.exposure_time.unwrap();
        assert_eq!(num, 1);
        assert_eq!(den, 8000);
        // User can compute f64:
        let exposure_secs = num as f64 / den as f64;
        assert!((exposure_secs - 0.000125).abs() < 1e-10);
    }

    // ── JpegColorSpace — variants and traits ─────────────────────────────

    #[test]
    fn jpeg_color_space_variants_constructible() {
        let srgb = JpegColorSpace::Srgb;
        let icc = JpegColorSpace::IccTagged;
        assert_eq!(srgb, JpegColorSpace::Srgb);
        assert_eq!(icc, JpegColorSpace::IccTagged);
        assert_ne!(srgb, icc);
    }

    #[test]
    fn jpeg_color_space_is_copy() {
        let cs = JpegColorSpace::Srgb;
        let cs2 = cs;
        assert_eq!(cs, cs2);
    }

    #[test]
    fn jpeg_color_space_debug() {
        assert_eq!(format!("{:?}", JpegColorSpace::Srgb), "Srgb");
        assert_eq!(format!("{:?}", JpegColorSpace::IccTagged), "IccTagged");
    }

    #[test]
    fn jpeg_color_space_clone() {
        let cs = JpegColorSpace::IccTagged;
        let cloned = cs.clone();
        assert_eq!(cs, cloned);
    }

    // ── JpegPixelDensity — variants and traits ───────────────────────────

    #[test]
    fn jpeg_pixel_density_dpi() {
        let d = JpegPixelDensity::Dpi { x: 300, y: 300 };
        match d {
            JpegPixelDensity::Dpi { x, y } => {
                assert_eq!(x, 300);
                assert_eq!(y, 300);
            }
            _ => panic!("expected Dpi"),
        }
    }

    #[test]
    fn jpeg_pixel_density_dpcm() {
        let d = JpegPixelDensity::Dpcm { x: 118, y: 118 };
        match d {
            JpegPixelDensity::Dpcm { x, y } => {
                assert_eq!(x, 118);
                assert_eq!(y, 118);
            }
            _ => panic!("expected Dpcm"),
        }
    }

    #[test]
    fn jpeg_pixel_density_aspect_ratio() {
        let d = JpegPixelDensity::AspectRatio { x: 1, y: 2 };
        match d {
            JpegPixelDensity::AspectRatio { x, y } => {
                assert_eq!(x, 1);
                assert_eq!(y, 2);
            }
            _ => panic!("expected AspectRatio"),
        }
    }

    #[test]
    fn jpeg_pixel_density_is_copy() {
        let d = JpegPixelDensity::Dpi { x: 72, y: 72 };
        let d2 = d;
        assert_eq!(d, d2);
    }

    #[test]
    fn jpeg_pixel_density_debug() {
        let d = JpegPixelDensity::Dpi { x: 300, y: 300 };
        let dbg = format!("{:?}", d);
        assert!(dbg.contains("Dpi"));
        assert!(dbg.contains("300"));
    }

    #[test]
    fn jpeg_pixel_density_eq() {
        let a = JpegPixelDensity::Dpi { x: 300, y: 300 };
        let b = JpegPixelDensity::Dpi { x: 300, y: 300 };
        let c = JpegPixelDensity::Dpi { x: 72, y: 72 };
        let d = JpegPixelDensity::Dpcm { x: 300, y: 300 };
        assert_eq!(a, b);
        assert_ne!(a, c);
        assert_ne!(a, d);
    }

    #[test]
    fn jpeg_pixel_density_non_square() {
        let d = JpegPixelDensity::Dpi { x: 300, y: 600 };
        match d {
            JpegPixelDensity::Dpi { x, y } => {
                assert_eq!(x, 300);
                assert_eq!(y, 600);
            }
            _ => panic!("expected Dpi"),
        }
    }

    #[test]
    fn jpeg_pixel_density_all_variants_debug() {
        // Cover all Debug arms.
        let _ = format!("{:?}", JpegPixelDensity::Dpi { x: 1, y: 1 });
        let _ = format!("{:?}", JpegPixelDensity::Dpcm { x: 1, y: 1 });
        let _ = format!("{:?}", JpegPixelDensity::AspectRatio { x: 1, y: 1 });
    }

    // ── JpegMetadata — constructibility ──────────────────────────────────

    fn make_minimal_metadata() -> JpegMetadata {
        JpegMetadata {
            exif: None,
            raw_exif: None,
            icc_profile: None,
            pixel_density: None,
            comments: vec![],
            source_bit_depth: JpegBitDepth::Eight,
            color_space: JpegColorSpace::Srgb,
        }
    }

    #[test]
    fn jpeg_metadata_minimal() {
        let meta = make_minimal_metadata();
        assert!(meta.exif.is_none());
        assert!(meta.raw_exif.is_none());
        assert!(meta.icc_profile.is_none());
        assert!(meta.pixel_density.is_none());
        assert!(meta.comments.is_empty());
        assert_eq!(meta.source_bit_depth, JpegBitDepth::Eight);
        assert_eq!(meta.color_space, JpegColorSpace::Srgb);
    }

    #[test]
    fn jpeg_metadata_fully_populated() {
        let exif = JpegExifInfo {
            orientation: Some(1),
            camera_make: Some("Sony".to_string()),
            ..Default::default()
        };
        let meta = JpegMetadata {
            exif: Some(exif),
            raw_exif: Some(vec![0x45, 0x78, 0x69, 0x66].into_boxed_slice()),
            icc_profile: Some(vec![0u8; 128].into_boxed_slice()),
            pixel_density: Some(JpegPixelDensity::Dpi { x: 300, y: 300 }),
            comments: vec!["test comment".to_string(), "another".to_string()],
            source_bit_depth: JpegBitDepth::Twelve,
            color_space: JpegColorSpace::IccTagged,
        };
        assert!(meta.exif.is_some());
        assert_eq!(meta.exif.as_ref().unwrap().orientation, Some(1));
        assert!(meta.raw_exif.is_some());
        assert!(meta.icc_profile.is_some());
        assert_eq!(meta.icc_profile.as_ref().unwrap().len(), 128);
        assert_eq!(
            meta.pixel_density,
            Some(JpegPixelDensity::Dpi { x: 300, y: 300 })
        );
        assert_eq!(meta.comments.len(), 2);
        assert_eq!(meta.comments[0], "test comment");
        assert_eq!(meta.source_bit_depth, JpegBitDepth::Twelve);
        assert_eq!(meta.color_space, JpegColorSpace::IccTagged);
    }

    #[test]
    fn jpeg_metadata_with_12bit_depth() {
        let meta = JpegMetadata {
            source_bit_depth: JpegBitDepth::Twelve,
            ..make_minimal_metadata()
        };
        assert_eq!(meta.source_bit_depth, JpegBitDepth::Twelve);
    }

    #[test]
    fn jpeg_metadata_clone() {
        let meta = JpegMetadata {
            exif: Some(JpegExifInfo {
                orientation: Some(3),
                ..Default::default()
            }),
            comments: vec!["hello".to_string()],
            ..make_minimal_metadata()
        };
        let cloned = meta.clone();
        assert_eq!(
            cloned.exif.as_ref().unwrap().orientation,
            meta.exif.as_ref().unwrap().orientation
        );
        assert_eq!(cloned.comments, meta.comments);
        assert_eq!(cloned.source_bit_depth, meta.source_bit_depth);
        assert_eq!(cloned.color_space, meta.color_space);
    }

    #[test]
    fn jpeg_metadata_debug() {
        let meta = make_minimal_metadata();
        let dbg = format!("{:?}", meta);
        assert!(dbg.contains("JpegMetadata"));
        assert!(dbg.contains("source_bit_depth"));
    }

    #[test]
    fn jpeg_metadata_icc_profile_boxed_slice() {
        // Verify ICC profile uses boxed slice, not Vec.
        let profile_data: Box<[u8]> = vec![1, 2, 3, 4].into_boxed_slice();
        let meta = JpegMetadata {
            icc_profile: Some(profile_data),
            ..make_minimal_metadata()
        };
        assert_eq!(meta.icc_profile.as_ref().unwrap().len(), 4);
        assert_eq!(meta.icc_profile.as_ref().unwrap()[0], 1);
    }

    #[test]
    fn jpeg_metadata_raw_exif_boxed_slice() {
        let raw: Box<[u8]> = vec![0x45, 0x78, 0x69, 0x66, 0x00, 0x00].into_boxed_slice();
        let meta = JpegMetadata {
            raw_exif: Some(raw),
            ..make_minimal_metadata()
        };
        assert_eq!(meta.raw_exif.as_ref().unwrap().len(), 6);
    }

    #[test]
    fn jpeg_metadata_multiple_comments() {
        let meta = JpegMetadata {
            comments: vec![
                "comment 1".to_string(),
                "comment 2".to_string(),
                "comment 3".to_string(),
            ],
            ..make_minimal_metadata()
        };
        assert_eq!(meta.comments.len(), 3);
        assert_eq!(meta.comments[2], "comment 3");
    }

    // ── JpegDecoded — constructibility ───────────────────────────────────

    #[test]
    fn jpeg_decoded_field_access() {
        let decoded = JpegDecoded {
            image: JpegImage::Srgb8(Image::fill(1, 1, Srgb8::new(0, 0, 0))),
            metadata: make_minimal_metadata(),
        };
        // Fields are directly accessible:
        let _img = decoded.image;
        let _meta = decoded.metadata;
    }

    #[test]
    fn jpeg_decoded_with_srgb_mono8() {
        let decoded = JpegDecoded {
            image: JpegImage::SrgbMono8(Image::fill(10, 10, SrgbMono8::new(128))),
            metadata: make_minimal_metadata(),
        };
        match &decoded.image {
            JpegImage::SrgbMono8(img) => {
                assert_eq!(img.width(), 10);
                assert_eq!(img.height(), 10);
            }
            _ => panic!("expected SrgbMono8"),
        }
    }

    #[test]
    fn jpeg_decoded_with_srgb_mono16() {
        let decoded = JpegDecoded {
            image: JpegImage::SrgbMono16(Image::fill(5, 5, SrgbMono16::new(1024))),
            metadata: JpegMetadata {
                source_bit_depth: JpegBitDepth::Twelve,
                ..make_minimal_metadata()
            },
        };
        match &decoded.image {
            JpegImage::SrgbMono16(img) => {
                assert_eq!(img.width(), 5);
                assert_eq!(img.height(), 5);
            }
            _ => panic!("expected SrgbMono16"),
        }
        assert_eq!(decoded.metadata.source_bit_depth, JpegBitDepth::Twelve);
    }

    #[test]
    fn jpeg_decoded_with_full_metadata() {
        let img = Image::fill(1, 1, Srgb8::new(0, 0, 0));
        let decoded = JpegDecoded {
            image: JpegImage::Srgb8(img),
            metadata: JpegMetadata {
                exif: Some(JpegExifInfo {
                    orientation: Some(6),
                    camera_make: Some("TestCam".to_string()),
                    ..Default::default()
                }),
                raw_exif: Some(vec![0xAA, 0xBB].into_boxed_slice()),
                icc_profile: Some(vec![0xCC, 0xDD].into_boxed_slice()),
                pixel_density: Some(JpegPixelDensity::Dpi { x: 300, y: 300 }),
                comments: vec!["photo comment".to_string()],
                source_bit_depth: JpegBitDepth::Eight,
                color_space: JpegColorSpace::IccTagged,
            },
        };
        match &decoded.image {
            JpegImage::Srgb8(img) => {
                assert_eq!(img.width(), 1);
                assert_eq!(img.height(), 1);
            }
            _ => panic!("expected Srgb8"),
        }
        let exif = decoded.metadata.exif.as_ref().unwrap();
        assert_eq!(exif.orientation, Some(6));
        assert_eq!(exif.camera_make.as_deref(), Some("TestCam"));
        assert_eq!(decoded.metadata.color_space, JpegColorSpace::IccTagged);
    }

    #[test]
    fn jpeg_decoded_debug() {
        let decoded = JpegDecoded {
            image: JpegImage::Srgb8(Image::fill(2, 2, Srgb8::new(0, 0, 0))),
            metadata: make_minimal_metadata(),
        };
        let dbg = format!("{:?}", decoded);
        assert!(dbg.contains("JpegDecoded"));
        assert!(dbg.contains("Srgb8(2x2)"));
        assert!(dbg.contains("JpegMetadata"));
    }

    // ── Exhaustive matching — compile-time guarantee ─────────────────────

    /// Verify that JpegImage supports exhaustive matching (no wildcard needed).
    #[test]
    fn jpeg_image_exhaustive_match() {
        let img = JpegImage::Srgb8(Image::fill(1, 1, Srgb8::new(0, 0, 0)));
        let name = match &img {
            JpegImage::SrgbMono8(_) => "SrgbMono8",
            JpegImage::SrgbMono16(_) => "SrgbMono16",
            JpegImage::Srgb8(_) => "Srgb8",
        };
        assert_eq!(name, "Srgb8");
    }

    /// Verify that JpegColorSpace supports exhaustive matching.
    #[test]
    fn jpeg_color_space_exhaustive_match() {
        let cs = JpegColorSpace::Srgb;
        let name = match cs {
            JpegColorSpace::Srgb => "Srgb",
            JpegColorSpace::IccTagged => "IccTagged",
        };
        assert_eq!(name, "Srgb");
    }

    /// Verify that JpegPixelDensity supports exhaustive matching.
    #[test]
    fn jpeg_pixel_density_exhaustive_match() {
        let d = JpegPixelDensity::Dpi { x: 72, y: 72 };
        let kind = match d {
            JpegPixelDensity::Dpi { .. } => "dpi",
            JpegPixelDensity::Dpcm { .. } => "dpcm",
            JpegPixelDensity::AspectRatio { .. } => "aspect",
        };
        assert_eq!(kind, "dpi");
    }

    // ── Type sizes ───────────────────────────────────────────────────────

    #[test]
    fn jpeg_color_space_is_small() {
        // Two-variant enum with no data — should be 1 byte.
        assert!(mem::size_of::<JpegColorSpace>() <= 2);
    }

    #[test]
    fn jpeg_pixel_density_is_small() {
        // Three variants each with two u16 fields + discriminant.
        // Should be compact (≤8 bytes).
        assert!(mem::size_of::<JpegPixelDensity>() <= 8);
    }

    #[test]
    fn jpeg_metadata_is_reasonable_size() {
        // JpegMetadata contains heap-allocated optionals; the struct itself
        // should be reasonably sized (no large inline data).
        let size = mem::size_of::<JpegMetadata>();
        // Should be well under 512 bytes for the struct itself.
        // The struct carries several Option<Box<[u8]>>, Option<JpegExifInfo>,
        // Vec<String>, etc. — all heap-allocated, but the struct shell with
        // its fat pointers and discriminants can reach ~280 bytes on 64-bit.
        assert!(
            size < 512,
            "JpegMetadata is {size} bytes — expected under 512"
        );
    }

    // ── Variant dispatch helpers ─────────────────────────────────────────

    /// Helper to get variant name as a string — useful for testing.
    fn variant_name(img: &JpegImage) -> &'static str {
        match img {
            JpegImage::SrgbMono8(_) => "SrgbMono8",
            JpegImage::SrgbMono16(_) => "SrgbMono16",
            JpegImage::Srgb8(_) => "Srgb8",
        }
    }

    #[test]
    fn variant_name_covers_all() {
        assert_eq!(
            variant_name(&JpegImage::SrgbMono8(Image::fill(1, 1, SrgbMono8::new(0)))),
            "SrgbMono8"
        );
        assert_eq!(
            variant_name(&JpegImage::SrgbMono16(Image::fill(
                1,
                1,
                SrgbMono16::new(0)
            ))),
            "SrgbMono16"
        );
        assert_eq!(
            variant_name(&JpegImage::Srgb8(Image::fill(1, 1, Srgb8::new(0, 0, 0)))),
            "Srgb8"
        );
    }

    // ── Image dimensions through JpegImage ───────────────────────────────

    #[test]
    fn jpeg_image_preserves_dimensions_mono8() {
        let img = JpegImage::SrgbMono8(Image::fill(100, 200, SrgbMono8::new(42)));
        match &img {
            JpegImage::SrgbMono8(i) => {
                assert_eq!(i.width(), 100);
                assert_eq!(i.height(), 200);
            }
            _ => panic!("wrong variant"),
        }
    }

    #[test]
    fn jpeg_image_preserves_dimensions_mono16() {
        let img = JpegImage::SrgbMono16(Image::fill(50, 75, SrgbMono16::new(1000)));
        match &img {
            JpegImage::SrgbMono16(i) => {
                assert_eq!(i.width(), 50);
                assert_eq!(i.height(), 75);
            }
            _ => panic!("wrong variant"),
        }
    }

    #[test]
    fn jpeg_image_preserves_dimensions_srgb8() {
        let img = JpegImage::Srgb8(Image::fill(1920, 1080, Srgb8::new(128, 64, 32)));
        match &img {
            JpegImage::Srgb8(i) => {
                assert_eq!(i.width(), 1920);
                assert_eq!(i.height(), 1080);
            }
            _ => panic!("wrong variant"),
        }
    }

    // ── Pixel data access through JpegImage ──────────────────────────────

    #[test]
    fn jpeg_image_pixel_data_accessible() {
        let img = JpegImage::Srgb8(Image::generate(3, 2, |x, y| {
            Srgb8::new(x as u8, y as u8, 0)
        }));
        match &img {
            JpegImage::Srgb8(i) => {
                assert_eq!(i.get(0, 0).unwrap().r.0, 0);
                assert_eq!(i.get(0, 0).unwrap().g.0, 0);
                assert_eq!(i.get(2, 1).unwrap().r.0, 2);
                assert_eq!(i.get(2, 1).unwrap().g.0, 1);
            }
            _ => panic!("wrong variant"),
        }
    }

    // ═════════════════════════════════════════════════════════════════════
    // TiffReader tests (task 2.1)
    // ═════════════════════════════════════════════════════════════════════

    #[test]
    fn tiff_reader_u8_at() {
        let data = [0xAA, 0xBB, 0xCC];
        let r = TiffReader::new(&data, ByteOrder::Little);
        assert_eq!(r.u8_at(0), Some(0xAA));
        assert_eq!(r.u8_at(1), Some(0xBB));
        assert_eq!(r.u8_at(2), Some(0xCC));
        assert_eq!(r.u8_at(3), None);
    }

    #[test]
    fn tiff_reader_u16_little_endian() {
        let data = [0x34, 0x12]; // LE: 0x1234
        let r = TiffReader::new(&data, ByteOrder::Little);
        assert_eq!(r.u16_at(0), Some(0x1234));
    }

    #[test]
    fn tiff_reader_u16_big_endian() {
        let data = [0x12, 0x34]; // BE: 0x1234
        let r = TiffReader::new(&data, ByteOrder::Big);
        assert_eq!(r.u16_at(0), Some(0x1234));
    }

    #[test]
    fn tiff_reader_u16_out_of_bounds() {
        let data = [0x12];
        let r = TiffReader::new(&data, ByteOrder::Little);
        assert_eq!(r.u16_at(0), None);
    }

    #[test]
    fn tiff_reader_u16_at_offset() {
        let data = [0x00, 0x00, 0x78, 0x56]; // LE at offset 2: 0x5678
        let r = TiffReader::new(&data, ByteOrder::Little);
        assert_eq!(r.u16_at(2), Some(0x5678));
    }

    #[test]
    fn tiff_reader_u32_little_endian() {
        let data = [0x78, 0x56, 0x34, 0x12]; // LE: 0x12345678
        let r = TiffReader::new(&data, ByteOrder::Little);
        assert_eq!(r.u32_at(0), Some(0x12345678));
    }

    #[test]
    fn tiff_reader_u32_big_endian() {
        let data = [0x12, 0x34, 0x56, 0x78]; // BE: 0x12345678
        let r = TiffReader::new(&data, ByteOrder::Big);
        assert_eq!(r.u32_at(0), Some(0x12345678));
    }

    #[test]
    fn tiff_reader_u32_out_of_bounds() {
        let data = [0x12, 0x34, 0x56];
        let r = TiffReader::new(&data, ByteOrder::Little);
        assert_eq!(r.u32_at(0), None);
    }

    #[test]
    fn tiff_reader_u32_partial_overlap() {
        // 5 bytes — u32 at offset 0 works, at offset 2 doesn't
        let data = [0x01, 0x02, 0x03, 0x04, 0x05];
        let r = TiffReader::new(&data, ByteOrder::Little);
        assert!(r.u32_at(0).is_some());
        assert_eq!(r.u32_at(2), None);
    }

    #[test]
    fn tiff_reader_rational_little_endian() {
        // num = 1 (LE), den = 250 (LE)
        let mut data = vec![];
        data.extend_from_slice(&1u32.to_le_bytes());
        data.extend_from_slice(&250u32.to_le_bytes());
        let r = TiffReader::new(&data, ByteOrder::Little);
        assert_eq!(r.rational_at(0), Some((1, 250)));
    }

    #[test]
    fn tiff_reader_rational_big_endian() {
        let mut data = vec![];
        data.extend_from_slice(&1u32.to_be_bytes());
        data.extend_from_slice(&250u32.to_be_bytes());
        let r = TiffReader::new(&data, ByteOrder::Big);
        assert_eq!(r.rational_at(0), Some((1, 250)));
    }

    #[test]
    fn tiff_reader_rational_out_of_bounds() {
        // Only 7 bytes — need 8 for a rational
        let data = [0u8; 7];
        let r = TiffReader::new(&data, ByteOrder::Little);
        assert_eq!(r.rational_at(0), None);
    }

    #[test]
    fn tiff_reader_rational_at_offset() {
        // Pad 4 bytes, then rational at offset 4
        let mut data = vec![0u8; 4];
        data.extend_from_slice(&50u32.to_le_bytes());
        data.extend_from_slice(&1u32.to_le_bytes());
        let r = TiffReader::new(&data, ByteOrder::Little);
        assert_eq!(r.rational_at(4), Some((50, 1)));
    }

    #[test]
    fn tiff_reader_empty_data() {
        let data: [u8; 0] = [];
        let r = TiffReader::new(&data, ByteOrder::Little);
        assert_eq!(r.u8_at(0), None);
        assert_eq!(r.u16_at(0), None);
        assert_eq!(r.u32_at(0), None);
        assert_eq!(r.rational_at(0), None);
        assert_eq!(r.len(), 0);
    }

    #[test]
    fn tiff_reader_len() {
        let data = [1, 2, 3, 4, 5];
        let r = TiffReader::new(&data, ByteOrder::Big);
        assert_eq!(r.len(), 5);
    }

    #[test]
    fn tiff_reader_u16_max_offset_no_overflow() {
        // Ensure we don't panic on usize near-overflow
        let data = [0xFFu8; 4];
        let r = TiffReader::new(&data, ByteOrder::Little);
        // Very large offset — should return None, not panic
        assert_eq!(r.u16_at(usize::MAX), None);
        assert_eq!(r.u32_at(usize::MAX), None);
        assert_eq!(r.rational_at(usize::MAX), None);
    }

    #[test]
    fn byte_order_debug_and_eq() {
        let le = ByteOrder::Little;
        let be = ByteOrder::Big;
        assert_eq!(le, ByteOrder::Little);
        assert_ne!(le, be);
        assert_eq!(format!("{:?}", le), "Little");
        assert_eq!(format!("{:?}", be), "Big");
        // Copy
        let le2 = le;
        assert_eq!(le, le2);
    }

    // ═════════════════════════════════════════════════════════════════════
    // IFD entry reader tests (task 2.2)
    // ═════════════════════════════════════════════════════════════════════

    /// Build a minimal IFD blob at offset 0: count (2 bytes) + N entries (12 bytes each).
    fn build_ifd_le(entries: &[(u16, u16, u32, u32)]) -> Vec<u8> {
        let mut buf = Vec::new();
        buf.extend_from_slice(&(entries.len() as u16).to_le_bytes());
        for &(tag, typ, count, val) in entries {
            buf.extend_from_slice(&tag.to_le_bytes());
            buf.extend_from_slice(&typ.to_le_bytes());
            buf.extend_from_slice(&count.to_le_bytes());
            buf.extend_from_slice(&val.to_le_bytes());
        }
        buf
    }

    fn build_ifd_be(entries: &[(u16, u16, u32, u32)]) -> Vec<u8> {
        let mut buf = Vec::new();
        buf.extend_from_slice(&(entries.len() as u16).to_be_bytes());
        for &(tag, typ, count, val) in entries {
            buf.extend_from_slice(&tag.to_be_bytes());
            buf.extend_from_slice(&typ.to_be_bytes());
            buf.extend_from_slice(&count.to_be_bytes());
            buf.extend_from_slice(&val.to_be_bytes());
        }
        buf
    }

    #[test]
    fn read_ifd_single_entry_le() {
        let data = build_ifd_le(&[(0x010F, 2, 6, 100)]);
        let r = TiffReader::new(&data, ByteOrder::Little);
        let entries = read_ifd_entries(&r, 0);
        assert_eq!(entries.len(), 1);
        assert_eq!(
            entries[0],
            IfdEntry {
                tag: 0x010F,
                tiff_type: 2,
                count: 6,
                value_or_offset: 100
            }
        );
    }

    #[test]
    fn read_ifd_single_entry_be() {
        let data = build_ifd_be(&[(0x010F, 2, 6, 100)]);
        let r = TiffReader::new(&data, ByteOrder::Big);
        let entries = read_ifd_entries(&r, 0);
        assert_eq!(entries.len(), 1);
        assert_eq!(
            entries[0],
            IfdEntry {
                tag: 0x010F,
                tiff_type: 2,
                count: 6,
                value_or_offset: 100
            }
        );
    }

    #[test]
    fn read_ifd_multiple_entries() {
        let data = build_ifd_le(&[(0x010F, 2, 6, 100), (0x0110, 2, 10, 200), (0x0112, 3, 1, 6)]);
        let r = TiffReader::new(&data, ByteOrder::Little);
        let entries = read_ifd_entries(&r, 0);
        assert_eq!(entries.len(), 3);
        assert_eq!(entries[0].tag, 0x010F);
        assert_eq!(entries[1].tag, 0x0110);
        assert_eq!(entries[2].tag, 0x0112);
        assert_eq!(entries[2].value_or_offset, 6); // orientation value
    }

    #[test]
    fn read_ifd_zero_entries() {
        let data = [0u8, 0]; // count = 0
        let r = TiffReader::new(&data, ByteOrder::Little);
        let entries = read_ifd_entries(&r, 0);
        assert!(entries.is_empty());
    }

    #[test]
    fn read_ifd_empty_data() {
        let data: [u8; 0] = [];
        let r = TiffReader::new(&data, ByteOrder::Little);
        let entries = read_ifd_entries(&r, 0);
        assert!(entries.is_empty());
    }

    #[test]
    fn read_ifd_out_of_bounds_offset() {
        let data = build_ifd_le(&[(0x010F, 2, 6, 100)]);
        let r = TiffReader::new(&data, ByteOrder::Little);
        let entries = read_ifd_entries(&r, 9999);
        assert!(entries.is_empty());
    }

    #[test]
    fn read_ifd_truncated_entry() {
        // Build 2-entry IFD but truncate after the first entry
        let mut data = build_ifd_le(&[(0x010F, 2, 6, 100), (0x0110, 2, 10, 200)]);
        data.truncate(2 + 12 + 6); // count + 1 full entry + partial second
        let r = TiffReader::new(&data, ByteOrder::Little);
        let entries = read_ifd_entries(&r, 0);
        // Should get only the first complete entry
        assert_eq!(entries.len(), 1);
    }

    #[test]
    fn read_ifd_capped_at_max() {
        // Craft data that claims 2000 entries but only has bytes for a few
        let mut data = Vec::new();
        data.extend_from_slice(&2000u16.to_le_bytes()); // claim 2000
        // Only provide 2 entries worth of data
        for _ in 0..2 {
            data.extend_from_slice(&0x0100u16.to_le_bytes());
            data.extend_from_slice(&3u16.to_le_bytes());
            data.extend_from_slice(&1u32.to_le_bytes());
            data.extend_from_slice(&42u32.to_le_bytes());
        }
        let r = TiffReader::new(&data, ByteOrder::Little);
        let entries = read_ifd_entries(&r, 0);
        // Capped at MAX_IFD_ENTRIES (1000), but only 2 entries' worth of data,
        // so we should get exactly 2 before hitting out-of-bounds.
        assert_eq!(entries.len(), 2);
    }

    #[test]
    fn read_ifd_at_nonzero_offset() {
        // 8 bytes of padding, then the IFD
        let mut data = vec![0u8; 8];
        data.extend_from_slice(&build_ifd_le(&[(0x0112, 3, 1, 1)]));
        let r = TiffReader::new(&data, ByteOrder::Little);
        let entries = read_ifd_entries(&r, 8);
        assert_eq!(entries.len(), 1);
        assert_eq!(
            entries[0],
            IfdEntry {
                tag: 0x0112,
                tiff_type: 3,
                count: 1,
                value_or_offset: 1
            }
        );
    }

    #[test]
    fn read_ifd_preserves_value_or_offset() {
        // SHORT type (3), count 1 — value fits inline (value_or_offset = 6)
        // LONG type (4), count 1 — value fits inline (value_or_offset = 99999)
        // ASCII type (2), count 20 — value is an offset (value_or_offset = 500)
        let data = build_ifd_le(&[
            (0x0112, 3, 1, 6),
            (0x8769, 4, 1, 99999),
            (0x010F, 2, 20, 500),
        ]);
        let r = TiffReader::new(&data, ByteOrder::Little);
        let entries = read_ifd_entries(&r, 0);
        assert_eq!(
            entries[0],
            IfdEntry {
                tag: 0x0112,
                tiff_type: 3,
                count: 1,
                value_or_offset: 6
            }
        );
        assert_eq!(
            entries[1],
            IfdEntry {
                tag: 0x8769,
                tiff_type: 4,
                count: 1,
                value_or_offset: 99999
            }
        );
        assert_eq!(
            entries[2],
            IfdEntry {
                tag: 0x010F,
                tiff_type: 2,
                count: 20,
                value_or_offset: 500
            }
        );
    }

    // ═════════════════════════════════════════════════════════════════════
    // ASCII string reader tests (task 2.3)
    // ═════════════════════════════════════════════════════════════════════

    #[test]
    fn read_ascii_simple() {
        let data = b"Canon\0";
        let r = TiffReader::new(data, ByteOrder::Little);
        assert_eq!(read_ascii(&r, 0, 6), Some("Canon".to_string()));
    }

    #[test]
    fn read_ascii_no_nul() {
        // Some malformed EXIF may not NUL-terminate
        let data = b"Nikon";
        let r = TiffReader::new(data, ByteOrder::Little);
        assert_eq!(read_ascii(&r, 0, 5), Some("Nikon".to_string()));
    }

    #[test]
    fn read_ascii_multiple_trailing_nuls() {
        let data = b"Test\0\0\0";
        let r = TiffReader::new(data, ByteOrder::Little);
        assert_eq!(read_ascii(&r, 0, 7), Some("Test".to_string()));
    }

    #[test]
    fn read_ascii_all_nuls() {
        let data = [0u8; 4];
        let r = TiffReader::new(&data, ByteOrder::Little);
        assert_eq!(read_ascii(&r, 0, 4), None);
    }

    #[test]
    fn read_ascii_empty_count() {
        let data = b"Hello\0";
        let r = TiffReader::new(data, ByteOrder::Little);
        assert_eq!(read_ascii(&r, 0, 0), None);
    }

    #[test]
    fn read_ascii_out_of_bounds() {
        let data = b"Hi\0";
        let r = TiffReader::new(data, ByteOrder::Little);
        assert_eq!(read_ascii(&r, 0, 10), None);
    }

    #[test]
    fn read_ascii_at_offset() {
        let mut data = vec![0u8; 10];
        data.extend_from_slice(b"Sony\0");
        let r = TiffReader::new(&data, ByteOrder::Little);
        assert_eq!(read_ascii(&r, 10, 5), Some("Sony".to_string()));
    }

    #[test]
    fn read_ascii_datetime_format() {
        let data = b"2025:01:15 12:30:00\0";
        let r = TiffReader::new(data, ByteOrder::Little);
        let result = read_ascii(&r, 0, 20);
        assert_eq!(result, Some("2025:01:15 12:30:00".to_string()));
    }

    #[test]
    fn read_ascii_utf8_passthrough() {
        // UTF-8 encoded string (German umlaut)
        let data = "Müller\0".as_bytes();
        let r = TiffReader::new(data, ByteOrder::Little);
        let result = read_ascii(&r, 0, data.len() as u32);
        assert_eq!(result, Some("Müller".to_string()));
    }

    #[test]
    fn read_ascii_latin1_fallback() {
        // Latin-1: 0xFC = ü, 0xE4 = ä — not valid UTF-8 as a sequence
        let data = [0x4Du8, 0xFC, 0x6C, 0x6C, 0x65, 0x72, 0x00]; // "Müller\0" in Latin-1
        let r = TiffReader::new(&data, ByteOrder::Little);
        let result = read_ascii(&r, 0, 7);
        assert_eq!(result, Some("Müller".to_string()));
    }

    #[test]
    fn read_ascii_single_char() {
        let data = b"A\0";
        let r = TiffReader::new(data, ByteOrder::Little);
        assert_eq!(read_ascii(&r, 0, 2), Some("A".to_string()));
    }

    #[test]
    fn read_ascii_single_nul() {
        let data = [0u8];
        let r = TiffReader::new(&data, ByteOrder::Little);
        assert_eq!(read_ascii(&r, 0, 1), None);
    }

    #[test]
    fn read_ifd_ascii_inline_short_string() {
        // An ASCII value with count <= 4 is stored inline in the value_or_offset field.
        // "OK\0" = 3 bytes, stored inline starting at the entry's value offset.
        let mut data = Vec::new();
        // Simulate: the 4-byte value field contains "OK\0\0"
        data.extend_from_slice(b"OK\0\0");
        let r = TiffReader::new(&data, ByteOrder::Little);
        // entry_value_offset = 0, pointing to the "OK\0\0" bytes
        let result = read_ifd_ascii(&r, 3, 0 /* ignored for inline */, 0);
        assert_eq!(result, Some("OK".to_string()));
    }

    #[test]
    fn read_ifd_ascii_offset_referenced() {
        // count > 4, so value_or_offset is an offset.
        let mut data = vec![0u8; 50];
        // Place "Canon EOS R5\0" at offset 30
        let s = b"Canon EOS R5\0";
        data[30..30 + s.len()].copy_from_slice(s);
        let r = TiffReader::new(&data, ByteOrder::Little);
        let result = read_ifd_ascii(&r, 13, 30, 0 /* ignored for offset */);
        assert_eq!(result, Some("Canon EOS R5".to_string()));
    }

    #[test]
    fn read_ifd_ascii_inline_4_bytes_exact() {
        // Exactly 4 bytes inline: "RGB\0"
        let data = b"RGB\0";
        let r = TiffReader::new(data, ByteOrder::Little);
        let result = read_ifd_ascii(&r, 4, 0, 0);
        assert_eq!(result, Some("RGB".to_string()));
    }

    #[test]
    fn read_ifd_ascii_inline_1_byte() {
        // Single byte inline: "N\0" but count=2 ≤ 4
        let data = b"N\0\0\0";
        let r = TiffReader::new(data, ByteOrder::Little);
        let result = read_ifd_ascii(&r, 2, 0, 0);
        assert_eq!(result, Some("N".to_string()));
    }

    // ═════════════════════════════════════════════════════════════════════
    // parse_tiff_exif tests (refactored internal entry point)
    // ═════════════════════════════════════════════════════════════════════

    #[test]
    fn parse_tiff_exif_empty() {
        assert_eq!(parse_tiff_exif(b""), None);
    }

    #[test]
    fn parse_tiff_exif_too_short() {
        assert_eq!(parse_tiff_exif(b"II\x2a\x00"), None);
    }

    #[test]
    fn parse_tiff_exif_valid_le_zero_entries() {
        // Minimal valid TIFF: II, magic 42, IFD0 offset=8
        // At TIFF offset 8: entry count = 0, next-IFD = 0
        let mut data = vec![0u8; 14];
        data[0..2].copy_from_slice(b"II");
        data[2..4].copy_from_slice(&42u16.to_le_bytes());
        data[4..8].copy_from_slice(&8u32.to_le_bytes());
        // IFD count = 0
        data[8..10].copy_from_slice(&0u16.to_le_bytes());
        // next-IFD = 0
        data[10..14].copy_from_slice(&0u32.to_le_bytes());
        let info = parse_tiff_exif(&data).unwrap();
        assert_eq!(info, JpegExifInfo::default());
    }

    #[test]
    fn parse_tiff_exif_matches_parse_exif() {
        // Verify that parse_exif("Exif\0\0" ++ tiff) == parse_tiff_exif(tiff)
        let data = build_exif_le(&[(0x0112, 3, 1, 3)], &[]);
        let from_exif = parse_exif(&data).unwrap();
        let from_tiff = parse_tiff_exif(&data[6..]).unwrap();
        assert_eq!(from_exif, from_tiff);
    }

    // ═════════════════════════════════════════════════════════════════════
    // dms_to_decimal tests (task 2.4)
    // ═════════════════════════════════════════════════════════════════════

    #[test]
    fn dms_to_decimal_north_latitude() {
        // 40° 26' 46" N → 40.446111...
        let result = dms_to_decimal((40, 1), (26, 1), (46, 1), b'N');
        let val = result.unwrap();
        assert!((val - 40.44611111).abs() < 1e-6, "got {val}");
    }

    #[test]
    fn dms_to_decimal_south_latitude() {
        // 33° 51' 54" S → -33.865
        let result = dms_to_decimal((33, 1), (51, 1), (54, 1), b'S');
        let val = result.unwrap();
        assert!(val < 0.0, "South should be negative");
        assert!((val - (-33.865)).abs() < 1e-6, "got {val}");
    }

    #[test]
    fn dms_to_decimal_east_longitude() {
        // 79° 58' 56" E → 79.98222...
        let result = dms_to_decimal((79, 1), (58, 1), (56, 1), b'E');
        let val = result.unwrap();
        assert!(val > 0.0);
        assert!((val - 79.98222222).abs() < 1e-6, "got {val}");
    }

    #[test]
    fn dms_to_decimal_west_longitude() {
        // 73° 59' 11" W → -73.98638...
        let result = dms_to_decimal((73, 1), (59, 1), (11, 1), b'W');
        let val = result.unwrap();
        assert!(val < 0.0, "West should be negative");
        assert!((val - (-73.98638888)).abs() < 1e-6, "got {val}");
    }

    #[test]
    fn dms_to_decimal_zero_coordinates() {
        let result = dms_to_decimal((0, 1), (0, 1), (0, 1), b'N');
        assert_eq!(result, Some(0.0));
    }

    #[test]
    fn dms_to_decimal_fractional_seconds() {
        // Fractional seconds via rational: 46.5 seconds = (93, 2)
        // 40° 26' 46.5" N → 40.44625
        let result = dms_to_decimal((40, 1), (26, 1), (93, 2), b'N');
        let val = result.unwrap();
        assert!((val - 40.44625).abs() < 1e-8, "got {val}");
    }

    #[test]
    fn dms_to_decimal_fractional_degrees() {
        // Some GPS stores everything in degrees: (40446111, 1000000), (0,1), (0,1)
        let result = dms_to_decimal((40446111, 1000000), (0, 1), (0, 1), b'N');
        let val = result.unwrap();
        assert!((val - 40.446111).abs() < 1e-6, "got {val}");
    }

    #[test]
    fn dms_to_decimal_zero_denominator_degrees() {
        assert_eq!(dms_to_decimal((40, 0), (26, 1), (46, 1), b'N'), None);
    }

    #[test]
    fn dms_to_decimal_zero_denominator_minutes() {
        assert_eq!(dms_to_decimal((40, 1), (26, 0), (46, 1), b'N'), None);
    }

    #[test]
    fn dms_to_decimal_zero_denominator_seconds() {
        assert_eq!(dms_to_decimal((40, 1), (26, 1), (46, 0), b'N'), None);
    }

    #[test]
    fn dms_to_decimal_degrees_out_of_range() {
        // 360° is invalid
        assert_eq!(dms_to_decimal((360, 1), (0, 1), (0, 1), b'N'), None);
        assert_eq!(dms_to_decimal((500, 1), (0, 1), (0, 1), b'E'), None);
    }

    #[test]
    fn dms_to_decimal_minutes_out_of_range() {
        assert_eq!(dms_to_decimal((40, 1), (60, 1), (0, 1), b'N'), None);
        assert_eq!(dms_to_decimal((40, 1), (99, 1), (0, 1), b'N'), None);
    }

    #[test]
    fn dms_to_decimal_seconds_out_of_range() {
        assert_eq!(dms_to_decimal((40, 1), (26, 1), (60, 1), b'N'), None);
        assert_eq!(dms_to_decimal((40, 1), (26, 1), (120, 1), b'N'), None);
    }

    #[test]
    fn dms_to_decimal_invalid_ref_char() {
        assert_eq!(dms_to_decimal((40, 1), (26, 1), (46, 1), b'X'), None);
        assert_eq!(dms_to_decimal((40, 1), (26, 1), (46, 1), b'n'), None);
        assert_eq!(dms_to_decimal((40, 1), (26, 1), (46, 1), 0), None);
    }

    #[test]
    fn dms_to_decimal_max_valid() {
        // 359° 59' 59" N — boundary: just under 360
        let result = dms_to_decimal((359, 1), (59, 1), (59, 1), b'N');
        let val = result.unwrap();
        assert!(val < 360.0);
        assert!(val > 359.99);
    }

    // ═════════════════════════════════════════════════════════════════════
    // parse_exif tests (tasks 2.5 / 2.6)
    // ═════════════════════════════════════════════════════════════════════

    // ── Test helpers for building synthetic EXIF data ─────────────────

    /// Write a u16 in little-endian at the given offset.
    fn put_u16_le(buf: &mut [u8], offset: usize, val: u16) {
        buf[offset..offset + 2].copy_from_slice(&val.to_le_bytes());
    }

    /// Write a u32 in little-endian at the given offset.
    fn put_u32_le(buf: &mut [u8], offset: usize, val: u32) {
        buf[offset..offset + 4].copy_from_slice(&val.to_le_bytes());
    }

    /// Write a u16 in big-endian at the given offset.
    fn put_u16_be(buf: &mut [u8], offset: usize, val: u16) {
        buf[offset..offset + 2].copy_from_slice(&val.to_be_bytes());
    }

    /// Write a u32 in big-endian at the given offset.
    fn put_u32_be(buf: &mut [u8], offset: usize, val: u32) {
        buf[offset..offset + 4].copy_from_slice(&val.to_be_bytes());
    }

    /// Build a minimal valid EXIF blob (little-endian) with the given
    /// IFD0 entries placed after the header.  `extra` bytes are appended
    /// after the IFD for offset-referenced values.
    ///
    /// Layout:
    /// - [0..6]: `Exif\0\0`
    /// - [6..8]: `II` (LE byte order)
    /// - [8..10]: magic 42
    /// - [10..14]: IFD0 offset = 8 (relative to TIFF start, i.e. byte 14 in raw)
    /// - [14..16]: entry count
    /// - [16..]: 12-byte IFD entries
    /// - After entries: 4-byte next-IFD pointer (0)
    /// - Then: `extra` bytes for offset-referenced data
    ///
    /// Returns `(raw_exif_bytes, tiff_data_start_in_raw, ifd_entries_start_in_raw)`.
    fn build_exif_le(entries: &[(u16, u16, u32, u32)], extra: &[u8]) -> Vec<u8> {
        let ifd0_tiff_offset: u32 = 8; // IFD0 starts at offset 8 within the TIFF stream
        let entry_count = entries.len();
        let ifd_size = 2 + entry_count * 12 + 4; // count + entries + next-IFD pointer
        let tiff_size = 8 + ifd_size + extra.len(); // header + IFD + extra
        let total = 6 + tiff_size; // Exif\0\0 + TIFF

        let mut buf = vec![0u8; total];

        // Exif header
        buf[0..6].copy_from_slice(b"Exif\0\0");

        // TIFF header (starts at raw offset 6)
        buf[6..8].copy_from_slice(b"II"); // little-endian
        put_u16_le(&mut buf, 8, 42); // magic
        put_u32_le(&mut buf, 10, ifd0_tiff_offset); // IFD0 offset

        // IFD0 (starts at raw offset 14, TIFF offset 8)
        let ifd_raw_start = 14;
        put_u16_le(&mut buf, ifd_raw_start, entry_count as u16);

        for (i, &(tag, typ, count, val)) in entries.iter().enumerate() {
            let base = ifd_raw_start + 2 + i * 12;
            put_u16_le(&mut buf, base, tag);
            put_u16_le(&mut buf, base + 2, typ);
            put_u32_le(&mut buf, base + 4, count);
            put_u32_le(&mut buf, base + 8, val);
        }

        // next-IFD pointer = 0 (no more IFDs)
        let next_ifd_off = ifd_raw_start + 2 + entry_count * 12;
        put_u32_le(&mut buf, next_ifd_off, 0);

        // Extra data for offset-referenced values
        let extra_start = next_ifd_off + 4;
        buf[extra_start..extra_start + extra.len()].copy_from_slice(extra);

        buf
    }

    /// Build a minimal valid EXIF blob (big-endian) analogous to `build_exif_le`.
    fn build_exif_be(entries: &[(u16, u16, u32, u32)], extra: &[u8]) -> Vec<u8> {
        let ifd0_tiff_offset: u32 = 8;
        let entry_count = entries.len();
        let ifd_size = 2 + entry_count * 12 + 4;
        let tiff_size = 8 + ifd_size + extra.len();
        let total = 6 + tiff_size;

        let mut buf = vec![0u8; total];

        buf[0..6].copy_from_slice(b"Exif\0\0");
        buf[6..8].copy_from_slice(b"MM"); // big-endian
        put_u16_be(&mut buf, 8, 42);
        put_u32_be(&mut buf, 10, ifd0_tiff_offset);

        let ifd_raw_start = 14;
        put_u16_be(&mut buf, ifd_raw_start, entry_count as u16);

        for (i, &(tag, typ, count, val)) in entries.iter().enumerate() {
            let base = ifd_raw_start + 2 + i * 12;
            put_u16_be(&mut buf, base, tag);
            put_u16_be(&mut buf, base + 2, typ);
            put_u32_be(&mut buf, base + 4, count);
            put_u32_be(&mut buf, base + 8, val);
        }

        let next_ifd_off = ifd_raw_start + 2 + entry_count * 12;
        put_u32_be(&mut buf, next_ifd_off, 0);

        let extra_start = next_ifd_off + 4;
        buf[extra_start..extra_start + extra.len()].copy_from_slice(extra);

        buf
    }

    /// Compute the TIFF offset of the "extra" region that follows the IFD
    /// in our synthetic EXIF blobs.
    ///
    /// The TIFF stream starts at raw offset 6.
    /// IFD0 starts at TIFF offset 8.
    /// IFD0 = 2 (count) + entries*12 + 4 (next-IFD pointer).
    /// Extra starts right after.
    fn extra_tiff_offset(entry_count: usize) -> u32 {
        // TIFF offset of IFD0 = 8
        // IFD0 size = 2 + entry_count * 12 + 4
        (8 + 2 + entry_count * 12 + 4) as u32
    }

    // ── Basic EXIF parse tests ───────────────────────────────────────

    #[test]
    fn parse_exif_completely_empty() {
        assert_eq!(parse_exif(b""), None);
    }

    #[test]
    fn parse_exif_too_short() {
        assert_eq!(parse_exif(b"Exif\0\0II"), None);
    }

    #[test]
    fn parse_exif_wrong_header() {
        let mut data = build_exif_le(&[], &[]);
        data[0..4].copy_from_slice(b"JFIF");
        assert_eq!(parse_exif(&data), None);
    }

    #[test]
    fn parse_exif_wrong_magic() {
        let mut data = build_exif_le(&[], &[]);
        // Overwrite magic 42 with 99
        put_u16_le(&mut data, 8, 99);
        assert_eq!(parse_exif(&data), None);
    }

    #[test]
    fn parse_exif_wrong_byte_order() {
        let mut data = build_exif_le(&[], &[]);
        data[6..8].copy_from_slice(b"XX");
        assert_eq!(parse_exif(&data), None);
    }

    #[test]
    fn parse_exif_valid_header_zero_entries() {
        let data = build_exif_le(&[], &[]);
        let info = parse_exif(&data).unwrap();
        assert_eq!(info, JpegExifInfo::default());
    }

    #[test]
    fn parse_exif_valid_header_zero_entries_be() {
        let data = build_exif_be(&[], &[]);
        let info = parse_exif(&data).unwrap();
        assert_eq!(info, JpegExifInfo::default());
    }

    // ── Orientation ──────────────────────────────────────────────────

    #[test]
    fn parse_exif_orientation_le() {
        // Orientation (0x0112), SHORT (3), count=1, value=6
        // In LE, a SHORT value=6 stored inline: low 16 bits = 6 → u32 = 6
        let data = build_exif_le(&[(0x0112, 3, 1, 6)], &[]);
        let info = parse_exif(&data).unwrap();
        assert_eq!(info.orientation, Some(6));
    }

    #[test]
    fn parse_exif_orientation_be() {
        // In BE, a SHORT value=6 inline: the u16 is at bytes [8..10] of the entry,
        // which we read with u16_at(entry_val_off). The 4-byte value field has
        // the SHORT in the first 2 bytes. We store as u32 in BE:
        // 6 as u16 in first 2 bytes → u32 = 6 << 16 = 0x00060000
        // But our builder writes the u32 as BE, so put_u32_be(6 << 16).
        // When we reader.u16_at(entry_val_off), it reads the first 2 bytes
        // of the value field as BE u16 → 6.
        let data = build_exif_be(&[(0x0112, 3, 1, 6 << 16)], &[]);
        let info = parse_exif(&data).unwrap();
        assert_eq!(info.orientation, Some(6));
    }

    #[test]
    fn parse_exif_orientation_all_valid_values() {
        for v in 1u16..=8 {
            let data = build_exif_le(&[(0x0112, 3, 1, v as u32)], &[]);
            let info = parse_exif(&data).unwrap();
            assert_eq!(info.orientation, Some(v as u8), "orientation {v}");
        }
    }

    #[test]
    fn parse_exif_orientation_zero_invalid() {
        let data = build_exif_le(&[(0x0112, 3, 1, 0)], &[]);
        let info = parse_exif(&data).unwrap();
        assert_eq!(info.orientation, None);
    }

    #[test]
    fn parse_exif_orientation_9_invalid() {
        let data = build_exif_le(&[(0x0112, 3, 1, 9)], &[]);
        let info = parse_exif(&data).unwrap();
        assert_eq!(info.orientation, None);
    }

    #[test]
    fn parse_exif_orientation_wrong_type_ignored() {
        // Orientation with wrong TIFF type (LONG instead of SHORT) → skip
        let data = build_exif_le(&[(0x0112, 4, 1, 6)], &[]);
        let info = parse_exif(&data).unwrap();
        assert_eq!(info.orientation, None);
    }

    // ── ASCII fields (Make, Model, Software, DateTime) ───────────────

    #[test]
    fn parse_exif_make_inline() {
        // Make (0x010F), ASCII (2), count=4 (≤4 → inline), value="Hi!\0"
        // The 4-byte value field contains "Hi!\0" = [0x48, 0x69, 0x21, 0x00]
        // LE u32 of those bytes: 0x00216948
        let val = u32::from_le_bytes([b'H', b'i', b'!', 0]);
        let data = build_exif_le(&[(0x010F, 2, 4, val)], &[]);
        let info = parse_exif(&data).unwrap();
        assert_eq!(info.camera_make, Some("Hi!".to_string()));
    }

    #[test]
    fn parse_exif_model_offset_referenced() {
        // Model (0x0110), ASCII (2), count=6, offset → extra region
        let extra_off = extra_tiff_offset(1);
        let model_bytes = b"Canon\0";
        let data = build_exif_le(&[(0x0110, 2, 6, extra_off)], model_bytes);
        let info = parse_exif(&data).unwrap();
        assert_eq!(info.camera_model, Some("Canon".to_string()));
    }

    #[test]
    fn parse_exif_software_offset_referenced() {
        let extra_off = extra_tiff_offset(1);
        let sw_bytes = b"Lightroom 6.0\0";
        let data = build_exif_le(&[(0x0131, 2, 14, extra_off)], sw_bytes);
        let info = parse_exif(&data).unwrap();
        assert_eq!(info.software, Some("Lightroom 6.0".to_string()));
    }

    #[test]
    fn parse_exif_datetime_offset_referenced() {
        let extra_off = extra_tiff_offset(1);
        let dt_bytes = b"2025:01:15 12:30:00\0";
        let data = build_exif_le(&[(0x0132, 2, 20, extra_off)], dt_bytes);
        let info = parse_exif(&data).unwrap();
        assert_eq!(info.datetime, Some("2025:01:15 12:30:00".to_string()));
    }

    #[test]
    fn parse_exif_ascii_wrong_type_ignored() {
        // Make with wrong type (SHORT instead of ASCII) → skip
        let data = build_exif_le(&[(0x010F, 3, 1, 42)], &[]);
        let info = parse_exif(&data).unwrap();
        assert_eq!(info.camera_make, None);
    }

    // ── Multiple IFD0 fields ─────────────────────────────────────────

    #[test]
    fn parse_exif_multiple_ifd0_fields() {
        // Build extra: make at extra_off, model at extra_off+6, datetime at extra_off+12
        let make_str = b"Nikon\0";
        let model_str = b"D850\0\0"; // pad to 6 bytes for alignment
        let dt_str = b"2024:06:01 09:15:30\0";
        let mut extra = Vec::new();
        extra.extend_from_slice(make_str); // offset 0
        extra.extend_from_slice(model_str); // offset 6
        extra.extend_from_slice(dt_str); // offset 12

        let base_off = extra_tiff_offset(4); // 4 entries
        let entries = [
            (0x010F, 2u16, 6u32, base_off), // Make
            (0x0110, 2, 6, base_off + 6),   // Model
            (0x0112, 3, 1, 1u32),           // Orientation = 1
            (0x0132, 2, 20, base_off + 12), // DateTime
        ];
        let data = build_exif_le(&entries, &extra);
        let info = parse_exif(&data).unwrap();
        assert_eq!(info.camera_make, Some("Nikon".to_string()));
        assert_eq!(info.camera_model, Some("D850".to_string()));
        assert_eq!(info.orientation, Some(1));
        assert_eq!(info.datetime, Some("2024:06:01 09:15:30".to_string()));
    }

    // ── EXIF sub-IFD ─────────────────────────────────────────────────

    /// Build a complete EXIF blob with an IFD0 → EXIF sub-IFD chain (LE).
    ///
    /// Layout:
    /// - Exif\0\0 (6 bytes)
    /// - TIFF header (8 bytes at raw 6..14)
    /// - IFD0 (at TIFF offset 8):
    ///   - 1 entry: ExifIFDPointer (0x8769) pointing to the sub-IFD
    ///   - next-IFD = 0
    /// - EXIF sub-IFD (placed after IFD0 + next-IFD-ptr):
    ///   - `exif_entries` IFD entries
    ///   - next-IFD = 0
    /// - Extra data after the sub-IFD
    fn build_exif_with_sub_ifd_le(
        exif_entries: &[(u16, u16, u32, u32)],
        extra: &[u8],
    ) -> (Vec<u8>, u32) {
        // IFD0: 1 entry (ExifIFDPointer)
        let ifd0_tiff_off: u32 = 8;
        let ifd0_size = 2 + 1 * 12 + 4; // 18 bytes
        let exif_ifd_tiff_off = ifd0_tiff_off + ifd0_size as u32;

        let exif_entry_count = exif_entries.len();
        let exif_ifd_size = 2 + exif_entry_count * 12 + 4;
        let extra_tiff_off = exif_ifd_tiff_off + exif_ifd_size as u32;

        let tiff_size = 8 + ifd0_size + exif_ifd_size + extra.len();
        let total = 6 + tiff_size;
        let mut buf = vec![0u8; total];

        // Exif header
        buf[0..6].copy_from_slice(b"Exif\0\0");
        buf[6..8].copy_from_slice(b"II");
        put_u16_le(&mut buf, 8, 42);
        put_u32_le(&mut buf, 10, ifd0_tiff_off);

        // IFD0
        let ifd0_raw = 6 + ifd0_tiff_off as usize;
        put_u16_le(&mut buf, ifd0_raw, 1); // 1 entry
        // Entry: ExifIFDPointer (0x8769), LONG (4), count=1, value = exif_ifd_tiff_off
        let e0 = ifd0_raw + 2;
        put_u16_le(&mut buf, e0, 0x8769);
        put_u16_le(&mut buf, e0 + 2, 4); // LONG
        put_u32_le(&mut buf, e0 + 4, 1); // count
        put_u32_le(&mut buf, e0 + 8, exif_ifd_tiff_off);
        // next-IFD = 0
        put_u32_le(&mut buf, e0 + 12, 0);

        // EXIF sub-IFD
        let exif_raw = 6 + exif_ifd_tiff_off as usize;
        put_u16_le(&mut buf, exif_raw, exif_entry_count as u16);
        for (i, &(tag, typ, count, val)) in exif_entries.iter().enumerate() {
            let base = exif_raw + 2 + i * 12;
            put_u16_le(&mut buf, base, tag);
            put_u16_le(&mut buf, base + 2, typ);
            put_u32_le(&mut buf, base + 4, count);
            put_u32_le(&mut buf, base + 8, val);
        }
        // next-IFD = 0
        let next_ptr = exif_raw + 2 + exif_entry_count * 12;
        put_u32_le(&mut buf, next_ptr, 0);

        // Extra data
        let extra_raw = 6 + extra_tiff_off as usize;
        buf[extra_raw..extra_raw + extra.len()].copy_from_slice(extra);

        (buf, extra_tiff_off)
    }

    #[test]
    fn parse_exif_sub_ifd_exposure_time() {
        // ExposureTime (0x829A), RATIONAL, count=1, offset → extra
        // Value: 1/250 = (1, 250)
        let mut extra = [0u8; 8];
        put_u32_le(&mut extra, 0, 1); // numerator
        put_u32_le(&mut extra, 4, 250); // denominator

        let (data, extra_off) = build_exif_with_sub_ifd_le(
            &[(0x829A, 5, 1, 0)], // placeholder offset, fix below
            &extra,
        );
        // Fix the offset in the sub-IFD entry's value_or_offset field
        let mut data = data;
        // The sub-IFD entry's value_or_offset is at:
        // raw = 6 + exif_ifd_tiff_off + 2 + 0 * 12 + 8
        let ifd0_size = 2 + 1 * 12 + 4;
        let exif_ifd_tiff_off = 8 + ifd0_size as usize;
        let val_off_raw = 6 + exif_ifd_tiff_off + 2 + 8;
        put_u32_le(&mut data, val_off_raw, extra_off);

        let info = parse_exif(&data).unwrap();
        assert_eq!(info.exposure_time, Some((1, 250)));
    }

    #[test]
    fn parse_exif_sub_ifd_fnumber() {
        let mut extra = [0u8; 8];
        put_u32_le(&mut extra, 0, 28); // numerator
        put_u32_le(&mut extra, 4, 10); // denominator → f/2.8

        let (mut data, extra_off) = build_exif_with_sub_ifd_le(&[(0x829D, 5, 1, 0)], &extra);
        let ifd0_size = 2 + 1 * 12 + 4;
        let exif_ifd_tiff_off = 8 + ifd0_size;
        let val_off_raw = 6 + exif_ifd_tiff_off + 2 + 8;
        put_u32_le(&mut data, val_off_raw, extra_off);

        let info = parse_exif(&data).unwrap();
        assert_eq!(info.f_number, Some((28, 10)));
    }

    #[test]
    fn parse_exif_sub_ifd_iso_speed() {
        // ISOSpeedRatings (0x8827), SHORT (3), count=1, value=400
        let (data, _) = build_exif_with_sub_ifd_le(&[(0x8827, 3, 1, 400)], &[]);
        let info = parse_exif(&data).unwrap();
        assert_eq!(info.iso_speed, Some(400));
    }

    #[test]
    fn parse_exif_sub_ifd_focal_length() {
        let mut extra = [0u8; 8];
        put_u32_le(&mut extra, 0, 50); // numerator
        put_u32_le(&mut extra, 4, 1); // denominator → 50mm

        let (mut data, extra_off) = build_exif_with_sub_ifd_le(&[(0x920A, 5, 1, 0)], &extra);
        let ifd0_size = 2 + 1 * 12 + 4;
        let exif_ifd_tiff_off = 8 + ifd0_size;
        let val_off_raw = 6 + exif_ifd_tiff_off + 2 + 8;
        put_u32_le(&mut data, val_off_raw, extra_off);

        let info = parse_exif(&data).unwrap();
        assert_eq!(info.focal_length, Some((50, 1)));
    }

    #[test]
    fn parse_exif_sub_ifd_datetime_original() {
        let dt = b"2024:12:25 08:00:00\0";
        let (mut data, extra_off) = build_exif_with_sub_ifd_le(&[(0x9003, 2, 20, 0)], dt);
        let ifd0_size = 2 + 1 * 12 + 4;
        let exif_ifd_tiff_off = 8 + ifd0_size;
        let val_off_raw = 6 + exif_ifd_tiff_off + 2 + 8;
        put_u32_le(&mut data, val_off_raw, extra_off);

        let info = parse_exif(&data).unwrap();
        assert_eq!(
            info.datetime_original,
            Some("2024:12:25 08:00:00".to_string())
        );
    }

    #[test]
    fn parse_exif_missing_exif_sub_ifd() {
        // IFD0 has no ExifIFDPointer → all EXIF sub-IFD fields remain None
        let data = build_exif_le(&[(0x0112, 3, 1, 1)], &[]);
        let info = parse_exif(&data).unwrap();
        assert_eq!(info.orientation, Some(1));
        assert_eq!(info.exposure_time, None);
        assert_eq!(info.f_number, None);
        assert_eq!(info.iso_speed, None);
        assert_eq!(info.focal_length, None);
        assert_eq!(info.datetime_original, None);
    }

    #[test]
    fn parse_exif_multiple_exif_sub_ifd_entries() {
        // Two entries in EXIF sub-IFD: ISO and a RATIONAL focal length
        let mut extra = [0u8; 8];
        put_u32_le(&mut extra, 0, 85); // focal length numerator
        put_u32_le(&mut extra, 4, 1); // focal length denominator

        let (mut data, extra_off) = build_exif_with_sub_ifd_le(
            &[
                (0x8827, 3, 1, 200), // ISO 200
                (0x920A, 5, 1, 0),   // focal length → fix offset
            ],
            &extra,
        );
        // Fix focal length offset (entry index 1)
        let ifd0_size = 2 + 1 * 12 + 4;
        let exif_ifd_tiff_off = 8 + ifd0_size;
        let val_off_raw = 6 + exif_ifd_tiff_off + 2 + 1 * 12 + 8;
        put_u32_le(&mut data, val_off_raw, extra_off);

        let info = parse_exif(&data).unwrap();
        assert_eq!(info.iso_speed, Some(200));
        assert_eq!(info.focal_length, Some((85, 1)));
    }

    // ── GPS sub-IFD ──────────────────────────────────────────────────

    /// Build a complete EXIF blob with IFD0 → GPS sub-IFD chain (LE).
    fn build_exif_with_gps_ifd_le(
        gps_entries: &[(u16, u16, u32, u32)],
        extra: &[u8],
    ) -> (Vec<u8>, u32) {
        let ifd0_tiff_off: u32 = 8;
        let ifd0_size = 2 + 1 * 12 + 4; // 1 entry (GPSInfoPointer)
        let gps_ifd_tiff_off = ifd0_tiff_off + ifd0_size as u32;

        let gps_entry_count = gps_entries.len();
        let gps_ifd_size = 2 + gps_entry_count * 12 + 4;
        let extra_tiff_off = gps_ifd_tiff_off + gps_ifd_size as u32;

        let tiff_size = 8 + ifd0_size + gps_ifd_size + extra.len();
        let total = 6 + tiff_size;
        let mut buf = vec![0u8; total];

        buf[0..6].copy_from_slice(b"Exif\0\0");
        buf[6..8].copy_from_slice(b"II");
        put_u16_le(&mut buf, 8, 42);
        put_u32_le(&mut buf, 10, ifd0_tiff_off);

        // IFD0: 1 entry (GPSInfoPointer)
        let ifd0_raw = 6 + ifd0_tiff_off as usize;
        put_u16_le(&mut buf, ifd0_raw, 1);
        let e0 = ifd0_raw + 2;
        put_u16_le(&mut buf, e0, 0x8825);
        put_u16_le(&mut buf, e0 + 2, 4); // LONG
        put_u32_le(&mut buf, e0 + 4, 1);
        put_u32_le(&mut buf, e0 + 8, gps_ifd_tiff_off);
        put_u32_le(&mut buf, e0 + 12, 0); // next-IFD

        // GPS sub-IFD
        let gps_raw = 6 + gps_ifd_tiff_off as usize;
        put_u16_le(&mut buf, gps_raw, gps_entry_count as u16);
        for (i, &(tag, typ, count, val)) in gps_entries.iter().enumerate() {
            let base = gps_raw + 2 + i * 12;
            put_u16_le(&mut buf, base, tag);
            put_u16_le(&mut buf, base + 2, typ);
            put_u32_le(&mut buf, base + 4, count);
            put_u32_le(&mut buf, base + 8, val);
        }
        let next_ptr = gps_raw + 2 + gps_entry_count * 12;
        put_u32_le(&mut buf, next_ptr, 0);

        // Extra
        let extra_raw = 6 + extra_tiff_off as usize;
        buf[extra_raw..extra_raw + extra.len()].copy_from_slice(extra);

        (buf, extra_tiff_off)
    }

    #[test]
    fn parse_exif_gps_latitude_north() {
        // GPS: 40° 26' 46" N
        // Needs: LatRef (0x0001), Latitude (0x0002)
        let mut extra = [0u8; 24];
        // Degrees: 40/1
        put_u32_le(&mut extra, 0, 40);
        put_u32_le(&mut extra, 4, 1);
        // Minutes: 26/1
        put_u32_le(&mut extra, 8, 26);
        put_u32_le(&mut extra, 12, 1);
        // Seconds: 46/1
        put_u32_le(&mut extra, 16, 46);
        put_u32_le(&mut extra, 20, 1);

        // LatRef = 'N' inline as ASCII count=2: "N\0"
        let lat_ref_val = u32::from_le_bytes([b'N', 0, 0, 0]);

        let (mut data, extra_off) = build_exif_with_gps_ifd_le(
            &[
                (0x0001, 2, 2, lat_ref_val), // GPSLatitudeRef
                (0x0002, 5, 3, 0),           // GPSLatitude → fix offset
            ],
            &extra,
        );
        // Fix latitude offset (entry index 1, value_or_offset)
        let ifd0_size = 2 + 1 * 12 + 4;
        let gps_ifd_tiff_off = (8 + ifd0_size) as usize;
        let val_off_raw = 6 + gps_ifd_tiff_off + 2 + 1 * 12 + 8;
        put_u32_le(&mut data, val_off_raw, extra_off);

        let info = parse_exif(&data).unwrap();
        assert!(info.gps_latitude.is_some());
        let lat = info.gps_latitude.unwrap();
        assert!((lat - 40.44611111).abs() < 1e-6, "got {lat}");
    }

    #[test]
    fn parse_exif_gps_latitude_south_negative() {
        let mut extra = [0u8; 24];
        put_u32_le(&mut extra, 0, 33);
        put_u32_le(&mut extra, 4, 1);
        put_u32_le(&mut extra, 8, 51);
        put_u32_le(&mut extra, 12, 1);
        put_u32_le(&mut extra, 16, 54);
        put_u32_le(&mut extra, 20, 1);

        let lat_ref_val = u32::from_le_bytes([b'S', 0, 0, 0]);

        let (mut data, extra_off) =
            build_exif_with_gps_ifd_le(&[(0x0001, 2, 2, lat_ref_val), (0x0002, 5, 3, 0)], &extra);
        let ifd0_size = 2 + 1 * 12 + 4;
        let gps_ifd_tiff_off = (8 + ifd0_size) as usize;
        let val_off_raw = 6 + gps_ifd_tiff_off + 2 + 1 * 12 + 8;
        put_u32_le(&mut data, val_off_raw, extra_off);

        let info = parse_exif(&data).unwrap();
        let lat = info.gps_latitude.unwrap();
        assert!(lat < 0.0, "South should be negative, got {lat}");
        assert!((lat - (-33.865)).abs() < 1e-6, "got {lat}");
    }

    #[test]
    fn parse_exif_gps_longitude_west_negative() {
        let mut extra = [0u8; 24];
        put_u32_le(&mut extra, 0, 73);
        put_u32_le(&mut extra, 4, 1);
        put_u32_le(&mut extra, 8, 59);
        put_u32_le(&mut extra, 12, 1);
        put_u32_le(&mut extra, 16, 11);
        put_u32_le(&mut extra, 20, 1);

        let lon_ref_val = u32::from_le_bytes([b'W', 0, 0, 0]);

        let (mut data, extra_off) =
            build_exif_with_gps_ifd_le(&[(0x0003, 2, 2, lon_ref_val), (0x0004, 5, 3, 0)], &extra);
        let ifd0_size = 2 + 1 * 12 + 4;
        let gps_ifd_tiff_off = (8 + ifd0_size) as usize;
        let val_off_raw = 6 + gps_ifd_tiff_off + 2 + 1 * 12 + 8;
        put_u32_le(&mut data, val_off_raw, extra_off);

        let info = parse_exif(&data).unwrap();
        let lon = info.gps_longitude.unwrap();
        assert!(lon < 0.0, "West should be negative, got {lon}");
        assert!((lon - (-73.98638888)).abs() < 1e-6, "got {lon}");
    }

    #[test]
    fn parse_exif_gps_altitude_above_sea_level() {
        // Altitude: 100/1 m, AltRef=0 (above)
        let mut extra = [0u8; 8];
        put_u32_le(&mut extra, 0, 100);
        put_u32_le(&mut extra, 4, 1);

        let (mut data, extra_off) = build_exif_with_gps_ifd_le(
            &[
                (0x0005, 1, 1, 0), // GPSAltitudeRef = 0 (above)
                (0x0006, 5, 1, 0), // GPSAltitude → fix
            ],
            &extra,
        );
        let ifd0_size = 2 + 1 * 12 + 4;
        let gps_ifd_tiff_off = (8 + ifd0_size) as usize;
        let val_off_raw = 6 + gps_ifd_tiff_off + 2 + 1 * 12 + 8;
        put_u32_le(&mut data, val_off_raw, extra_off);

        let info = parse_exif(&data).unwrap();
        let alt = info.gps_altitude.unwrap();
        assert!((alt - 100.0).abs() < 1e-6, "got {alt}");
    }

    #[test]
    fn parse_exif_gps_altitude_below_sea_level() {
        let mut extra = [0u8; 8];
        put_u32_le(&mut extra, 0, 50);
        put_u32_le(&mut extra, 4, 1);

        let (mut data, extra_off) = build_exif_with_gps_ifd_le(
            &[
                (0x0005, 1, 1, 1), // GPSAltitudeRef = 1 (below)
                (0x0006, 5, 1, 0),
            ],
            &extra,
        );
        let ifd0_size = 2 + 1 * 12 + 4;
        let gps_ifd_tiff_off = (8 + ifd0_size) as usize;
        let val_off_raw = 6 + gps_ifd_tiff_off + 2 + 1 * 12 + 8;
        put_u32_le(&mut data, val_off_raw, extra_off);

        let info = parse_exif(&data).unwrap();
        let alt = info.gps_altitude.unwrap();
        assert!((alt - (-50.0)).abs() < 1e-6, "got {alt}");
    }

    #[test]
    fn parse_exif_gps_altitude_no_ref_defaults_above() {
        // No GPSAltitudeRef → defaults to above sea level (positive)
        let mut extra = [0u8; 8];
        put_u32_le(&mut extra, 0, 200);
        put_u32_le(&mut extra, 4, 1);

        let (mut data, extra_off) = build_exif_with_gps_ifd_le(
            &[
                (0x0006, 5, 1, 0), // GPSAltitude only, no AltRef
            ],
            &extra,
        );
        let ifd0_size = 2 + 1 * 12 + 4;
        let gps_ifd_tiff_off = (8 + ifd0_size) as usize;
        let val_off_raw = 6 + gps_ifd_tiff_off + 2 + 0 * 12 + 8;
        put_u32_le(&mut data, val_off_raw, extra_off);

        let info = parse_exif(&data).unwrap();
        assert_eq!(info.gps_altitude, Some(200.0));
    }

    #[test]
    fn parse_exif_missing_gps_sub_ifd() {
        // IFD0 has orientation but no GPSInfoPointer → GPS fields None
        let data = build_exif_le(&[(0x0112, 3, 1, 1)], &[]);
        let info = parse_exif(&data).unwrap();
        assert_eq!(info.gps_latitude, None);
        assert_eq!(info.gps_longitude, None);
        assert_eq!(info.gps_altitude, None);
    }

    #[test]
    fn parse_exif_gps_lat_without_ref_produces_none() {
        // GPSLatitude present but no GPSLatitudeRef → lat remains None
        let mut extra = [0u8; 24];
        put_u32_le(&mut extra, 0, 40);
        put_u32_le(&mut extra, 4, 1);
        put_u32_le(&mut extra, 8, 26);
        put_u32_le(&mut extra, 12, 1);
        put_u32_le(&mut extra, 16, 46);
        put_u32_le(&mut extra, 20, 1);

        let (mut data, extra_off) = build_exif_with_gps_ifd_le(
            &[
                (0x0002, 5, 3, 0), // GPSLatitude only, no ref
            ],
            &extra,
        );
        let ifd0_size = 2 + 1 * 12 + 4;
        let gps_ifd_tiff_off = (8 + ifd0_size) as usize;
        let val_off_raw = 6 + gps_ifd_tiff_off + 2 + 0 * 12 + 8;
        put_u32_le(&mut data, val_off_raw, extra_off);

        let info = parse_exif(&data).unwrap();
        assert_eq!(info.gps_latitude, None);
    }

    #[test]
    fn parse_exif_gps_full_coordinates() {
        // Full GPS: lat 40°26'46"N, lon 73°59'11"W, alt 10m above
        // Extra layout: lat DMS (24 bytes), lon DMS (24 bytes), alt RATIONAL (8 bytes)
        let mut extra = [0u8; 56];
        // Latitude: 40° 26' 46" at offset 0
        put_u32_le(&mut extra, 0, 40);
        put_u32_le(&mut extra, 4, 1);
        put_u32_le(&mut extra, 8, 26);
        put_u32_le(&mut extra, 12, 1);
        put_u32_le(&mut extra, 16, 46);
        put_u32_le(&mut extra, 20, 1);
        // Longitude: 73° 59' 11" at offset 24
        put_u32_le(&mut extra, 24, 73);
        put_u32_le(&mut extra, 28, 1);
        put_u32_le(&mut extra, 32, 59);
        put_u32_le(&mut extra, 36, 1);
        put_u32_le(&mut extra, 40, 11);
        put_u32_le(&mut extra, 44, 1);
        // Altitude: 10/1 at offset 48
        put_u32_le(&mut extra, 48, 10);
        put_u32_le(&mut extra, 52, 1);

        let lat_ref = u32::from_le_bytes([b'N', 0, 0, 0]);
        let lon_ref = u32::from_le_bytes([b'W', 0, 0, 0]);

        let (mut data, extra_off) = build_exif_with_gps_ifd_le(
            &[
                (0x0001, 2, 2, lat_ref), // LatRef
                (0x0002, 5, 3, 0),       // Lat → fix
                (0x0003, 2, 2, lon_ref), // LonRef
                (0x0004, 5, 3, 0),       // Lon → fix
                (0x0005, 1, 1, 0),       // AltRef = 0
                (0x0006, 5, 1, 0),       // Alt → fix
            ],
            &extra,
        );
        let ifd0_size = 2 + 1 * 12 + 4;
        let gps_ifd_tiff_off = (8 + ifd0_size) as usize;
        // Fix Latitude offset (entry 1)
        let lat_val_off = 6 + gps_ifd_tiff_off + 2 + 1 * 12 + 8;
        put_u32_le(&mut data, lat_val_off, extra_off + 0);
        // Fix Longitude offset (entry 3)
        let lon_val_off = 6 + gps_ifd_tiff_off + 2 + 3 * 12 + 8;
        put_u32_le(&mut data, lon_val_off, extra_off + 24);
        // Fix Altitude offset (entry 5)
        let alt_val_off = 6 + gps_ifd_tiff_off + 2 + 5 * 12 + 8;
        put_u32_le(&mut data, alt_val_off, extra_off + 48);

        let info = parse_exif(&data).unwrap();

        let lat = info.gps_latitude.unwrap();
        assert!((lat - 40.44611111).abs() < 1e-6, "lat={lat}");

        let lon = info.gps_longitude.unwrap();
        assert!(lon < 0.0);
        assert!((lon - (-73.98638888)).abs() < 1e-6, "lon={lon}");

        let alt = info.gps_altitude.unwrap();
        assert!((alt - 10.0).abs() < 1e-6, "alt={alt}");
    }

    // ── Robustness / edge-case tests ─────────────────────────────────

    #[test]
    fn parse_exif_truncated_after_tiff_header() {
        // Valid Exif header + byte order + magic, but IFD0 offset points past end
        let mut data = vec![0u8; 14];
        data[0..6].copy_from_slice(b"Exif\0\0");
        data[6..8].copy_from_slice(b"II");
        put_u16_le(&mut data, 8, 42);
        put_u32_le(&mut data, 10, 200); // offset past end
        // Should fail gracefully when trying to read IFD count
        let info = parse_exif(&data).unwrap();
        assert_eq!(info, JpegExifInfo::default());
    }

    #[test]
    fn parse_exif_malformed_orientation_other_fields_still_parse() {
        // Orientation has wrong TIFF type (LONG), but Make is valid
        let extra_off = extra_tiff_offset(2);
        let make = b"Sony\0\0"; // 6 bytes
        let data = build_exif_le(
            &[
                (0x0112, 4, 1, 6), // wrong type for orientation
                (0x010F, 2, 6, extra_off),
            ],
            make,
        );
        let info = parse_exif(&data).unwrap();
        assert_eq!(info.orientation, None, "bad orientation should be None");
        assert_eq!(
            info.camera_make,
            Some("Sony".to_string()),
            "Make should still parse"
        );
    }

    #[test]
    fn parse_exif_unknown_tags_ignored() {
        // Tags that we don't recognize should be silently skipped
        let data = build_exif_le(
            &[
                (0xFFFF, 3, 1, 42),  // unknown tag
                (0x0112, 3, 1, 3),   // valid orientation
                (0xABCD, 4, 1, 999), // unknown tag
            ],
            &[],
        );
        let info = parse_exif(&data).unwrap();
        assert_eq!(info.orientation, Some(3));
    }

    #[test]
    fn parse_exif_not_exif_data() {
        // Random bytes that don't start with Exif\0\0
        assert_eq!(parse_exif(b"This is not EXIF data at all"), None);
    }

    #[test]
    fn parse_exif_jfif_not_exif() {
        assert_eq!(parse_exif(b"JFIF\0\0IIQQ"), None);
    }

    #[test]
    fn parse_exif_big_endian_full_parse() {
        // Test a BE EXIF with orientation and make
        let make_val = u32::from_be_bytes([b'X', 0, 0, 0]);
        let data = build_exif_be(
            &[
                (0x0112, 3, 1, 1 << 16),  // orientation=1 as BE SHORT inline
                (0x010F, 2, 1, make_val), // Make="X" — but count=1 is just the NUL issue
            ],
            &[],
        );
        let info = parse_exif(&data).unwrap();
        assert_eq!(info.orientation, Some(1));
    }

    #[test]
    fn parse_exif_big_endian_make_offset() {
        let extra_off = extra_tiff_offset(1);
        let make = b"Fujifilm\0";
        // Build BE: offset values must also be BE-encoded
        let data = build_exif_be(&[(0x010F, 2, 9, extra_off)], make);
        // The extra offset is already BE-encoded by build_exif_be
        let _ = &data; // verify it compiles
        let info = parse_exif(&data).unwrap();
        assert_eq!(info.camera_make, Some("Fujifilm".to_string()));
    }

    #[test]
    fn parse_exif_gps_altitude_fractional() {
        // Altitude: 1234/10 = 123.4m above sea level
        let mut extra = [0u8; 8];
        put_u32_le(&mut extra, 0, 1234);
        put_u32_le(&mut extra, 4, 10);

        let (mut data, extra_off) =
            build_exif_with_gps_ifd_le(&[(0x0005, 1, 1, 0), (0x0006, 5, 1, 0)], &extra);
        let ifd0_size = 2 + 1 * 12 + 4;
        let gps_ifd_tiff_off = (8 + ifd0_size) as usize;
        let val_off_raw = 6 + gps_ifd_tiff_off + 2 + 1 * 12 + 8;
        put_u32_le(&mut data, val_off_raw, extra_off);

        let info = parse_exif(&data).unwrap();
        let alt = info.gps_altitude.unwrap();
        assert!((alt - 123.4).abs() < 1e-6, "got {alt}");
    }

    #[test]
    fn parse_exif_gps_altitude_zero_denominator_produces_none() {
        // Altitude with zero denominator → no altitude
        let mut extra = [0u8; 8];
        put_u32_le(&mut extra, 0, 100);
        put_u32_le(&mut extra, 4, 0); // zero denominator!

        let (mut data, extra_off) = build_exif_with_gps_ifd_le(&[(0x0006, 5, 1, 0)], &extra);
        let ifd0_size = 2 + 1 * 12 + 4;
        let gps_ifd_tiff_off = (8 + ifd0_size) as usize;
        let val_off_raw = 6 + gps_ifd_tiff_off + 2 + 0 * 12 + 8;
        put_u32_le(&mut data, val_off_raw, extra_off);

        let info = parse_exif(&data).unwrap();
        assert_eq!(info.gps_altitude, None);
    }

    #[test]
    fn parse_exif_exposure_time_round_trip() {
        // Verify specific rational values survive the round trip
        let mut extra = [0u8; 8];
        put_u32_le(&mut extra, 0, 1);
        put_u32_le(&mut extra, 4, 8000); // 1/8000 sec

        let (mut data, extra_off) = build_exif_with_sub_ifd_le(&[(0x829A, 5, 1, 0)], &extra);
        let ifd0_size = 2 + 1 * 12 + 4;
        let exif_ifd_tiff_off = 8 + ifd0_size;
        let val_off_raw = 6 + exif_ifd_tiff_off + 2 + 8;
        put_u32_le(&mut data, val_off_raw, extra_off);

        let info = parse_exif(&data).unwrap();
        assert_eq!(info.exposure_time, Some((1, 8000)));
    }

    #[test]
    fn parse_exif_iso_speed_max_u16() {
        let (data, _) = build_exif_with_sub_ifd_le(&[(0x8827, 3, 1, u16::MAX as u32)], &[]);
        let info = parse_exif(&data).unwrap();
        assert_eq!(info.iso_speed, Some(u16::MAX));
    }

    #[test]
    fn parse_exif_does_not_panic_on_fuzz_like_data() {
        // Various degenerate inputs that must not panic
        let inputs: &[&[u8]] = &[
            b"Exif\0\0II\x2a\x00\x08\x00\x00\x00",
            b"Exif\0\0MM\x00\x2a\x00\x00\x00\x08",
            b"Exif\0\0II\x2a\x00\xff\xff\xff\xff",
            b"Exif\0\0II\x2a\x00\x08\x00\x00\x00\xff\xff",
        ];
        for input in inputs {
            // Just ensure no panic — result can be Some or None
            let _ = parse_exif(input);
        }
    }

    // ═════════════════════════════════════════════════════════════════════
    // scan_com_markers tests (task 3.4)
    // ═════════════════════════════════════════════════════════════════════

    #[test]
    fn scan_com_no_markers() {
        let jpeg = build_jpeg_rgb(2, 2, 128, 128, 128);
        // The encoder may or may not insert COM markers.
        // At minimum, verify it doesn't panic and returns a Vec.
        let _ = scan_com_markers(&jpeg);
    }

    #[test]
    fn scan_com_single_comment() {
        let jpeg = build_jpeg_rgb(2, 2, 0, 0, 0);
        let jpeg = inject_com_marker(&jpeg, "Hello, world!");
        let comments = scan_com_markers(&jpeg);
        assert!(comments.contains(&"Hello, world!".to_string()));
    }

    #[test]
    fn scan_com_multiple_comments() {
        let jpeg = build_jpeg_rgb(2, 2, 0, 0, 0);
        let jpeg = inject_com_marker(&jpeg, "First");
        let jpeg = inject_com_marker(&jpeg, "Second");
        let comments = scan_com_markers(&jpeg);
        assert!(comments.contains(&"First".to_string()));
        assert!(comments.contains(&"Second".to_string()));
    }

    #[test]
    fn scan_com_empty_data() {
        assert!(scan_com_markers(&[]).is_empty());
    }

    #[test]
    fn scan_com_not_jpeg() {
        assert!(scan_com_markers(b"This is not JPEG").is_empty());
    }

    #[test]
    fn scan_com_truncated() {
        // SOI + COM marker but truncated length
        let data = [0xFF, 0xD8, 0xFF, 0xFE, 0x00];
        let comments = scan_com_markers(&data);
        assert!(comments.is_empty());
    }

    #[test]
    fn scan_com_latin1_fallback() {
        let jpeg = build_jpeg_rgb(1, 1, 0, 0, 0);
        // Build a COM marker with invalid UTF-8 bytes (Latin-1 characters)
        let mut injected = Vec::new();
        injected.extend_from_slice(&jpeg[..2]); // SOI
        injected.push(0xFF);
        injected.push(0xFE); // COM
        let text = [0xC0, 0xC1, 0xFE, 0xFF]; // invalid UTF-8, valid Latin-1
        let seg_len = (text.len() + 2) as u16;
        injected.extend_from_slice(&seg_len.to_be_bytes());
        injected.extend_from_slice(&text);
        injected.extend_from_slice(&jpeg[2..]);
        let comments = scan_com_markers(&injected);
        assert_eq!(comments.len(), 1);
        // Latin-1 fallback: each byte maps to its Unicode code point.
        // 0xC0 = 'À', 0xC1 = 'Á', 0xFE = 'þ', 0xFF = 'ÿ'
        assert_eq!(comments[0], "\u{00C0}\u{00C1}\u{00FE}\u{00FF}");
        // Must NOT contain U+FFFD replacement characters.
        assert!(!comments[0].contains('\u{FFFD}'));
    }

    // ═════════════════════════════════════════════════════════════════════
    // scan_jfif_density tests
    // ═════════════════════════════════════════════════════════════════════

    #[test]
    fn scan_jfif_density_dpi() {
        let jpeg = build_jpeg_rgb(2, 2, 0, 0, 0);
        let jpeg = inject_jfif_app0(&jpeg, 1, 300, 300);
        let density = scan_jfif_density(&jpeg);
        assert_eq!(density, Some(JpegPixelDensity::Dpi { x: 300, y: 300 }));
    }

    #[test]
    fn scan_jfif_density_dpcm() {
        let jpeg = build_jpeg_rgb(2, 2, 0, 0, 0);
        let jpeg = inject_jfif_app0(&jpeg, 2, 118, 118);
        let density = scan_jfif_density(&jpeg);
        assert_eq!(density, Some(JpegPixelDensity::Dpcm { x: 118, y: 118 }));
    }

    #[test]
    fn scan_jfif_density_aspect_ratio() {
        let jpeg = build_jpeg_rgb(2, 2, 0, 0, 0);
        let jpeg = inject_jfif_app0(&jpeg, 0, 1, 1);
        let density = scan_jfif_density(&jpeg);
        assert_eq!(density, Some(JpegPixelDensity::AspectRatio { x: 1, y: 1 }));
    }

    #[test]
    fn scan_jfif_density_no_app0() {
        // A JPEG without our injected APP0 may or may not have one from the encoder.
        // Test with empty data → should be None.
        assert_eq!(scan_jfif_density(&[]), None);
        assert_eq!(scan_jfif_density(b"not jpeg"), None);
    }

    #[test]
    fn scan_jfif_density_non_square() {
        let jpeg = build_jpeg_rgb(2, 2, 0, 0, 0);
        let jpeg = inject_jfif_app0(&jpeg, 1, 300, 600);
        let density = scan_jfif_density(&jpeg);
        assert_eq!(density, Some(JpegPixelDensity::Dpi { x: 300, y: 600 }));
    }

    // ═════════════════════════════════════════════════════════════════════
    // decode / decode_reader tests (task 3.6)
    // ═════════════════════════════════════════════════════════════════════

    #[test]
    fn decode_rgb_8bit() {
        let jpeg = build_jpeg_rgb(4, 3, 200, 100, 50);
        let decoded = decode(&jpeg).unwrap();
        match &decoded.image {
            JpegImage::Srgb8(img) => {
                assert_eq!(img.width(), 4);
                assert_eq!(img.height(), 3);
            }
            other => panic!("expected Srgb8, got {:?}", other),
        }
        assert_eq!(decoded.metadata.source_bit_depth, JpegBitDepth::Eight);
        assert_eq!(decoded.metadata.color_space, JpegColorSpace::Srgb);
    }

    #[test]
    fn decode_grayscale_8bit() {
        let jpeg = build_jpeg_gray(4, 3, 128);
        let decoded = decode(&jpeg).unwrap();
        match &decoded.image {
            JpegImage::SrgbMono8(img) => {
                assert_eq!(img.width(), 4);
                assert_eq!(img.height(), 3);
            }
            other => panic!("expected SrgbMono8, got {:?}", other),
        }
        assert_eq!(decoded.metadata.source_bit_depth, JpegBitDepth::Eight);
    }

    #[test]
    fn decode_preserves_dimensions_rgb() {
        for &(w, h) in &[(1, 1), (2, 2), (8, 8), (16, 9), (100, 50)] {
            let jpeg = build_jpeg_rgb(w, h, 0, 0, 0);
            let decoded = decode(&jpeg).unwrap();
            match &decoded.image {
                JpegImage::Srgb8(img) => {
                    assert_eq!(img.width(), w as usize, "width mismatch for {w}x{h}");
                    assert_eq!(img.height(), h as usize, "height mismatch for {w}x{h}");
                }
                other => panic!("expected Srgb8 for {w}x{h}, got {:?}", other),
            }
        }
    }

    #[test]
    fn decode_preserves_dimensions_gray() {
        for &(w, h) in &[(1, 1), (8, 8), (16, 9)] {
            let jpeg = build_jpeg_gray(w, h, 0);
            let decoded = decode(&jpeg).unwrap();
            match &decoded.image {
                JpegImage::SrgbMono8(img) => {
                    assert_eq!(img.width(), w as usize);
                    assert_eq!(img.height(), h as usize);
                }
                other => panic!("expected SrgbMono8 for {w}x{h}, got {:?}", other),
            }
        }
    }

    #[test]
    fn decode_invalid_data_returns_error() {
        let result = decode(b"this is not a jpeg");
        assert!(result.is_err());
    }

    #[test]
    fn decode_empty_data_returns_error() {
        let result = decode(b"");
        assert!(result.is_err());
    }

    #[test]
    fn decode_truncated_jpeg_returns_error() {
        let jpeg = build_jpeg_rgb(4, 4, 100, 100, 100);
        let truncated = &jpeg[..jpeg.len() / 2];
        let result = decode(truncated);
        assert!(result.is_err());
    }

    #[test]
    fn decode_debug_output_shows_variant_and_dimensions() {
        let jpeg = build_jpeg_rgb(8, 6, 0, 0, 0);
        let decoded = decode(&jpeg).unwrap();
        let dbg = format!("{:?}", decoded.image);
        assert_eq!(dbg, "Srgb8(8x6)");
    }

    #[test]
    fn decode_debug_output_gray() {
        let jpeg = build_jpeg_gray(3, 2, 0);
        let decoded = decode(&jpeg).unwrap();
        let dbg = format!("{:?}", decoded.image);
        assert_eq!(dbg, "SrgbMono8(3x2)");
    }

    #[test]
    fn decode_metadata_no_exif() {
        let jpeg = build_jpeg_rgb(2, 2, 0, 0, 0);
        let decoded = decode(&jpeg).unwrap();
        // A minimal encoder-produced JPEG typically has no EXIF.
        // (The encoder may or may not produce exif data.)
        // Just verify the metadata is accessible.
        let _ = &decoded.metadata.exif;
        let _ = &decoded.metadata.raw_exif;
    }

    #[test]
    fn decode_metadata_color_space_srgb_no_icc() {
        let jpeg = build_jpeg_rgb(2, 2, 0, 0, 0);
        let decoded = decode(&jpeg).unwrap();
        // No ICC profile embedded by default → Srgb
        if decoded.metadata.icc_profile.is_none() {
            assert_eq!(decoded.metadata.color_space, JpegColorSpace::Srgb);
        }
    }

    #[test]
    fn decode_with_com_marker() {
        let jpeg = build_jpeg_rgb(2, 2, 0, 0, 0);
        let jpeg = inject_com_marker(&jpeg, "Test comment");
        let decoded = decode(&jpeg).unwrap();
        assert!(
            decoded
                .metadata
                .comments
                .contains(&"Test comment".to_string())
        );
    }

    #[test]
    fn decode_with_jfif_density() {
        let jpeg = build_jpeg_rgb(2, 2, 0, 0, 0);
        let jpeg = inject_jfif_app0(&jpeg, 1, 72, 72);
        let decoded = decode(&jpeg).unwrap();
        // Our injected APP0 should be picked up.
        // Note: the encoder may also inject its own APP0, and ours comes first.
        assert_eq!(
            decoded.metadata.pixel_density,
            Some(JpegPixelDensity::Dpi { x: 72, y: 72 })
        );
    }

    #[test]
    fn decode_reader_rgb_8bit() {
        let jpeg = build_jpeg_rgb(4, 3, 200, 100, 50);
        let decoded = decode_reader(std::io::Cursor::new(&jpeg)).unwrap();
        match &decoded.image {
            JpegImage::Srgb8(img) => {
                assert_eq!(img.width(), 4);
                assert_eq!(img.height(), 3);
            }
            other => panic!("expected Srgb8, got {:?}", other),
        }
    }

    #[test]
    fn decode_reader_gray_8bit() {
        let jpeg = build_jpeg_gray(4, 3, 128);
        let decoded = decode_reader(std::io::Cursor::new(&jpeg)).unwrap();
        match &decoded.image {
            JpegImage::SrgbMono8(img) => {
                assert_eq!(img.width(), 4);
                assert_eq!(img.height(), 3);
            }
            other => panic!("expected SrgbMono8, got {:?}", other),
        }
    }

    #[test]
    fn decode_reader_has_com_and_density() {
        // After R2 fixup, decode_reader buffers internally and delegates
        // to decode(), so COM comments and JFIF density are available.
        let jpeg = build_jpeg_rgb(2, 2, 0, 0, 0);
        let jpeg_with_com = inject_com_marker(&jpeg, "visible");
        let jpeg_with_both = inject_jfif_app0(&jpeg_with_com, 1, 150, 150);
        let decoded = decode_reader(std::io::Cursor::new(&jpeg_with_both)).unwrap();
        // Comments should be populated from the reader path.
        assert!(decoded.metadata.comments.contains(&"visible".to_string()));
        // Density should be populated from the reader path.
        assert_eq!(
            decoded.metadata.pixel_density,
            Some(JpegPixelDensity::Dpi { x: 150, y: 150 })
        );
    }

    #[test]
    fn decode_reader_matches_decode_image() {
        // Verify both paths produce the same image variant and dimensions.
        let jpeg = build_jpeg_rgb(8, 6, 100, 150, 200);
        let d1 = decode(&jpeg).unwrap();
        let d2 = decode_reader(std::io::Cursor::new(&jpeg)).unwrap();
        match (&d1.image, &d2.image) {
            (JpegImage::Srgb8(a), JpegImage::Srgb8(b)) => {
                assert_eq!(a.width(), b.width());
                assert_eq!(a.height(), b.height());
            }
            _ => panic!("variant mismatch"),
        }
    }

    #[test]
    fn decode_reader_invalid_data_returns_error() {
        let result = decode_reader(std::io::Cursor::new(b"not jpeg"));
        assert!(result.is_err());
    }

    #[test]
    fn decode_reader_empty_data_returns_error() {
        let result = decode_reader(std::io::Cursor::new(b""));
        assert!(result.is_err());
    }

    #[test]
    fn decode_pixel_values_approximately_correct() {
        // JPEG is lossy, so we can't test exact values, but we can check
        // that a solid-colour image decodes to approximately the right values.
        let jpeg = build_jpeg_rgb(8, 8, 200, 100, 50);
        let decoded = decode(&jpeg).unwrap();
        match &decoded.image {
            JpegImage::Srgb8(img) => {
                let px = img.get(4, 4).unwrap();
                // JPEG compression introduces some error; allow ±10
                assert!((px.r.0 as i16 - 200).unsigned_abs() < 10, "red: {}", px.r.0);
                assert!(
                    (px.g.0 as i16 - 100).unsigned_abs() < 10,
                    "green: {}",
                    px.g.0
                );
                assert!((px.b.0 as i16 - 50).unsigned_abs() < 10, "blue: {}", px.b.0);
            }
            other => panic!("expected Srgb8, got {:?}", other),
        }
    }

    #[test]
    fn decode_pixel_values_gray_approximately_correct() {
        let jpeg = build_jpeg_gray(8, 8, 180);
        let decoded = decode(&jpeg).unwrap();
        match &decoded.image {
            JpegImage::SrgbMono8(img) => {
                let px = img.get(4, 4).unwrap();
                assert!(
                    (px.0.0 as i16 - 180).unsigned_abs() < 10,
                    "gray: {}",
                    px.0.0
                );
            }
            other => panic!("expected SrgbMono8, got {:?}", other),
        }
    }

    #[test]
    fn decode_1x1_rgb() {
        let jpeg = build_jpeg_rgb(1, 1, 255, 0, 0);
        let decoded = decode(&jpeg).unwrap();
        match &decoded.image {
            JpegImage::Srgb8(img) => {
                assert_eq!(img.width(), 1);
                assert_eq!(img.height(), 1);
            }
            other => panic!("expected Srgb8, got {:?}", other),
        }
    }

    #[test]
    fn decode_1x1_gray() {
        let jpeg = build_jpeg_gray(1, 1, 42);
        let decoded = decode(&jpeg).unwrap();
        match &decoded.image {
            JpegImage::SrgbMono8(img) => {
                assert_eq!(img.width(), 1);
                assert_eq!(img.height(), 1);
            }
            other => panic!("expected SrgbMono8, got {:?}", other),
        }
    }

    #[test]
    fn decode_metadata_source_bit_depth_8_for_rgb() {
        let jpeg = build_jpeg_rgb(2, 2, 0, 0, 0);
        let decoded = decode(&jpeg).unwrap();
        assert_eq!(decoded.metadata.source_bit_depth, JpegBitDepth::Eight);
    }

    #[test]
    fn decode_metadata_source_bit_depth_8_for_gray() {
        let jpeg = build_jpeg_gray(2, 2, 0);
        let decoded = decode(&jpeg).unwrap();
        assert_eq!(decoded.metadata.source_bit_depth, JpegBitDepth::Eight);
    }

    #[test]
    fn decode_error_maps_io_error() {
        // Construct a jpeg_decoder Io error and verify mapping
        let io_err = std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "test");
        let jpeg_err = jpeg_decoder::Error::Io(io_err);
        let mapped = decode_error(jpeg_err);
        match mapped {
            IoError::Io(e) => assert_eq!(e.kind(), std::io::ErrorKind::UnexpectedEof),
            other => panic!("expected IoError::Io, got {:?}", other),
        }
    }

    #[test]
    fn decode_error_maps_format_error() {
        let jpeg_err = jpeg_decoder::Error::Format("bad format".to_string());
        let mapped = decode_error(jpeg_err);
        match mapped {
            IoError::DecodeFailed { .. } => {} // expected
            other => panic!("expected IoError::DecodeFailed, got {:?}", other),
        }
    }

    #[test]
    fn decode_multiple_com_markers() {
        let jpeg = build_jpeg_rgb(2, 2, 0, 0, 0);
        let jpeg = inject_com_marker(&jpeg, "Comment A");
        let jpeg = inject_com_marker(&jpeg, "Comment B");
        let decoded = decode(&jpeg).unwrap();
        assert!(decoded.metadata.comments.len() >= 2);
        assert!(decoded.metadata.comments.contains(&"Comment A".to_string()));
        assert!(decoded.metadata.comments.contains(&"Comment B".to_string()));
    }

    #[test]
    fn decode_exhaustive_image_match() {
        // Verify all JpegImage variants can be matched exhaustively
        let jpeg = build_jpeg_rgb(2, 2, 0, 0, 0);
        let decoded = decode(&jpeg).unwrap();
        match decoded.image {
            JpegImage::SrgbMono8(_) => {}
            JpegImage::SrgbMono16(_) => {}
            JpegImage::Srgb8(_) => {}
        }
    }

    #[test]
    fn decode_large_image() {
        // Test with a larger image to ensure no panics on buffer sizing.
        let jpeg = build_jpeg_rgb(256, 256, 100, 200, 50);
        let decoded = decode(&jpeg).unwrap();
        match &decoded.image {
            JpegImage::Srgb8(img) => {
                assert_eq!(img.width(), 256);
                assert_eq!(img.height(), 256);
            }
            other => panic!("expected Srgb8, got {:?}", other),
        }
    }

    // ═════════════════════════════════════════════════════════════════════
    // IfdEntry struct tests (R5 fixup)
    // ═════════════════════════════════════════════════════════════════════

    #[test]
    fn ifd_entry_struct_fields() {
        let entry = IfdEntry {
            tag: 0x0112,
            tiff_type: 3,
            count: 1,
            value_or_offset: 6,
        };
        assert_eq!(entry.tag, 0x0112);
        assert_eq!(entry.tiff_type, 3);
        assert_eq!(entry.count, 1);
        assert_eq!(entry.value_or_offset, 6);
    }

    #[test]
    fn ifd_entry_debug() {
        let entry = IfdEntry {
            tag: 0x010F,
            tiff_type: 2,
            count: 5,
            value_or_offset: 100,
        };
        let dbg = format!("{:?}", entry);
        assert!(dbg.contains("tag"));
        assert!(dbg.contains("tiff_type"));
    }

    #[test]
    fn ifd_entry_eq() {
        let a = IfdEntry {
            tag: 1,
            tiff_type: 2,
            count: 3,
            value_or_offset: 4,
        };
        let b = IfdEntry {
            tag: 1,
            tiff_type: 2,
            count: 3,
            value_or_offset: 4,
        };
        assert_eq!(a, b);
    }

    #[test]
    fn ifd_entry_copy() {
        let a = IfdEntry {
            tag: 1,
            tiff_type: 2,
            count: 3,
            value_or_offset: 4,
        };
        let b = a;
        assert_eq!(a, b);
    }

    // ═════════════════════════════════════════════════════════════════════
    // JpegSamplingFactor tests (task 4.1)
    // ═════════════════════════════════════════════════════════════════════

    #[test]
    fn jpeg_sampling_factor_variants() {
        let f1 = JpegSamplingFactor::F1x1;
        let f2 = JpegSamplingFactor::F2x1;
        let f3 = JpegSamplingFactor::F2x2;
        assert_ne!(f1, f2);
        assert_ne!(f2, f3);
        assert_ne!(f1, f3);
    }

    #[test]
    fn jpeg_sampling_factor_is_copy() {
        let f = JpegSamplingFactor::F1x1;
        let f2 = f;
        assert_eq!(f, f2);
    }

    #[test]
    fn jpeg_sampling_factor_debug() {
        assert_eq!(format!("{:?}", JpegSamplingFactor::F1x1), "F1x1");
        assert_eq!(format!("{:?}", JpegSamplingFactor::F2x1), "F2x1");
        assert_eq!(format!("{:?}", JpegSamplingFactor::F2x2), "F2x2");
    }

    // ═════════════════════════════════════════════════════════════════════
    // JpegEncodeOptions tests (task 4.2)
    // ═════════════════════════════════════════════════════════════════════

    #[test]
    fn jpeg_encode_options_default() {
        let opts = JpegEncodeOptions::default();
        assert_eq!(opts.quality, 85);
        assert_eq!(opts.sampling_factor, None);
        assert!(!opts.progressive);
    }

    #[test]
    fn jpeg_encode_options_custom() {
        let opts = JpegEncodeOptions {
            quality: 95,
            sampling_factor: Some(JpegSamplingFactor::F1x1),
            progressive: true,
        };
        assert_eq!(opts.quality, 95);
        assert_eq!(opts.sampling_factor, Some(JpegSamplingFactor::F1x1));
        assert!(opts.progressive);
    }

    #[test]
    fn jpeg_encode_options_debug() {
        let opts = JpegEncodeOptions::default();
        let dbg = format!("{:?}", opts);
        assert!(dbg.contains("quality"));
        assert!(dbg.contains("85"));
    }

    #[test]
    fn jpeg_encode_options_clone() {
        let opts = JpegEncodeOptions {
            quality: 50,
            sampling_factor: Some(JpegSamplingFactor::F2x2),
            progressive: true,
        };
        let opts2 = opts.clone();
        assert_eq!(opts2.quality, 50);
        assert_eq!(opts2.sampling_factor, Some(JpegSamplingFactor::F2x2));
        assert!(opts2.progressive);
    }

    // ═════════════════════════════════════════════════════════════════════
    // JpegPixel trait tests (task 4.3)
    // ═════════════════════════════════════════════════════════════════════

    #[test]
    fn jpeg_pixel_srgb_mono8() {
        // SrgbMono8 implements JpegPixel with Luma colour type
        assert_eq!(SrgbMono8::JPEG_COLOR_TYPE, jpeg_encoder::ColorType::Luma);
    }

    #[test]
    fn jpeg_pixel_srgb8() {
        // Srgb8 implements JpegPixel with Rgb colour type
        assert_eq!(Srgb8::JPEG_COLOR_TYPE, jpeg_encoder::ColorType::Rgb);
    }

    // ═════════════════════════════════════════════════════════════════════
    // Encode tests (tasks 4.4–4.8)
    // ═════════════════════════════════════════════════════════════════════

    #[test]
    fn encode_srgb8_roundtrip() {
        let img = Image::fill(8, 8, Srgb8::new(200, 100, 50));
        let bytes = encode(&img, &JpegEncodeOptions::default()).unwrap();
        // Verify it decodes back to an Srgb8 image with correct dimensions.
        let decoded = decode(&bytes).unwrap();
        match &decoded.image {
            JpegImage::Srgb8(dec_img) => {
                assert_eq!(dec_img.width(), 8);
                assert_eq!(dec_img.height(), 8);
            }
            other => panic!("expected Srgb8, got {:?}", other),
        }
    }

    #[test]
    fn encode_srgb_mono8_roundtrip() {
        let img = Image::fill(8, 8, SrgbMono8::new(128));
        let bytes = encode(&img, &JpegEncodeOptions::default()).unwrap();
        let decoded = decode(&bytes).unwrap();
        match &decoded.image {
            JpegImage::SrgbMono8(dec_img) => {
                assert_eq!(dec_img.width(), 8);
                assert_eq!(dec_img.height(), 8);
            }
            other => panic!("expected SrgbMono8, got {:?}", other),
        }
    }

    #[test]
    fn encode_quality_affects_size() {
        let img = Image::fill(64, 64, Srgb8::new(128, 64, 32));
        let low = encode(
            &img,
            &JpegEncodeOptions {
                quality: 10,
                ..Default::default()
            },
        )
        .unwrap();
        let high = encode(
            &img,
            &JpegEncodeOptions {
                quality: 100,
                ..Default::default()
            },
        )
        .unwrap();
        // Higher quality should produce a larger file.
        assert!(
            high.len() > low.len(),
            "high quality ({}) should be larger than low quality ({})",
            high.len(),
            low.len()
        );
    }

    #[test]
    fn encode_writer_byte_identical_to_encode() {
        let img = Image::fill(4, 4, Srgb8::new(100, 150, 200));
        let opts = JpegEncodeOptions::default();
        let bytes_encode = encode(&img, &opts).unwrap();
        let mut bytes_writer = Vec::new();
        encode_writer(&img, &mut bytes_writer, &opts).unwrap();
        assert_eq!(bytes_encode, bytes_writer);
    }

    #[test]
    fn encode_dimensions_roundtrip() {
        for &(w, h) in &[(1u16, 1), (2, 2), (8, 6), (16, 9), (100, 50)] {
            let img = Image::fill(w as usize, h as usize, Srgb8::new(0, 0, 0));
            let bytes = encode(&img, &JpegEncodeOptions::default()).unwrap();
            let decoded = decode(&bytes).unwrap();
            match &decoded.image {
                JpegImage::Srgb8(dec_img) => {
                    assert_eq!(dec_img.width(), w as usize, "width for {w}x{h}");
                    assert_eq!(dec_img.height(), h as usize, "height for {w}x{h}");
                }
                other => panic!("expected Srgb8 for {w}x{h}, got {:?}", other),
            }
        }
    }

    #[test]
    fn encode_progressive_accepted() {
        let img = Image::fill(8, 8, Srgb8::new(0, 0, 0));
        let opts = JpegEncodeOptions {
            progressive: true,
            ..Default::default()
        };
        let bytes = encode(&img, &opts).unwrap();
        // Verify the result is a valid JPEG.
        let decoded = decode(&bytes).unwrap();
        match &decoded.image {
            JpegImage::Srgb8(_) => {}
            other => panic!("expected Srgb8, got {:?}", other),
        }
    }

    #[test]
    fn encode_sampling_factor_f1x1() {
        let img = Image::fill(8, 8, Srgb8::new(0, 0, 0));
        let opts = JpegEncodeOptions {
            sampling_factor: Some(JpegSamplingFactor::F1x1),
            ..Default::default()
        };
        let bytes = encode(&img, &opts).unwrap();
        let decoded = decode(&bytes).unwrap();
        match &decoded.image {
            JpegImage::Srgb8(_) => {}
            other => panic!("expected Srgb8, got {:?}", other),
        }
    }

    #[test]
    fn encode_sampling_factor_f2x1() {
        let img = Image::fill(8, 8, Srgb8::new(0, 0, 0));
        let opts = JpegEncodeOptions {
            sampling_factor: Some(JpegSamplingFactor::F2x1),
            ..Default::default()
        };
        let bytes = encode(&img, &opts).unwrap();
        let decoded = decode(&bytes).unwrap();
        match &decoded.image {
            JpegImage::Srgb8(_) => {}
            other => panic!("expected Srgb8, got {:?}", other),
        }
    }

    #[test]
    fn encode_sampling_factor_f2x2() {
        let img = Image::fill(8, 8, Srgb8::new(0, 0, 0));
        let opts = JpegEncodeOptions {
            sampling_factor: Some(JpegSamplingFactor::F2x2),
            ..Default::default()
        };
        let bytes = encode(&img, &opts).unwrap();
        let decoded = decode(&bytes).unwrap();
        match &decoded.image {
            JpegImage::Srgb8(_) => {}
            other => panic!("expected Srgb8, got {:?}", other),
        }
    }

    #[test]
    fn encode_jpeg_image_srgb8() {
        let img = JpegImage::Srgb8(Image::fill(4, 4, Srgb8::new(128, 64, 32)));
        let bytes = encode_jpeg_image(&img, &JpegEncodeOptions::default()).unwrap();
        let decoded = decode(&bytes).unwrap();
        match &decoded.image {
            JpegImage::Srgb8(dec_img) => {
                assert_eq!(dec_img.width(), 4);
                assert_eq!(dec_img.height(), 4);
            }
            other => panic!("expected Srgb8, got {:?}", other),
        }
    }

    #[test]
    fn encode_jpeg_image_srgb_mono8() {
        let img = JpegImage::SrgbMono8(Image::fill(4, 4, SrgbMono8::new(200)));
        let bytes = encode_jpeg_image(&img, &JpegEncodeOptions::default()).unwrap();
        let decoded = decode(&bytes).unwrap();
        match &decoded.image {
            JpegImage::SrgbMono8(_) => {}
            other => panic!("expected SrgbMono8, got {:?}", other),
        }
    }

    #[test]
    fn encode_jpeg_image_srgb_mono16_unsupported() {
        let img = JpegImage::SrgbMono16(Image::fill(2, 2, SrgbMono16::new(4000)));
        let result = encode_jpeg_image(&img, &JpegEncodeOptions::default());
        match result {
            Err(IoError::UnsupportedFeature { .. }) => {} // expected
            other => panic!("expected UnsupportedFeature, got {:?}", other),
        }
    }

    #[test]
    fn encode_pixel_values_approximately_correct() {
        // JPEG is lossy, but with quality 100, values should be close.
        let img = Image::fill(8, 8, Srgb8::new(200, 100, 50));
        let opts = JpegEncodeOptions {
            quality: 100,
            ..Default::default()
        };
        let bytes = encode(&img, &opts).unwrap();
        let decoded = decode(&bytes).unwrap();
        match &decoded.image {
            JpegImage::Srgb8(dec_img) => {
                let px = dec_img.get(4, 4).unwrap();
                assert!((px.r.0 as i16 - 200).unsigned_abs() < 5, "red: {}", px.r.0);
                assert!(
                    (px.g.0 as i16 - 100).unsigned_abs() < 5,
                    "green: {}",
                    px.g.0
                );
                assert!((px.b.0 as i16 - 50).unsigned_abs() < 5, "blue: {}", px.b.0);
            }
            other => panic!("expected Srgb8, got {:?}", other),
        }
    }

    #[test]
    fn encode_error_maps_io_error() {
        let io_err = std::io::Error::new(std::io::ErrorKind::BrokenPipe, "test");
        let enc_err = jpeg_encoder::EncodingError::IoError(io_err);
        let mapped = encode_error(enc_err);
        match mapped {
            IoError::Io(e) => assert_eq!(e.kind(), std::io::ErrorKind::BrokenPipe),
            other => panic!("expected IoError::Io, got {:?}", other),
        }
    }

    #[test]
    fn encode_error_maps_encoding_error() {
        // BadImageData is a non-IO encoding error.
        let enc_err = jpeg_encoder::EncodingError::BadImageData {
            length: 10,
            required: 12,
        };
        let mapped = encode_error(enc_err);
        match mapped {
            IoError::EncodeFailed { .. } => {} // expected
            other => panic!("expected IoError::EncodeFailed, got {:?}", other),
        }
    }

    // ─────────────────────────────────────────────────────────────────────
    // P1-3: JPEG spec limits dimensions to u16 in the SOFn marker.
    // Casting `as u16` silently wraps; the encoder must validate and
    // return Err instead.
    // ─────────────────────────────────────────────────────────────────────

    #[test]
    fn encode_rejects_width_exceeding_u16_max() {
        // 65_536 wide ⇒ exceeds JPEG's 16-bit width field by 1.
        // Mono8 ⇒ 64 KiB allocation, cheap for a test.
        let img: Image<SrgbMono8> = Image::fill(u16::MAX as usize + 1, 1, SrgbMono8::new(0));
        let result = encode(&img, &JpegEncodeOptions::default());
        match result {
            Err(IoError::UnsupportedFeature { reason }) => {
                assert!(
                    reason.contains("65535") || reason.contains("dimensions"),
                    "unexpected reason: {reason}"
                );
            }
            other => panic!("expected UnsupportedFeature, got {:?}", other),
        }
    }

    #[test]
    fn encode_rejects_height_exceeding_u16_max() {
        let img: Image<SrgbMono8> = Image::fill(1, u16::MAX as usize + 1, SrgbMono8::new(0));
        let result = encode(&img, &JpegEncodeOptions::default());
        assert!(
            matches!(result, Err(IoError::UnsupportedFeature { .. })),
            "expected UnsupportedFeature, got {:?}",
            result
        );
    }

    #[test]
    fn encode_accepts_max_valid_dimension() {
        // 65_535 (= u16::MAX) is the largest spec-compliant width.
        // Use 1px tall ⇒ 64 KiB, encodes quickly.
        let img: Image<SrgbMono8> = Image::fill(u16::MAX as usize, 1, SrgbMono8::new(42));
        let result = encode(&img, &JpegEncodeOptions::default());
        assert!(
            result.is_ok(),
            "expected Ok for max valid width, got {:?}",
            result.err()
        );
    }

    // ═════════════════════════════════════════════════════════════════════
    // Roundtrip integration tests (Phase 5)
    // ═════════════════════════════════════════════════════════════════════

    #[test]
    fn roundtrip_srgb8_encode_decode() {
        let img = Image::fill(16, 12, Srgb8::new(100, 150, 200));
        let bytes = encode(&img, &JpegEncodeOptions::default()).unwrap();
        let decoded = decode(&bytes).unwrap();
        match &decoded.image {
            JpegImage::Srgb8(dec_img) => {
                assert_eq!(dec_img.width(), 16);
                assert_eq!(dec_img.height(), 12);
            }
            other => panic!("expected Srgb8, got {:?}", other),
        }
        assert_eq!(decoded.metadata.source_bit_depth, JpegBitDepth::Eight);
    }

    #[test]
    fn roundtrip_srgb_mono8_encode_decode() {
        let img = Image::fill(16, 12, SrgbMono8::new(180));
        let bytes = encode(&img, &JpegEncodeOptions::default()).unwrap();
        let decoded = decode(&bytes).unwrap();
        match &decoded.image {
            JpegImage::SrgbMono8(dec_img) => {
                assert_eq!(dec_img.width(), 16);
                assert_eq!(dec_img.height(), 12);
            }
            other => panic!("expected SrgbMono8, got {:?}", other),
        }
    }

    #[test]
    fn roundtrip_via_encode_jpeg_image() {
        let orig = JpegImage::Srgb8(Image::fill(8, 8, Srgb8::new(50, 100, 150)));
        let bytes = encode_jpeg_image(&orig, &JpegEncodeOptions::default()).unwrap();
        let decoded = decode(&bytes).unwrap();
        match (&orig, &decoded.image) {
            (JpegImage::Srgb8(a), JpegImage::Srgb8(b)) => {
                assert_eq!(a.width(), b.width());
                assert_eq!(a.height(), b.height());
            }
            _ => panic!("variant mismatch"),
        }
    }

    #[test]
    fn decode_reader_matches_decode_fully() {
        // After R2 fixup, decode_reader should produce identical results
        // to decode, including comments and pixel density.
        let jpeg = build_jpeg_rgb(8, 6, 100, 150, 200);
        let jpeg = inject_com_marker(&jpeg, "reader test");
        let jpeg = inject_jfif_app0(&jpeg, 1, 72, 72);
        let d1 = decode(&jpeg).unwrap();
        let d2 = decode_reader(std::io::Cursor::new(&jpeg)).unwrap();
        // Image dimensions and variant match.
        match (&d1.image, &d2.image) {
            (JpegImage::Srgb8(a), JpegImage::Srgb8(b)) => {
                assert_eq!(a.width(), b.width());
                assert_eq!(a.height(), b.height());
            }
            _ => panic!("variant mismatch"),
        }
        // Metadata matches.
        assert_eq!(d1.metadata.comments, d2.metadata.comments);
        assert_eq!(d1.metadata.pixel_density, d2.metadata.pixel_density);
        assert_eq!(d1.metadata.source_bit_depth, d2.metadata.source_bit_depth);
        assert_eq!(d1.metadata.color_space, d2.metadata.color_space);
    }
}