stegoeggo 0.2.2

Rights-reservation metadata and AI-training restriction notices for images, with optional steganographic markers
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
use serde::{Deserialize, Serialize};
use std::sync::Arc;

/// IPTC Photo Metadata Standard 2023.1 - DMI (Data Mining) tags for AI exclusion.
/// These tags communicate whether content may be used for AI/ML training.
///
/// When injected into XMP metadata, the TDM Reservation Protocol (ISO/IEC 21000-21)
/// property `tdm:reserve_tdm` is also included: `"1"` for all prohibition values,
/// `"0"` for `Allowed`. This is the standard referenced by the EU AI Act (2024).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[non_exhaustive]
pub enum DmiValue {
    /// No DMI restriction specified (default).
    #[default]
    Unspecified,
    /// Content may be used for AI/ML training.
    Allowed,
    /// Prohibited for AI/ML training.
    ProhibitedAiMlTraining,
    /// Prohibited for generative AI training.
    ProhibitedGenAiMlTraining,
    /// Prohibited except for search engine indexing.
    ProhibitedExceptSearchEngineIndexing,
    /// All uses prohibited.
    Prohibited,
    /// Prohibited, see constraints for details.
    ProhibitedSeeConstraints,
}

impl DmiValue {
    /// Returns the string representation of this DMI value.
    #[must_use]
    pub fn as_str(&self) -> &'static str {
        match self {
            DmiValue::Unspecified => "Unspecified",
            DmiValue::Allowed => "Allowed",
            DmiValue::ProhibitedAiMlTraining => "ProhibitedAiMlTraining",
            DmiValue::ProhibitedGenAiMlTraining => "ProhibitedGenAiMlTraining",
            DmiValue::ProhibitedExceptSearchEngineIndexing => {
                "ProhibitedExceptSearchEngineIndexing"
            }
            DmiValue::Prohibited => "Prohibited",
            DmiValue::ProhibitedSeeConstraints => "ProhibitedSeeConstraints",
        }
    }

    /// Returns the IPTC XMP property name for this DMI value.
    ///
    /// Note: The IPTC Photo Metadata Standard defines only two property names:
    /// `Iptc4xmpExt:DMI-Allowed` and `Iptc4xmpExt:DMI-Prohibited`.
    /// The specific prohibition granularity (`ProhibitedAiMlTraining`,
    /// `ProhibitedGenAiMlTraining`, etc.) is conveyed via the *value* of the
    /// property (returned by `as_str()`), not the property name itself.
    pub fn to_iptc_property(&self) -> &'static str {
        match self {
            DmiValue::Unspecified => "Iptc4xmpExt:DMI",
            DmiValue::Allowed => "Iptc4xmpExt:DMI-Allowed",
            DmiValue::ProhibitedAiMlTraining => "Iptc4xmpExt:DMI-Prohibited",
            DmiValue::ProhibitedGenAiMlTraining => "Iptc4xmpExt:DMI-Prohibited",
            DmiValue::ProhibitedExceptSearchEngineIndexing => "Iptc4xmpExt:DMI-Prohibited",
            DmiValue::Prohibited => "Iptc4xmpExt:DMI-Prohibited",
            DmiValue::ProhibitedSeeConstraints => "Iptc4xmpExt:DMI-Prohibited",
        }
    }

    /// Returns the canonical PLUS controlled-vocabulary key identifier for this DMI value.
    #[must_use]
    pub fn plus_vocab_key(self) -> &'static str {
        match self {
            DmiValue::Unspecified => "DMI-UNSPECIFIED",
            DmiValue::Allowed => "DMI-ALLOWED",
            DmiValue::ProhibitedAiMlTraining => "DMI-PROHIBITED-AIMLTRAINING",
            DmiValue::ProhibitedGenAiMlTraining => "DMI-PROHIBITED-GENAIMLTRAINING",
            DmiValue::ProhibitedExceptSearchEngineIndexing => {
                "DMI-PROHIBITED-EXCEPTSEARCHENGINEINDEXING"
            }
            DmiValue::Prohibited => "DMI-PROHIBITED",
            DmiValue::ProhibitedSeeConstraints => "DMI-PROHIBITED-SEECONSTRAINT",
        }
    }

    /// Parse a canonical PLUS vocabulary key identifier into a `DmiValue`.
    /// Returns `None` for unknown or malformed values.
    #[must_use]
    pub fn from_plus_vocab_key(key: &str) -> Option<Self> {
        match key {
            "DMI-UNSPECIFIED" => Some(DmiValue::Unspecified),
            "DMI-ALLOWED" => Some(DmiValue::Allowed),
            "DMI-PROHIBITED-AIMLTRAINING" => Some(DmiValue::ProhibitedAiMlTraining),
            "DMI-PROHIBITED-GENAIMLTRAINING" => Some(DmiValue::ProhibitedGenAiMlTraining),
            "DMI-PROHIBITED-EXCEPTSEARCHENGINEINDEXING" => {
                Some(DmiValue::ProhibitedExceptSearchEngineIndexing)
            }
            "DMI-PROHIBITED" => Some(DmiValue::Prohibited),
            "DMI-PROHIBITED-SEECONSTRAINT" => Some(DmiValue::ProhibitedSeeConstraints),
            _ => None,
        }
    }
}

/// PLUS LDF namespace URI for the `plus` prefix.
pub const PLUS_NAMESPACE: &str = "http://ns.useplus.org/ldf/xmp/1.0/";
/// PLUS Data Mining property name (without prefix).
pub const PLUS_DATA_MINING_PROPERTY: &str = "plus:DataMining";

/// Evidence profile controlling the interpretation of protection warnings
/// and the default evidence posture.
///
/// An evidence profile answers the question "what evidence model is the caller
/// trying to express?" while [`ProtectionLevel`] answers "how much processing
/// should occur?"
///
/// - [`LegalNotice`](Self::LegalNotice): Standards-aligned metadata notice.
///   No MAC key required.
/// - [`LegalNoticeWithStego`](Self::LegalNoticeWithStego): Metadata notice
///   plus best-effort hidden marker. No MAC key required.
/// - [`AuthenticatedProvenance`](Self::AuthenticatedProvenance): Cryptographic
///   proof that a hidden payload was generated by a party with the configured
///   key. MAC key expected.
/// - [`Maximal`](Self::Maximal): All available legal notice and evidence channels.
#[deprecated(
    since = "0.4.0",
    note = "Use ProtectionPreset instead. EvidenceProfile only changes warning interpretation; ProtectionPreset controls actual processing behavior."
)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[non_exhaustive]
pub enum EvidenceProfile {
    /// Standards-aligned metadata notice. No MAC key required.
    /// Missing MAC is not a warning.
    #[default]
    LegalNotice,
    /// Metadata notice plus best-effort hidden marker.
    /// No MAC key required. Stego capacity warnings are best-effort, not
    /// legal-notice failures.
    LegalNoticeWithStego,
    /// Cryptographic proof that a hidden payload was generated by a party
    /// with the configured key. MAC key expected; missing MAC is a warning.
    AuthenticatedProvenance,
    /// All available legal notice and evidence channels.
    /// MAC key used if provided; missing MAC is informational.
    Maximal,
}

#[allow(deprecated)]
impl EvidenceProfile {
    /// Returns the lowercase string representation of this evidence profile.
    #[must_use]
    pub fn as_str(&self) -> &'static str {
        match self {
            EvidenceProfile::LegalNotice => "legal-notice",
            EvidenceProfile::LegalNoticeWithStego => "legal-notice-stego",
            EvidenceProfile::AuthenticatedProvenance => "authenticated-provenance",
            EvidenceProfile::Maximal => "maximal",
        }
    }
}

/// Policy for updating metadata on repeated image processing.
///
/// Controls how the protection pipeline handles existing metadata when
/// re-processing an already-protected image.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[non_exhaustive]
pub enum MetadataUpdatePolicy {
    /// Replace all StegoEggo-owned metadata properties. Preserve unrelated
    /// metadata (camera EXIF, color profiles, etc.). This is the default.
    #[default]
    ReplaceStegoOwned,
    /// Fail with an error if conflicting StegoEggo metadata already exists.
    FailOnConflict,
    /// Preserve existing StegoEggo metadata and only add new fields.
    /// Never overwrites existing values.
    PreserveExisting,
}

impl MetadataUpdatePolicy {
    /// Returns the lowercase string representation of this policy.
    #[must_use]
    pub fn as_str(&self) -> &'static str {
        match self {
            MetadataUpdatePolicy::ReplaceStegoOwned => "replace-stego-owned",
            MetadataUpdatePolicy::FailOnConflict => "fail-on-conflict",
            MetadataUpdatePolicy::PreserveExisting => "preserve-existing",
        }
    }
}

impl std::fmt::Display for MetadataUpdatePolicy {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            MetadataUpdatePolicy::ReplaceStegoOwned => write!(f, "ReplaceStegoOwned"),
            MetadataUpdatePolicy::FailOnConflict => write!(f, "FailOnConflict"),
            MetadataUpdatePolicy::PreserveExisting => write!(f, "PreserveExisting"),
        }
    }
}

/// Protection level determining the protection strategy applied to images.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[non_exhaustive]
pub enum ProtectionLevel {
    /// No protection applied.
    Disabled,
    /// Metadata injection with minimal steganography.
    Light,
    /// Full steganography + metadata injection (default).
    #[default]
    Standard,
}

impl ProtectionLevel {
    /// Returns the lowercase string representation of this protection level.
    #[must_use]
    pub fn as_str(&self) -> &'static str {
        match self {
            ProtectionLevel::Disabled => "disabled",
            ProtectionLevel::Light => "light",
            ProtectionLevel::Standard => "standard",
        }
    }

    /// Encodes this protection level as a single byte for payload serialization.
    #[must_use]
    pub fn to_byte(&self) -> u8 {
        match self {
            ProtectionLevel::Disabled => 0,
            ProtectionLevel::Light => 1,
            ProtectionLevel::Standard => 2,
        }
    }

    /// Decodes a protection level from a byte. Returns `None` for unknown values.
    #[must_use]
    pub fn from_byte(b: u8) -> Option<Self> {
        match b {
            0 => Some(ProtectionLevel::Disabled),
            1 => Some(ProtectionLevel::Light),
            2 => Some(ProtectionLevel::Standard),
            _ => None,
        }
    }

    /// Converts this legacy protection level into a [`ProtectionRequest`] template.
    ///
    /// This is a compatibility adapter for callers migrating from the level-based API.
    /// The returned request has default processing options and no legal metadata —
    /// callers should chain builder methods to add notice, policy, and metadata.
    #[must_use]
    pub fn to_request(&self, notice: RightsNotice, policy: RightsPolicy) -> ProtectionRequest {
        match self {
            ProtectionLevel::Disabled => {
                // Disabled: metadata-only with no channels
                ProtectionRequest::new(
                    notice,
                    policy,
                    ProtectionChannels {
                        rights_metadata: false,
                        hidden_marker: HiddenMarkerMode::Disabled,
                        authentication: AuthenticationMode::None,
                    },
                )
            }
            ProtectionLevel::Light => {
                // Light: metadata + minimal seed stego (Q-table for JPEG, LSB redundancy=1)
                // Map to BestEffort hidden marker
                ProtectionRequest::new(notice, policy, ProtectionChannels::with_hidden_marker())
            }
            ProtectionLevel::Standard => {
                // Standard: full stego + metadata
                ProtectionRequest::new(notice, policy, ProtectionChannels::with_hidden_marker())
            }
        }
    }
}

/// Image output format for encoding protected images.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[non_exhaustive]
pub enum ImageOutputFormat {
    /// Portable Network Graphics (default).
    #[default]
    Png,
    /// Joint Photographic Experts Group.
    Jpeg,
    /// WebP image format.
    WebP,
}

/// Default output format used when none is specified.
pub const DEFAULT_OUTPUT_FORMAT: ImageOutputFormat = ImageOutputFormat::Png;

impl ImageOutputFormat {
    /// Parses an image format from a file extension (case-insensitive).
    ///
    /// Recognizes `"png"`, `"jpg"`, `"jpeg"`, and `"webp"`.
    #[must_use]
    pub fn from_extension(ext: &str) -> Option<Self> {
        match ext.to_lowercase().as_str() {
            "png" => Some(ImageOutputFormat::Png),
            "jpg" | "jpeg" => Some(ImageOutputFormat::Jpeg),
            "webp" => Some(ImageOutputFormat::WebP),
            _ => None,
        }
    }

    /// Detects the image format from file magic bytes.
    ///
    /// Returns `None` if the bytes are too short or the format is unrecognized.
    #[must_use]
    pub fn from_magic_bytes(bytes: &[u8]) -> Option<Self> {
        if bytes.len() < 4 {
            return None;
        }
        if bytes.starts_with(&[0x89, 0x50, 0x4E, 0x47]) {
            return Some(ImageOutputFormat::Png);
        }
        if bytes.starts_with(&[0xFF, 0xD8, 0xFF]) {
            return Some(ImageOutputFormat::Jpeg);
        }
        if bytes.len() >= 12 && &bytes[0..4] == b"RIFF" && &bytes[8..12] == b"WEBP" {
            return Some(ImageOutputFormat::WebP);
        }
        None
    }

    /// Returns `true` if the bytes start with the PNG magic number.
    #[must_use]
    pub fn is_png(bytes: &[u8]) -> bool {
        bytes.len() >= 4 && bytes.starts_with(&[0x89, 0x50, 0x4E, 0x47])
    }

    /// Returns `true` if the bytes start with the JPEG magic number.
    #[must_use]
    pub fn is_jpeg(bytes: &[u8]) -> bool {
        bytes.len() >= 3 && bytes.starts_with(&[0xFF, 0xD8, 0xFF])
    }

    /// Returns `true` if the bytes start with the RIFF/WEBP magic number.
    #[must_use]
    pub fn is_webp(bytes: &[u8]) -> bool {
        bytes.len() >= 12 && &bytes[0..4] == b"RIFF" && &bytes[8..12] == b"WEBP"
    }

    /// Returns the canonical file extension for this format.
    pub fn extension(&self) -> &'static str {
        match self {
            ImageOutputFormat::Png => "png",
            ImageOutputFormat::Jpeg => "jpg",
            ImageOutputFormat::WebP => "webp",
        }
    }

    /// Converts to the corresponding `image::ImageFormat` variant.
    #[must_use]
    pub fn to_image_format(self) -> image::ImageFormat {
        match self {
            ImageOutputFormat::Png => image::ImageFormat::Png,
            ImageOutputFormat::Jpeg => image::ImageFormat::Jpeg,
            ImageOutputFormat::WebP => image::ImageFormat::WebP,
        }
    }
}

/// A text value with an associated language tag.
///
/// Used for metadata fields that support localization, such as
/// `xmpRights:UsageTerms`. The default language is `"x-default"`.
///
/// # Examples
///
/// ```ignore
/// use stegoeggo::LocalizedText;
///
/// let terms = LocalizedText::new("All rights reserved.");
/// assert_eq!(terms.text(), "All rights reserved.");
/// assert_eq!(terms.lang(), "x-default");
///
/// let french = LocalizedText::with_lang("Tous droits réservés.", "fr");
/// assert_eq!(french.lang(), "fr");
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct LocalizedText {
    text: String,
    #[serde(default = "default_lang")]
    lang: String,
}

fn default_lang() -> String {
    "x-default".to_string()
}

impl LocalizedText {
    /// Creates a new `LocalizedText` with the default language (`"x-default"`).
    #[must_use]
    pub fn new(text: impl Into<String>) -> Self {
        Self {
            text: text.into(),
            lang: default_lang(),
        }
    }

    /// Creates a new `LocalizedText` with an explicit language tag.
    #[must_use]
    pub fn with_lang(text: impl Into<String>, lang: impl Into<String>) -> Self {
        Self {
            text: text.into(),
            lang: lang.into(),
        }
    }

    /// Returns the text content.
    #[must_use]
    pub fn text(&self) -> &str {
        &self.text
    }

    /// Returns the language tag.
    #[must_use]
    pub fn lang(&self) -> &str {
        &self.lang
    }
}

impl From<String> for LocalizedText {
    fn from(s: String) -> Self {
        Self::new(s)
    }
}

impl From<&str> for LocalizedText {
    fn from(s: &str) -> Self {
        Self::new(s)
    }
}

impl std::fmt::Display for LocalizedText {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.text)
    }
}

/// Normalized rights notice produced by the pipeline before format encoding.
///
/// All format writers (PNG tEXt, JPEG COM, WebP XMP) consume the same
/// `RightsNotice` instance, ensuring semantically equivalent metadata
/// regardless of output format.
///
/// Created by [`ProtectionContext::normalize_rights_notice`] or
/// [`MetadataTrapProtector::normalize_rights_notice`](crate::MetadataTrapProtector::normalize_rights_notice).
#[derive(Debug, Clone, Default)]
pub struct RightsNotice {
    copyright_holder: Option<String>,
    contact_email: Option<String>,
    license_url: Option<String>,
    usage_terms: Option<String>,
    usage_terms_lang: Option<String>,
    creation_date: Option<String>,
    ai_constraints: Option<String>,
    web_statement_of_rights: Option<String>,
    creator: Option<String>,
    credit_line: Option<String>,
    copyright_owner: Option<String>,
    licensor_name: Option<String>,
    licensor_email: Option<String>,
    licensor_url: Option<String>,
    metadata_date: Option<String>,
    notice_applied_at: Option<String>,
    dmi: Option<DmiValue>,
    seed: Option<u64>,
}

impl RightsNotice {
    /// Creates a new empty `RightsNotice`.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Returns the copyright holder name, if set.
    #[must_use]
    pub fn copyright_holder(&self) -> Option<&str> {
        self.copyright_holder.as_deref()
    }

    /// Returns the contact email, if set.
    #[must_use]
    pub fn contact_email(&self) -> Option<&str> {
        self.contact_email.as_deref()
    }

    /// Returns the license URL, if set.
    #[must_use]
    pub fn license_url(&self) -> Option<&str> {
        self.license_url.as_deref()
    }

    /// Returns the usage terms, if set.
    #[must_use]
    pub fn usage_terms(&self) -> Option<&str> {
        self.usage_terms.as_deref()
    }

    /// Returns the usage terms language tag, if set.
    #[must_use]
    pub fn usage_terms_lang(&self) -> Option<&str> {
        self.usage_terms_lang.as_deref()
    }

    /// Returns the creation date, if set.
    #[must_use]
    pub fn creation_date(&self) -> Option<&str> {
        self.creation_date.as_deref()
    }

    /// Returns the AI constraints, if set.
    #[must_use]
    pub fn ai_constraints(&self) -> Option<&str> {
        self.ai_constraints.as_deref()
    }

    /// Returns the web statement of rights URL, if set.
    #[must_use]
    pub fn web_statement_of_rights(&self) -> Option<&str> {
        self.web_statement_of_rights.as_deref()
    }

    /// Returns the creator name, if set.
    #[must_use]
    pub fn creator(&self) -> Option<&str> {
        self.creator.as_deref()
    }

    /// Returns the credit line, if set.
    #[must_use]
    pub fn credit_line(&self) -> Option<&str> {
        self.credit_line.as_deref()
    }

    /// Returns the copyright owner name, if set.
    #[must_use]
    pub fn copyright_owner(&self) -> Option<&str> {
        self.copyright_owner.as_deref()
    }

    /// Returns the licensor name, if set.
    #[must_use]
    pub fn licensor_name(&self) -> Option<&str> {
        self.licensor_name.as_deref()
    }

    /// Returns the licensor email, if set.
    #[must_use]
    pub fn licensor_email(&self) -> Option<&str> {
        self.licensor_email.as_deref()
    }

    /// Returns the licensor URL, if set.
    #[must_use]
    pub fn licensor_url(&self) -> Option<&str> {
        self.licensor_url.as_deref()
    }

    /// Returns the metadata date, if set.
    #[must_use]
    pub fn metadata_date(&self) -> Option<&str> {
        self.metadata_date.as_deref()
    }

    /// Returns the notice-applied-at timestamp, if set.
    #[must_use]
    pub fn notice_applied_at(&self) -> Option<&str> {
        self.notice_applied_at.as_deref()
    }

    /// Returns the resolved DMI value, if any.
    #[must_use]
    pub fn dmi(&self) -> Option<DmiValue> {
        self.dmi
    }

    /// Returns the protection seed, if any.
    #[must_use]
    pub fn seed(&self) -> Option<u64> {
        self.seed
    }

    /// Returns `true` if any legal field is set.
    #[must_use]
    pub fn has_legal_content(&self) -> bool {
        self.copyright_holder.is_some()
            || self.contact_email.is_some()
            || self.license_url.is_some()
            || self.usage_terms.is_some()
            || self.creation_date.is_some()
            || self.ai_constraints.is_some()
            || self.web_statement_of_rights.is_some()
            || self.creator.is_some()
            || self.credit_line.is_some()
            || self.copyright_owner.is_some()
            || self.licensor_name.is_some()
            || self.licensor_email.is_some()
            || self.licensor_url.is_some()
            || self.metadata_date.is_some()
            || self.notice_applied_at.is_some()
    }

    /// Sets the copyright holder name.
    #[must_use]
    pub fn with_copyright_holder(mut self, holder: impl Into<String>) -> Self {
        self.copyright_holder = Some(holder.into());
        self
    }

    /// Sets the contact email for IP claims.
    #[must_use]
    pub fn with_contact_email(mut self, email: impl Into<String>) -> Self {
        self.contact_email = Some(email.into());
        self
    }

    /// Sets the license URL.
    #[must_use]
    pub fn with_license_url(mut self, url: impl Into<String>) -> Self {
        self.license_url = Some(url.into());
        self
    }

    /// Sets the usage terms (e.g., "All Rights Reserved").
    #[must_use]
    pub fn with_usage_terms(mut self, terms: impl Into<String>) -> Self {
        self.usage_terms = Some(terms.into());
        self
    }

    /// Sets the creation date string.
    #[must_use]
    pub fn with_creation_date(mut self, date: impl Into<String>) -> Self {
        self.creation_date = Some(date.into());
        self
    }

    /// Sets the AI training constraints (e.g., "No AI training permitted").
    #[must_use]
    pub fn with_ai_constraints(mut self, constraints: impl Into<String>) -> Self {
        self.ai_constraints = Some(constraints.into());
        self
    }

    /// Sets the web statement of rights URL.
    #[must_use]
    pub fn with_web_statement_of_rights(mut self, statement: impl Into<String>) -> Self {
        self.web_statement_of_rights = Some(statement.into());
        self
    }

    /// Sets the creator name.
    #[must_use]
    pub fn with_creator(mut self, creator: impl Into<String>) -> Self {
        self.creator = Some(creator.into());
        self
    }

    /// Sets the credit line.
    #[must_use]
    pub fn with_credit_line(mut self, line: impl Into<String>) -> Self {
        self.credit_line = Some(line.into());
        self
    }

    /// Sets the copyright owner name.
    #[must_use]
    pub fn with_copyright_owner(mut self, owner: impl Into<String>) -> Self {
        self.copyright_owner = Some(owner.into());
        self
    }

    /// Sets the licensor name.
    #[must_use]
    pub fn with_licensor_name(mut self, name: impl Into<String>) -> Self {
        self.licensor_name = Some(name.into());
        self
    }

    /// Sets the licensor email.
    #[must_use]
    pub fn with_licensor_email(mut self, email: impl Into<String>) -> Self {
        self.licensor_email = Some(email.into());
        self
    }

    /// Sets the licensor URL.
    #[must_use]
    pub fn with_licensor_url(mut self, url: impl Into<String>) -> Self {
        self.licensor_url = Some(url.into());
        self
    }

    /// Sets the metadata date.
    #[must_use]
    pub fn with_metadata_date(mut self, date: impl Into<String>) -> Self {
        self.metadata_date = Some(date.into());
        self
    }

    /// Sets the notice-applied-at timestamp.
    #[must_use]
    pub fn with_notice_applied_at(mut self, timestamp: impl Into<String>) -> Self {
        self.notice_applied_at = Some(timestamp.into());
        self
    }

    /// Sets the DMI value.
    #[must_use]
    pub fn with_dmi(mut self, dmi: DmiValue) -> Self {
        self.dmi = Some(dmi);
        self
    }

    /// Sets the seed.
    #[must_use]
    pub fn with_seed(mut self, seed: u64) -> Self {
        self.seed = Some(seed);
        self
    }
}

/// Legal metadata for copyright and AI training restrictions.
/// This information is embedded in the image for legal discovery and proof of intent.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct LegalMetadata {
    copyright_holder: Option<String>,
    contact_email: Option<String>,
    license_url: Option<String>,
    usage_terms: Option<String>,
    usage_terms_lang: Option<String>,
    creation_date: Option<String>,
    ai_constraints: Option<String>,
    web_statement_of_rights: Option<String>,
    creator: Option<String>,
    credit_line: Option<String>,
    copyright_owner: Option<String>,
    licensor_name: Option<String>,
    licensor_email: Option<String>,
    licensor_url: Option<String>,
    metadata_date: Option<String>,
    notice_applied_at: Option<String>,
}

impl LegalMetadata {
    /// Maximum byte length for any single metadata field.
    ///
    /// This limit ensures field values fit safely within JPEG segment length fields
    /// (u16: 65535 bytes max) and PNG chunk length fields (u32: 4 GiB max) after
    /// accounting for overhead bytes in the marker/chunk structure. The 8 KiB limit
    /// is generous for all practical metadata fields while preventing overflow.
    pub const MAX_FIELD_LEN: usize = 8192;

    /// Creates a new `LegalMetadata` with all fields unset.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Validates that all set fields are within the allowed byte length.
    ///
    /// Returns `Ok(())` if all fields are valid, or `Err` with a description
    /// of the first oversized field found.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Config`] if any field exceeds [`Self::MAX_FIELD_LEN`] bytes.
    ///
    /// URL fields (`license_url`, `web_statement_of_rights`, `licensor_url`)
    /// are also validated for basic syntactic correctness (scheme + authority).
    pub fn validate(&self) -> crate::Result<()> {
        let check = |name: &str, val: &Option<String>| -> crate::Result<()> {
            if let Some(v) = val {
                if v.len() > Self::MAX_FIELD_LEN {
                    return Err(crate::Error::Config(format!(
                        "Legal metadata field '{}' exceeds maximum length of {} bytes (got {})",
                        name,
                        Self::MAX_FIELD_LEN,
                        v.len()
                    )));
                }
            }
            Ok(())
        };
        let check_url = |name: &str, val: &Option<String>| -> crate::Result<()> {
            if let Some(v) = val {
                Self::validate_url_syntax(name, v)?;
            }
            Ok(())
        };
        check("copyright_holder", &self.copyright_holder)?;
        check("contact_email", &self.contact_email)?;
        check_url("license_url", &self.license_url)?;
        check("usage_terms", &self.usage_terms)?;
        check("creation_date", &self.creation_date)?;
        check("ai_constraints", &self.ai_constraints)?;
        check_url("web_statement_of_rights", &self.web_statement_of_rights)?;
        check("creator", &self.creator)?;
        check("credit_line", &self.credit_line)?;
        check("copyright_owner", &self.copyright_owner)?;
        check("licensor_name", &self.licensor_name)?;
        check("licensor_email", &self.licensor_email)?;
        check_url("licensor_url", &self.licensor_url)?;
        check("metadata_date", &self.metadata_date)?;
        check("notice_applied_at", &self.notice_applied_at)?;

        let check_date = |name: &str, val: &Option<String>| -> crate::Result<()> {
            if let Some(v) = val {
                Self::validate_date(name, v)?;
            }
            Ok(())
        };
        check_date("creation_date", &self.creation_date)?;
        check_date("metadata_date", &self.metadata_date)?;
        check_date("notice_applied_at", &self.notice_applied_at)?;

        Ok(())
    }

    fn validate_url_syntax(field_name: &str, url: &str) -> crate::Result<()> {
        if url.is_empty() {
            return Err(crate::Error::Config(format!(
                "URL field '{}' must not be empty",
                field_name
            )));
        }
        let has_scheme = url.contains("://");
        if !has_scheme {
            return Err(crate::Error::Config(format!(
                "URL field '{}' must include a scheme (e.g., https://): {}",
                field_name, url
            )));
        }
        let after_scheme = &url[url.find("://").unwrap() + 3..];
        if after_scheme.is_empty() {
            return Err(crate::Error::Config(format!(
                "URL field '{}' must include an authority after the scheme: {}",
                field_name, url
            )));
        }
        Ok(())
    }

    fn validate_date(field_name: &str, value: &str) -> crate::Result<()> {
        if value.is_empty() {
            return Err(crate::Error::Config(format!(
                "Date field '{}' must not be empty",
                field_name
            )));
        }
        let valid = match value.len() {
            10 => {
                // YYYY-MM-DD
                value.as_bytes()[4] == b'-'
                    && value.as_bytes()[7] == b'-'
                    && value.bytes().enumerate().all(|(i, b)| match i {
                        4 | 7 => b == b'-',
                        _ => b.is_ascii_digit(),
                    })
            }
            20 => {
                // YYYY-MM-DDTHH:MM:SSZ
                value.as_bytes()[4] == b'-'
                    && value.as_bytes()[7] == b'-'
                    && value.as_bytes()[10] == b'T'
                    && value.as_bytes()[13] == b':'
                    && value.as_bytes()[16] == b':'
                    && value.as_bytes()[19] == b'Z'
                    && value.bytes().enumerate().all(|(i, b)| match i {
                        4 | 7 => b == b'-',
                        10 => b == b'T',
                        13 | 16 => b == b':',
                        19 => b == b'Z',
                        _ => b.is_ascii_digit(),
                    })
            }
            25 => {
                // YYYY-MM-DDTHH:MM:SS+HH:MM
                value.as_bytes()[4] == b'-'
                    && value.as_bytes()[7] == b'-'
                    && value.as_bytes()[10] == b'T'
                    && value.as_bytes()[13] == b':'
                    && value.as_bytes()[16] == b':'
                    && (value.as_bytes()[19] == b'+' || value.as_bytes()[19] == b'-')
                    && value.as_bytes()[22] == b':'
                    && value.bytes().enumerate().all(|(i, b)| match i {
                        4 | 7 => b == b'-',
                        10 => b == b'T',
                        13 | 16 | 22 => b == b':',
                        19 => b == b'+' || b == b'-',
                        _ => b.is_ascii_digit(),
                    })
            }
            _ => false,
        };
        if !valid {
            return Err(crate::Error::Config(format!(
                "Date field '{}' must be ISO 8601 format (YYYY-MM-DD, YYYY-MM-DDTHH:MM:SSZ, \
                 or YYYY-MM-DDTHH:MM:SS+HH:MM): {}",
                field_name, value
            )));
        }
        Ok(())
    }

    /// Returns `true` if any legal metadata field is set.
    #[must_use]
    pub fn has_content(&self) -> bool {
        self.copyright_holder.is_some()
            || self.contact_email.is_some()
            || self.license_url.is_some()
            || self.usage_terms.is_some()
            || self.creation_date.is_some()
            || self.ai_constraints.is_some()
            || self.web_statement_of_rights.is_some()
            || self.creator.is_some()
            || self.credit_line.is_some()
            || self.copyright_owner.is_some()
            || self.licensor_name.is_some()
            || self.licensor_email.is_some()
            || self.licensor_url.is_some()
            || self.metadata_date.is_some()
            || self.notice_applied_at.is_some()
    }

    /// Returns the copyright holder name, if set.
    #[must_use]
    pub fn copyright_holder(&self) -> Option<&str> {
        self.copyright_holder.as_deref()
    }

    /// Returns the contact email for IP claims, if set.
    #[must_use]
    pub fn contact_email(&self) -> Option<&str> {
        self.contact_email.as_deref()
    }

    /// Returns the license URL, if set.
    #[must_use]
    pub fn license_url(&self) -> Option<&str> {
        self.license_url.as_deref()
    }

    /// Returns the usage terms string, if set.
    #[must_use]
    pub fn usage_terms(&self) -> Option<&str> {
        self.usage_terms.as_deref()
    }

    /// Returns the usage terms language tag, if set.
    ///
    /// Defaults to `"x-default"` when using [`with_usage_terms_localized`].
    #[must_use]
    pub fn usage_terms_lang(&self) -> Option<&str> {
        self.usage_terms_lang.as_deref()
    }

    /// Returns the creation date string, if set.
    #[must_use]
    pub fn creation_date(&self) -> Option<&str> {
        self.creation_date.as_deref()
    }

    /// Returns the AI training constraints string, if set.
    #[must_use]
    pub fn ai_constraints(&self) -> Option<&str> {
        self.ai_constraints.as_deref()
    }

    /// Returns the web statement of rights URL, if set.
    #[must_use]
    pub fn web_statement_of_rights(&self) -> Option<&str> {
        self.web_statement_of_rights.as_deref()
    }

    /// Returns the creator name, if set.
    #[must_use]
    pub fn creator(&self) -> Option<&str> {
        self.creator.as_deref()
    }

    /// Returns the credit line, if set.
    #[must_use]
    pub fn credit_line(&self) -> Option<&str> {
        self.credit_line.as_deref()
    }

    /// Returns the copyright owner name, if set.
    #[must_use]
    pub fn copyright_owner(&self) -> Option<&str> {
        self.copyright_owner.as_deref()
    }

    /// Returns the licensor name, if set.
    #[must_use]
    pub fn licensor_name(&self) -> Option<&str> {
        self.licensor_name.as_deref()
    }

    /// Returns the licensor email, if set.
    #[must_use]
    pub fn licensor_email(&self) -> Option<&str> {
        self.licensor_email.as_deref()
    }

    /// Returns the licensor URL, if set.
    #[must_use]
    pub fn licensor_url(&self) -> Option<&str> {
        self.licensor_url.as_deref()
    }

    /// Returns the metadata date, if set.
    #[must_use]
    pub fn metadata_date(&self) -> Option<&str> {
        self.metadata_date.as_deref()
    }

    /// Returns the notice-applied-at timestamp, if set.
    #[must_use]
    pub fn notice_applied_at(&self) -> Option<&str> {
        self.notice_applied_at.as_deref()
    }

    /// Sets the copyright holder name.
    #[must_use]
    pub fn with_copyright_holder(mut self, holder: impl Into<String>) -> Self {
        self.copyright_holder = Some(holder.into());
        self
    }

    /// Sets the contact email for IP claims.
    #[must_use]
    pub fn with_contact_email(mut self, email: impl Into<String>) -> Self {
        self.contact_email = Some(email.into());
        self
    }

    /// Sets the license URL.
    #[must_use]
    pub fn with_license_url(mut self, url: impl Into<String>) -> Self {
        self.license_url = Some(url.into());
        self
    }

    /// Sets the usage terms (e.g., "All Rights Reserved").
    #[must_use]
    pub fn with_usage_terms(mut self, terms: impl Into<String>) -> Self {
        self.usage_terms = Some(terms.into());
        self
    }

    /// Sets the usage terms with an explicit language tag.
    ///
    /// The language tag is emitted as `xml:lang` in XMP `rdf:Alt` containers.
    /// Defaults to `"x-default"` if not specified.
    #[must_use]
    pub fn with_usage_terms_localized(mut self, terms: impl Into<LocalizedText>) -> Self {
        let lt = terms.into();
        self.usage_terms = Some(lt.text().to_string());
        self.usage_terms_lang = Some(lt.lang().to_string());
        self
    }

    /// Sets the creation date string.
    #[must_use]
    pub fn with_creation_date(mut self, date: impl Into<String>) -> Self {
        self.creation_date = Some(date.into());
        self
    }

    /// Sets the AI training constraints (e.g., "No AI training permitted").
    #[must_use]
    pub fn with_ai_constraints(mut self, constraints: impl Into<String>) -> Self {
        self.ai_constraints = Some(constraints.into());
        self
    }

    /// Sets the web statement of rights URL.
    #[must_use]
    pub fn with_web_statement_of_rights(mut self, statement: impl Into<String>) -> Self {
        self.web_statement_of_rights = Some(statement.into());
        self
    }

    /// Sets the creator name.
    #[must_use]
    pub fn with_creator(mut self, creator: impl Into<String>) -> Self {
        self.creator = Some(creator.into());
        self
    }

    /// Sets the credit line.
    #[must_use]
    pub fn with_credit_line(mut self, line: impl Into<String>) -> Self {
        self.credit_line = Some(line.into());
        self
    }

    /// Sets the copyright owner name.
    #[must_use]
    pub fn with_copyright_owner(mut self, owner: impl Into<String>) -> Self {
        self.copyright_owner = Some(owner.into());
        self
    }

    /// Sets the licensor name.
    #[must_use]
    pub fn with_licensor_name(mut self, name: impl Into<String>) -> Self {
        self.licensor_name = Some(name.into());
        self
    }

    /// Sets the licensor email.
    #[must_use]
    pub fn with_licensor_email(mut self, email: impl Into<String>) -> Self {
        self.licensor_email = Some(email.into());
        self
    }

    /// Sets the licensor URL.
    #[must_use]
    pub fn with_licensor_url(mut self, url: impl Into<String>) -> Self {
        self.licensor_url = Some(url.into());
        self
    }

    /// Sets the metadata date.
    #[must_use]
    pub fn with_metadata_date(mut self, date: impl Into<String>) -> Self {
        self.metadata_date = Some(date.into());
        self
    }

    /// Sets the notice-applied-at timestamp.
    #[must_use]
    pub fn with_notice_applied_at(mut self, ts: impl Into<String>) -> Self {
        self.notice_applied_at = Some(ts.into());
        self
    }
}

/// Heavy configuration that is shared across requests via `Arc`.
/// Create once, reuse across many image processing calls.
/// This avoids per-request heap allocation of large fields.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ProtectionConfig {
    /// MAC key for cryptographic payload verification.
    ///
    /// # Security
    ///
    /// Without a MAC key, steganographic payload verification uses a non-cryptographic
    /// CRC32 checksum that provides no cryptographic assurance. Always set a
    /// MAC key in adversarial settings to enable HMAC-SHA256 verification.
    mac_key: Option<Vec<u8>>,
    /// Legal metadata for copyright and AI training restrictions.
    legal_metadata: Option<LegalMetadata>,
}

impl ProtectionConfig {
    /// Creates a new `ProtectionConfig` with no MAC key or legal metadata.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the MAC key for cryptographic payload verification.
    #[must_use]
    pub fn with_mac_key(mut self, key: Vec<u8>) -> Self {
        self.mac_key = Some(key);
        self
    }

    /// Sets the legal metadata for content ownership claims.
    #[must_use]
    pub fn with_legal_metadata(mut self, metadata: LegalMetadata) -> Self {
        self.legal_metadata = Some(metadata);
        self
    }

    /// Returns the MAC key, if set.
    #[must_use]
    pub fn mac_key(&self) -> Option<&[u8]> {
        self.mac_key.as_deref()
    }

    /// Returns the legal metadata, if set.
    #[must_use]
    pub fn legal_metadata(&self) -> Option<&LegalMetadata> {
        self.legal_metadata.as_ref()
    }
}

/// Context for protection operations containing intensity and configuration.
///
/// Cheap to clone (heavy fields are in `Arc<ProtectionConfig>`).
#[allow(deprecated)]
#[derive(Debug, Clone, Deserialize)]
pub struct ProtectionContext {
    intensity: f32,
    seed: u64,
    input_format: Option<ImageOutputFormat>,
    output_format: Option<ImageOutputFormat>,
    protection_level: Option<ProtectionLevel>,
    evidence_profile: Option<EvidenceProfile>,
    dmi_value: Option<DmiValue>,
    max_dimension: Option<u32>,
    /// Three-state control for metadata injection (seed, DMI values).
    ///
    /// - `None` (default): use level-based defaults — metadata is injected for
    ///   all protection levels except `Disabled`.
    /// - `Some(true)`: force-enable metadata injection, overriding the level default.
    /// - `Some(false)`: force-disable metadata injection, overriding the level default.
    ///
    /// Omitting `with_metadata_injection()` (leaving this `None`) differs from
    /// calling `.with_metadata_injection(false)` for non-`Disabled` levels:
    /// the former injects metadata; the latter suppresses it.
    inject_metadata: Option<bool>,
    /// Three-state control for legal claim injection (copyright, artist).
    ///
    /// - `None` (default): never inject legal claims (level default is off).
    /// - `Some(true)`: force-enable legal claim injection.
    /// - `Some(false)`: force-disable legal claim injection (same as `None`).
    ///
    /// Legal claims require `LegalMetadata` to be set via
    /// [`with_legal_metadata`](ProtectionContext::with_legal_metadata).
    /// WARNING: Only enable for content you own. May create legal liability otherwise.
    inject_legal_claims: Option<bool>,
    stego_redundancy: Option<usize>,
    jpeg_quality: u8,
    progressive_jpeg: bool,
    /// Tile size for crop-resistant stego embedding, in pixels.
    ///
    /// - `None` (default): tiling is disabled. Behavior matches the non-tiled
    ///   baseline, which survives common image transformations (resize,
    ///   recompression, format conversion) but is destroyed by cropping.
    /// - `Some(0)`: treated as disabled, same as `None`.
    /// - `Some(n)` with `n > 0`: each `n × n` pixel tile embeds a full copy of
    ///   the payload. The extractor scans candidate tile origins so the
    ///   payload is recoverable from any crop that contains at least one
    ///   intact tile. Valid range: 32..=1024. Smaller tiles fail ECC capacity
    ///   in non-MAC mode; larger tiles shrink the protected image's usable
    ///   embed region.
    ///
    /// Tiled mode multiplies total embed work by the tile count and is
    /// **opt-in** because the capacity and embedding-time costs are real.
    tile_size: Option<u32>,
    /// Maximum number of candidate tile origins the extractor will try before
    /// giving up. Bounds extraction time on very large images at the cost of
    /// potentially missing a successful tile when the crop is small or
    /// misaligned with the tile grid. Default 64.
    tile_extraction_max_origins: u32,
    /// Truncated content hash (4 bytes) for linking the protected image to its original.
    ///
    /// Derived from the ISCC content code or a truncated SHA-256 of the image pixels.
    /// Embedded in v2 payloads for provenance tracking. When not set, the hash is
    /// zeroed in the payload (v2 payloads without a content hash still carry the
    /// DMI value and flags fields).
    content_hash: Option<[u8; 4]>,
    /// Policy for updating metadata when re-processing an already-protected image.
    metadata_update_policy: Option<MetadataUpdatePolicy>,
    /// Override for auto-computed timestamps (notice_applied_at).
    ///
    /// When set, this value is used instead of `current_timestamp_iso8601()`.
    /// Intended for testing; not serialized.
    #[serde(skip)]
    timestamp_override: Option<String>,
    #[serde(skip)]
    config: Option<Arc<ProtectionConfig>>,
    #[serde(skip)]
    resource_limits: Option<crate::resource_limits::ResourceLimits>,
}

impl Serialize for ProtectionContext {
    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        use serde::ser::SerializeStruct;
        let mut fields = 17;
        if self.config.is_some() {
            fields += 1;
        }
        let mut s = serializer.serialize_struct("ProtectionContext", fields)?;
        s.serialize_field("intensity", &self.intensity)?;
        s.serialize_field("seed", &self.seed)?;
        s.serialize_field("input_format", &self.input_format)?;
        s.serialize_field("output_format", &self.output_format)?;
        s.serialize_field("protection_level", &self.protection_level)?;
        s.serialize_field("evidence_profile", &self.evidence_profile)?;
        s.serialize_field("dmi_value", &self.dmi_value)?;
        s.serialize_field("max_dimension", &self.max_dimension)?;
        s.serialize_field("inject_metadata", &self.inject_metadata)?;
        s.serialize_field("inject_legal_claims", &self.inject_legal_claims)?;
        s.serialize_field("stego_redundancy", &self.stego_redundancy)?;
        s.serialize_field("jpeg_quality", &self.jpeg_quality)?;
        s.serialize_field("progressive_jpeg", &self.progressive_jpeg)?;
        s.serialize_field("tile_size", &self.tile_size)?;
        s.serialize_field(
            "tile_extraction_max_origins",
            &self.tile_extraction_max_origins,
        )?;
        s.serialize_field("content_hash", &self.content_hash)?;
        s.serialize_field("metadata_update_policy", &self.metadata_update_policy)?;
        if self.config.is_some() {
            s.serialize_field(
                "_config_dropped_warning",
                "ProtectionContext.config is not serialized; MAC key and legal metadata will be lost on roundtrip. Set them again after deserialization.",
            )?;
        }
        s.end()
    }
}

/// The default seed is generated via `getrandom` (OS CSPRNG).
/// For reproducible protection, use `ProtectionContext::new(intensity, seed)`.
impl Default for ProtectionContext {
    fn default() -> Self {
        let seed = crate::util::seed::generate_random_seed();
        Self {
            intensity: 0.5,
            seed,
            input_format: None,
            output_format: None,
            protection_level: None,
            evidence_profile: None,
            dmi_value: None,
            max_dimension: None,
            inject_metadata: None,
            inject_legal_claims: None,
            stego_redundancy: None,
            jpeg_quality: 90,
            progressive_jpeg: false,
            tile_size: None,
            tile_extraction_max_origins: 64,
            content_hash: None,
            metadata_update_policy: None,
            timestamp_override: None,
            config: None,
            resource_limits: None,
        }
    }
}

impl ProtectionContext {
    /// Create a new ProtectionContext with the specified intensity and seed.
    ///
    /// Intensity is clamped to the range [0.0, 1.0].
    ///
    /// **Production use requires a MAC key.** Without one, steganographic payloads use
    /// a non-cryptographic CRC32 checksum that can be trivially forged. Call `.with_mac_key()`
    /// for adversarial or production deployments.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use stegoeggo::{ProtectionContext, ProtectionLevel, process_image};
    /// use image::DynamicImage;
    ///
    /// let img = DynamicImage::new_rgb8(64, 64);
    /// let ctx = ProtectionContext::new(0.5, 42);
    /// let protected = process_image(img, ProtectionLevel::Standard, &ctx).unwrap();
    /// ```
    pub fn new(intensity: f32, seed: u64) -> Self {
        Self {
            intensity: intensity.clamp(0.0, 1.0),
            seed,
            input_format: None,
            output_format: None,
            protection_level: None,
            evidence_profile: None,
            dmi_value: None,
            max_dimension: None,
            inject_metadata: None,
            inject_legal_claims: None,
            stego_redundancy: None,
            jpeg_quality: 90,
            progressive_jpeg: false,
            tile_size: None,
            tile_extraction_max_origins: 64,
            content_hash: None,
            metadata_update_policy: None,
            timestamp_override: None,
            config: None,
            resource_limits: None,
        }
    }

    /// Set the shared configuration (legal metadata, MAC key).
    #[must_use]
    pub fn with_config(mut self, config: Arc<ProtectionConfig>) -> Self {
        self.config = Some(config);
        self
    }

    /// Set the MAC key for cryptographic payload verification.
    /// Creates a `ProtectionConfig` internally.
    #[must_use]
    pub fn with_mac_key(mut self, key: Vec<u8>) -> Self {
        let config = self
            .config
            .get_or_insert_with(|| Arc::new(ProtectionConfig::new()));
        let mut builder = (**config).clone();
        builder.mac_key = Some(key);
        self.config = Some(Arc::new(builder));
        self
    }

    /// Set the legal metadata for this context.
    /// This should only be used for content you own.
    #[must_use]
    pub fn with_legal_metadata(mut self, metadata: LegalMetadata) -> Self {
        let config = self
            .config
            .get_or_insert_with(|| Arc::new(ProtectionConfig::new()));
        let mut builder = (**config).clone();
        builder.legal_metadata = Some(metadata);
        self.config = Some(Arc::new(builder));
        self
    }

    /// Access the MAC key, if set.
    #[must_use]
    pub fn mac_key(&self) -> Option<&[u8]> {
        self.config.as_ref().and_then(|c| c.mac_key.as_deref())
    }

    /// Access the legal metadata, if set.
    #[must_use]
    pub fn legal_metadata(&self) -> Option<&LegalMetadata> {
        self.config.as_ref().and_then(|c| c.legal_metadata.as_ref())
    }

    /// Set the maximum image dimension limit.
    #[must_use]
    pub fn with_max_dimension(mut self, max: u32) -> Self {
        self.max_dimension = Some(max);
        self
    }

    /// Set the output format for this context. When set, images will be encoded
    /// in this format. If not set, defaults to PNG or matches input format.
    #[must_use]
    pub fn with_format(mut self, format: ImageOutputFormat) -> Self {
        self.output_format = Some(format);
        self
    }

    /// Set the input format hint for this context.
    /// Usually auto-detected from magic bytes, so this is rarely needed.
    #[must_use]
    pub fn with_input_format(mut self, format: ImageOutputFormat) -> Self {
        self.input_format = Some(format);
        self
    }

    /// Set the DMI value for this context, returning a new context.
    #[deprecated(
        since = "0.4.0",
        note = "Use RightsPolicy in ProtectionRequest instead. See ProtectionRequest::new()."
    )]
    #[must_use]
    pub fn with_dmi(mut self, dmi: DmiValue) -> Self {
        self.dmi_value = Some(dmi);
        self
    }

    /// Set the evidence profile for this context.
    ///
    /// The evidence profile controls how protection warnings are interpreted
    /// and the default evidence posture. It does not directly change the
    /// processing pipeline — use [`ProtectionLevel`] for that.
    ///
    /// When not set, the profile defaults to [`EvidenceProfile::LegalNotice`]
    /// for warning interpretation purposes.
    #[allow(deprecated)]
    #[must_use]
    pub fn with_evidence_profile(mut self, profile: EvidenceProfile) -> Self {
        self.evidence_profile = Some(profile);
        self
    }

    /// Get the evidence profile.
    ///
    /// Returns the caller's explicit profile, if any. When `None`, the
    /// pipeline treats the context as [`EvidenceProfile::LegalNotice`] for
    /// warning interpretation.
    #[allow(deprecated)]
    #[must_use]
    pub fn evidence_profile(&self) -> EvidenceProfile {
        self.evidence_profile
            .unwrap_or(EvidenceProfile::LegalNotice)
    }

    /// Create a context pre-configured for legal notice (metadata only, no MAC required).
    #[allow(deprecated)]
    #[must_use]
    pub fn legal_notice() -> Self {
        Self::default().with_evidence_profile(EvidenceProfile::LegalNotice)
    }

    /// Create a context pre-configured for legal notice with steganographic markers.
    #[allow(deprecated)]
    #[must_use]
    pub fn legal_notice_with_stego() -> Self {
        Self::default().with_evidence_profile(EvidenceProfile::LegalNoticeWithStego)
    }

    /// Create a context pre-configured for authenticated provenance (MAC key expected).
    #[allow(deprecated)]
    #[must_use]
    pub fn authenticated_provenance() -> Self {
        Self::default().with_evidence_profile(EvidenceProfile::AuthenticatedProvenance)
    }

    /// Create a context pre-configured for maximal protection (all channels).
    #[allow(deprecated)]
    #[must_use]
    pub fn maximal() -> Self {
        Self::default().with_evidence_profile(EvidenceProfile::Maximal)
    }

    /// Override the level-based default for metadata injection.
    ///
    /// When `enable` is `true`, metadata (seed, DMI values) is injected
    /// regardless of protection level. When `enable` is `false`, metadata
    /// injection is suppressed even for levels that would normally inject it.
    ///
    /// If this method is **not** called, the default behavior depends on the
    /// protection level: metadata is injected for all levels except `Disabled`.
    /// This means `.with_metadata_injection(true)` on a `Standard` context is
    /// a no-op (metadata was already on), while `.with_metadata_injection(false)`
    /// suppresses it — a meaningful behavioral difference.
    #[deprecated(
        since = "0.4.0",
        note = "Use ProtectionChannels::metadata_only() or ProtectionRequest builder instead."
    )]
    #[must_use]
    pub fn with_metadata_injection(mut self, enable: bool) -> Self {
        self.inject_metadata = Some(enable);
        self
    }

    /// Override the default for legal claim injection.
    ///
    /// When `enable` is `true`, legal claims (copyright, artist) are injected
    /// into the image metadata. When `enable` is `false`, legal claim injection
    /// is disabled even if [`LegalMetadata`] is present.
    ///
    /// Legal claims require [`LegalMetadata`] to be set via
    /// [`with_legal_metadata`](ProtectionContext::with_legal_metadata).
    ///
    /// If this method is **not** called, legal claims are automatically
    /// enabled when [`LegalMetadata`] is present, and disabled otherwise.
    ///
    /// # Deprecated
    ///
    /// This method is deprecated. Legal claims are now automatically
    /// enabled when [`LegalMetadata`] is provided. Calling this method
    /// with `true` is redundant, and calling it with `false` while
    /// legal metadata is present produces a
    /// [`ContradictoryLegalClaims`](ProtectionWarning::ContradictoryLegalClaims)
    /// warning.
    ///
    /// # Warning
    ///
    /// Only enable for content you own. May create legal liability otherwise.
    #[must_use]
    #[deprecated(
        since = "0.2.2",
        note = "Legal claims are auto-enabled when LegalMetadata is present. \
                This method is redundant for the normal case and produces a \
                ContradictoryLegalClaims warning when used with `false` \
                while legal metadata is set."
    )]
    pub fn with_legal_claims(mut self, enable: bool) -> Self {
        self.inject_legal_claims = Some(enable);
        self
    }

    /// Set the intensity for this context, returning a new context.
    #[must_use]
    pub fn with_intensity(mut self, intensity: f32) -> Self {
        self.intensity = intensity.clamp(0.0, 1.0);
        self
    }

    /// Set the seed for this context, returning a new context.
    #[must_use]
    pub fn with_seed(mut self, seed: u64) -> Self {
        self.seed = seed;
        self
    }

    /// Set the stego embedding redundancy (1-10). Higher values are more robust
    /// for verification but slower. When not set, redundancy is derived from
    /// `intensity` via the internal `effective_redundancy()` helper.
    #[must_use]
    pub fn with_stego_redundancy(mut self, redundancy: usize) -> Self {
        self.stego_redundancy = Some(redundancy.clamp(1, 10));
        self
    }

    /// Set the JPEG encoding quality (1-100). Default is 90.
    #[must_use]
    pub fn with_jpeg_quality(mut self, quality: u8) -> Self {
        self.jpeg_quality = quality.clamp(1, 100);
        self
    }

    /// Enable progressive JPEG encoding. Progressive JPEGs render faster on
    /// slow connections as the image appears progressively. Default is false.
    #[must_use]
    pub fn with_progressive_jpeg(mut self, progressive: bool) -> Self {
        self.progressive_jpeg = progressive;
        self
    }

    /// Enable tiled stego embedding for crop resistance.
    ///
    /// Each `size × size` pixel tile embeds a full copy of the payload. The
    /// extractor scans candidate tile origins so the payload is recoverable
    /// from any crop that contains at least one intact tile.
    ///
    /// Pass `0` to disable tiling (same as never calling this method).
    /// Valid range for non-zero values: 32..=1024. Values outside that range
    /// are clamped. The most common choice is 64 (matches the LSB tile
    /// capacity for the default ECC payload).
    ///
    /// Tiled embedding multiplies total embed work by the tile count, so
    /// consider the capacity and embedding-time costs. For adversarial
    /// settings where cropping is a known attack vector, opt in via
    /// `with_tile_size(64)`.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use stegoeggo::{ProtectionContext, ProtectionLevel, process_image_bytes};
    ///
    /// let bytes: Vec<u8> = Vec::new();
    /// let ctx = ProtectionContext::new(0.7, 42).with_tile_size(64);
    /// let _protected = process_image_bytes(&bytes, ProtectionLevel::Standard, &ctx);
    /// ```
    #[must_use]
    pub fn with_tile_size(mut self, size: u32) -> Self {
        if size == 0 {
            self.tile_size = Some(0);
        } else {
            self.tile_size = Some(size.clamp(32, 1024));
        }
        self
    }

    /// Set the maximum number of candidate tile origins the extractor will
    /// try. Default is 64. Higher values increase extraction time but improve
    /// recovery from small or misaligned crops.
    #[must_use]
    pub fn with_tile_extraction_max_origins(mut self, n: u32) -> Self {
        self.tile_extraction_max_origins = n.clamp(1, 4096);
        self
    }

    /// Set a content hash for provenance tracking (v2 payloads).
    ///
    /// The 4-byte hash is embedded in v2 payload headers and can be used
    /// to link a protected image back to its original, even after metadata
    /// stripping. Typically derived from a truncated ISCC content code or
    /// SHA-256 of the image pixels.
    ///
    /// When not set, the hash is zeroed in the payload (v2 payloads without
    /// a content hash still carry the DMI value and flags fields).
    #[must_use]
    pub fn with_content_hash(mut self, hash: [u8; 4]) -> Self {
        self.content_hash = Some(hash);
        self
    }

    /// Set the metadata update policy for repeated image processing.
    ///
    /// Controls how the pipeline handles existing StegoEggo metadata when
    /// re-processing an already-protected image.
    #[must_use]
    pub fn with_metadata_update_policy(mut self, policy: MetadataUpdatePolicy) -> Self {
        self.metadata_update_policy = Some(policy);
        self
    }

    /// Get the metadata update policy.
    ///
    /// Returns the caller's explicit policy, if any. Defaults to
    /// [`MetadataUpdatePolicy::ReplaceStegoOwned`] when not set.
    #[must_use]
    pub fn metadata_update_policy(&self) -> MetadataUpdatePolicy {
        self.metadata_update_policy
            .unwrap_or(MetadataUpdatePolicy::ReplaceStegoOwned)
    }

    /// Override the auto-computed `notice_applied_at` timestamp.
    ///
    /// When set, this value replaces the wall-clock timestamp that would
    /// otherwise be auto-computed. Intended for testing to produce
    /// deterministic output. Not serialized.
    #[must_use]
    pub fn with_timestamp_override(mut self, ts: impl Into<String>) -> Self {
        self.timestamp_override = Some(ts.into());
        self
    }

    /// Set resource limits for parser hardening.
    ///
    /// Limits are applied to externally reachable parsers (PNG chunk walker,
    /// JPEG segment parser, WebP RIFF parser, XMP extraction, stego extraction)
    /// to prevent resource exhaustion from malformed or adversarial inputs.
    ///
    /// When not set, the library uses conservative defaults suitable for
    /// web-facing services. Explicit limits override all defaults.
    #[must_use]
    pub fn with_resource_limits(mut self, limits: crate::resource_limits::ResourceLimits) -> Self {
        self.resource_limits = Some(limits);
        self
    }

    /// Get the resource limits.
    ///
    /// Returns caller-specified limits, or conservative defaults.
    #[must_use]
    pub fn resource_limits(&self) -> crate::resource_limits::ResourceLimits {
        self.resource_limits.clone().unwrap_or_default()
    }

    /// Get the intensity value.
    #[must_use]
    pub fn intensity(&self) -> f32 {
        self.intensity
    }

    /// Get the seed value.
    #[must_use]
    pub fn seed(&self) -> u64 {
        self.seed
    }

    /// Get the input format hint.
    #[must_use]
    pub fn input_format(&self) -> Option<ImageOutputFormat> {
        self.input_format
    }

    /// Get the output format.
    #[must_use]
    pub fn output_format(&self) -> Option<ImageOutputFormat> {
        self.output_format
    }

    /// Get the protection level.
    #[must_use]
    pub fn protection_level(&self) -> Option<ProtectionLevel> {
        self.protection_level
    }

    /// Get the DMI value.
    #[must_use]
    pub fn dmi_value(&self) -> Option<DmiValue> {
        self.dmi_value
    }

    /// Get the maximum dimension limit.
    #[must_use]
    pub fn max_dimension(&self) -> Option<u32> {
        self.max_dimension
    }

    /// Get whether metadata injection is enabled.
    ///
    /// Returns the caller's explicit override, if any. `None` means the
    /// pipeline will apply the level-based default (inject unless `Disabled`).
    /// The pipeline resolves this by calling
    /// `inject_metadata.unwrap_or(!matches!(level, Disabled))`.
    #[must_use]
    pub fn inject_metadata(&self) -> Option<bool> {
        self.inject_metadata
    }

    /// Get whether legal claim injection is explicitly overridden.
    ///
    /// Returns the caller's explicit override, if any. `None` means the
    /// pipeline will auto-enable legal claims when [`LegalMetadata`] is
    /// present and disable them otherwise.
    #[must_use]
    pub fn inject_legal_claims(&self) -> Option<bool> {
        self.inject_legal_claims
    }

    /// Get the effective stego redundancy.
    ///
    /// When the user has explicitly set `stego_redundancy` via
    /// `with_stego_redundancy()`, that value is returned. Otherwise,
    /// the redundancy is derived from the current `intensity`:
    /// - `intensity < 0.3` → 1 (minimal embedding)
    /// - `intensity < 0.7` → 2 (standard)
    /// - `intensity >= 0.7` → 3 (heavy)
    #[must_use]
    pub fn stego_redundancy(&self) -> usize {
        self.effective_redundancy()
    }

    pub(crate) fn effective_redundancy(&self) -> usize {
        if let Some(r) = self.stego_redundancy {
            return r;
        }
        let i = self.intensity;
        if i < 0.3 {
            1
        } else if i < 0.7 {
            2
        } else {
            3
        }
    }

    /// Get the JPEG encoding quality.
    #[must_use]
    pub fn jpeg_quality(&self) -> u8 {
        self.jpeg_quality
    }

    /// Get whether progressive JPEG encoding is enabled.
    #[must_use]
    pub fn progressive_jpeg(&self) -> bool {
        self.progressive_jpeg
    }

    /// Get the tile size for crop-resistant stego embedding.
    ///
    /// Returns the configured value if set, otherwise `None`. Note that
    /// `Some(0)` and `None` both indicate that tiling is disabled — callers
    /// that need a single on/off decision should use
    /// [`is_tile_mode_enabled`](Self::is_tile_mode_enabled) instead.
    #[must_use]
    pub fn tile_size(&self) -> Option<u32> {
        self.tile_size
    }

    /// Returns `true` when tiled embedding is active.
    ///
    /// Treats both `Some(0)` and `None` as "tiling disabled" so callers
    /// don't need to special-case the sentinel.
    #[must_use]
    pub fn is_tile_mode_enabled(&self) -> bool {
        matches!(self.tile_size, Some(n) if n > 0)
    }

    /// Get the maximum number of candidate tile origins the extractor will
    /// try. Always at least 1.
    #[must_use]
    pub fn tile_extraction_max_origins(&self) -> u32 {
        self.tile_extraction_max_origins.max(1)
    }

    /// Get the content hash, if set.
    #[must_use]
    pub fn content_hash(&self) -> Option<[u8; 4]> {
        self.content_hash
    }

    /// Set the input format hint (non-consuming).
    pub fn set_input_format(&mut self, format: ImageOutputFormat) {
        self.input_format = Some(format);
    }

    /// Set the tile size (non-consuming, crate-internal).
    pub(crate) fn set_tile_size(&mut self, size: u32) {
        if size == 0 {
            self.tile_size = Some(0);
        } else {
            self.tile_size = Some(size.clamp(32, 1024));
        }
    }

    /// Set the protection level (non-consuming, crate-internal).
    pub(crate) fn set_protection_level(&mut self, level: ProtectionLevel) {
        self.protection_level = Some(level);
    }

    /// Normalize legal metadata and context into a format-independent [`RightsNotice`].
    ///
    /// This is called once per processing invocation. All format writers
    /// (PNG tEXt, JPEG COM, WebP XMP) consume the same `RightsNotice`,
    /// ensuring semantically equivalent metadata regardless of output format.
    ///
    /// The normalization resolves DMI defaults, applies auto-computed timestamps,
    /// and merges `LegalMetadata` fields with context-level overrides.
    #[must_use]
    pub fn normalize_rights_notice(&self) -> RightsNotice {
        let legal = self.legal_metadata();
        let dmi = self
            .dmi_value()
            .or_else(|| {
                self.protection_level().and_then(|level| match level {
                    ProtectionLevel::Light => Some(DmiValue::Prohibited),
                    ProtectionLevel::Standard => Some(DmiValue::ProhibitedAiMlTraining),
                    _ => None,
                })
            })
            .filter(|v| *v != DmiValue::Unspecified);

        let notice_applied_at =
            legal
                .and_then(|l| l.notice_applied_at().map(String::from))
                .or_else(|| {
                    if legal.is_some() {
                        Some(self.timestamp_override.clone().unwrap_or_else(
                            crate::protected::metadata_trap::current_timestamp_iso8601,
                        ))
                    } else {
                        None
                    }
                });

        RightsNotice {
            copyright_holder: legal.and_then(|l| l.copyright_holder().map(String::from)),
            contact_email: legal.and_then(|l| l.contact_email().map(String::from)),
            license_url: legal.and_then(|l| l.license_url().map(String::from)),
            usage_terms: legal.and_then(|l| l.usage_terms().map(String::from)),
            usage_terms_lang: legal.and_then(|l| l.usage_terms_lang().map(String::from)),
            creation_date: legal.and_then(|l| l.creation_date().map(String::from)),
            ai_constraints: legal.and_then(|l| l.ai_constraints().map(String::from)),
            web_statement_of_rights: legal
                .and_then(|l| l.web_statement_of_rights().map(String::from)),
            creator: legal.and_then(|l| l.creator().map(String::from)),
            credit_line: legal.and_then(|l| l.credit_line().map(String::from)),
            copyright_owner: legal.and_then(|l| l.copyright_owner().map(String::from)),
            licensor_name: legal.and_then(|l| l.licensor_name().map(String::from)),
            licensor_email: legal.and_then(|l| l.licensor_email().map(String::from)),
            licensor_url: legal.and_then(|l| l.licensor_url().map(String::from)),
            metadata_date: legal.and_then(|l| l.metadata_date().map(String::from)),
            notice_applied_at,
            dmi,
            seed: Some(self.seed()),
        }
    }
}

/// Detailed result of image protection verification.
///
/// Returned by [`verify_image_bytes_detailed`](crate::verify_image_bytes_detailed).
/// Provides richer information than the `Option<bool>` return of
/// [`verify_image_bytes`](crate::verify_image_bytes).
#[derive(Debug, Clone)]
pub enum VerificationResult {
    /// Protection data found and integrity check passed.
    ///
    /// Contains the extracted [`StegoPayload`](crate::StegoPayload) with
    /// protection metadata (seed, intensity, version, content hash, DMI value).
    Verified {
        /// The extracted payload from the protected image.
        payload: crate::StegoPayload,
    },
    /// Protection data found but integrity check failed.
    ///
    /// The payload was extracted but either the CRC32 checksum is invalid
    /// (non-MAC mode) or the HMAC-SHA256 verification failed (MAC mode).
    /// This may indicate corruption, wrong MAC key, or tampering.
    Corrupted {
        /// The partially extracted payload (may contain valid metadata).
        payload: crate::StegoPayload,
    },
    /// Metadata markers were found, but no steganographic payload could be
    /// integrity-verified.
    ///
    /// This is useful evidence that the image passed through the protection
    /// pipeline, but it is weaker than [`Verified`](Self::Verified). Metadata
    /// can be stripped, copied, or forged more easily than a MAC-verified
    /// steganographic payload.
    MetadataOnly {
        /// Protection seed recovered from metadata.
        seed: u64,
    },
    /// No protection data found in the image.
    ///
    /// The extraction chain exhausted all seed sources (metadata, LSB fallback,
    /// tiled extraction) without finding a valid payload.
    NotFound,
}

impl VerificationResult {
    /// Returns `true` if verification succeeded.
    #[must_use]
    pub fn is_verified(&self) -> bool {
        matches!(self, VerificationResult::Verified { .. })
    }

    /// Returns `true` if protection data was found (whether valid or corrupted).
    #[must_use]
    pub fn is_found(&self) -> bool {
        !matches!(self, VerificationResult::NotFound)
    }

    /// Returns the payload if verification succeeded.
    #[must_use]
    pub fn payload(&self) -> Option<&crate::StegoPayload> {
        match self {
            VerificationResult::Verified { payload } => Some(payload),
            _ => None,
        }
    }

    /// Returns the metadata seed when the result is metadata-only evidence.
    #[must_use]
    pub fn metadata_seed(&self) -> Option<u64> {
        match self {
            VerificationResult::MetadataOnly { seed } => Some(*seed),
            _ => None,
        }
    }
}

/// Simple verification status for quick checks.
///
/// Returned by [`verify_image_bytes`](crate::verify_image_bytes) and
/// [`SteganographyProtector::verify_payload_with_key`](crate::SteganographyProtector::verify_payload_with_key).
/// For richer information, use [`VerificationResult`] via
/// [`verify_image_bytes_detailed`](crate::verify_image_bytes_detailed).
///
/// # Examples
///
/// ```no_run
/// use stegoeggo::VerificationStatus;
///
/// let img_bytes: Vec<u8> = std::fs::read("protected.png").unwrap();
/// match stegoeggo::verify_image_bytes(&img_bytes, b"key") {
///     VerificationStatus::Verified => println!("Protected and verified"),
///     VerificationStatus::Invalid => println!("Protected but verification failed"),
///     VerificationStatus::NotFound => println!("No protection found"),
/// }
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum VerificationStatus {
    /// Protection data found and integrity check passed.
    Verified,
    /// Protection data found but integrity check failed.
    ///
    /// The payload was extracted but either the CRC32 checksum is invalid
    /// (non-MAC mode) or the HMAC-SHA256 verification failed (MAC mode).
    /// This may indicate corruption, wrong MAC key, or tampering.
    Invalid,
    /// No protection data found in the image.
    NotFound,
}

impl std::fmt::Display for VerificationStatus {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            VerificationStatus::Verified => write!(f, "Verified"),
            VerificationStatus::Invalid => write!(f, "Invalid"),
            VerificationStatus::NotFound => write!(f, "NotFound"),
        }
    }
}

impl From<Option<bool>> for VerificationStatus {
    fn from(val: Option<bool>) -> Self {
        match val {
            Some(true) => VerificationStatus::Verified,
            Some(false) => VerificationStatus::Invalid,
            None => VerificationStatus::NotFound,
        }
    }
}

impl From<VerificationStatus> for Option<bool> {
    fn from(val: VerificationStatus) -> Self {
        match val {
            VerificationStatus::Verified => Some(true),
            VerificationStatus::Invalid => Some(false),
            VerificationStatus::NotFound => None,
        }
    }
}

/// Strength of legal-notice evidence found in an image.
///
/// Evidence strength increases as more independent verification channels agree.
/// This enum is oriented toward legal deterrence, not cryptographic security.
///
/// # Interpretation
///
/// - [`NoNoticeFound`](Self::NoNoticeFound): No rights-reservation metadata detected.
/// - [`MetadataNoticeOnly`](Self::MetadataNoticeOnly): Legal-notice fields found in
///   metadata but no verified steganographic payload.
/// - [`MetadataNoticeAndBestEffortStego`](Self::MetadataNoticeAndBestEffortStego):
///   Legal-notice metadata plus a steganographic payload verified without
///   cryptographic authentication (CRC32 or unmatched MAC).
/// - [`MetadataNoticeAndAuthenticatedProvenance`](Self::MetadataNoticeAndAuthenticatedProvenance):
///   Legal-notice metadata plus a steganographic payload verified with
///   HMAC-SHA256 using the caller's MAC key.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
#[non_exhaustive]
pub enum EvidenceStrength {
    /// No rights-reservation metadata found in the image.
    NoNoticeFound,
    /// Legal-notice metadata found but no verified steganographic payload.
    MetadataNoticeOnly,
    /// Legal-notice metadata plus a non-authenticated steganographic payload.
    MetadataNoticeAndBestEffortStego,
    /// Legal-notice metadata plus a MAC-authenticated steganographic payload.
    MetadataNoticeAndAuthenticatedProvenance,
}

impl std::fmt::Display for EvidenceStrength {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            EvidenceStrength::NoNoticeFound => write!(f, "NoNoticeFound"),
            EvidenceStrength::MetadataNoticeOnly => write!(f, "MetadataNoticeOnly"),
            EvidenceStrength::MetadataNoticeAndBestEffortStego => {
                write!(f, "MetadataNoticeAndBestEffortStego")
            }
            EvidenceStrength::MetadataNoticeAndAuthenticatedProvenance => {
                write!(f, "MetadataNoticeAndAuthenticatedProvenance")
            }
        }
    }
}

/// A channel through which legal-notice or steganographic evidence was detected.
///
/// Each variant corresponds to a specific metadata location or steganographic
/// technique used by the protection pipeline.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
#[non_exhaustive]
pub enum EvidenceChannel {
    /// PNG tEXt/iTXt text chunk containing a key-value pair.
    PngText,
    /// PNG iTXt chunk containing XMP metadata.
    PngXmp,
    /// JPEG COM (comment) marker.
    JpegComment,
    /// JPEG APP1 marker containing XMP metadata.
    JpegXmp,
    /// JPEG APP13 marker containing IPTC-IIM data.
    JpegIptc,
    /// WebP RIFF chunk containing XMP metadata.
    WebPXmp,
    /// WebP RIFF chunk containing EXIF data.
    WebPExif,
    /// LSB steganographic payload embedded in pixel data.
    LsbPayload,
    /// F5-style DCT steganographic payload embedded in JPEG coefficients.
    DctPayload,
    /// Seed stored in JPEG quantization table LSBs.
    /// Reserved for future use — currently not emitted by `verify_legal_notice()`.
    QTableSeed,
}

impl std::fmt::Display for EvidenceChannel {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            EvidenceChannel::PngText => write!(f, "PngText"),
            EvidenceChannel::PngXmp => write!(f, "PngXmp"),
            EvidenceChannel::JpegComment => write!(f, "JpegComment"),
            EvidenceChannel::JpegXmp => write!(f, "JpegXmp"),
            EvidenceChannel::JpegIptc => write!(f, "JpegIptc"),
            EvidenceChannel::WebPXmp => write!(f, "WebPXmp"),
            EvidenceChannel::WebPExif => write!(f, "WebPExif"),
            EvidenceChannel::LsbPayload => write!(f, "LsbPayload"),
            EvidenceChannel::DctPayload => write!(f, "DctPayload"),
            EvidenceChannel::QTableSeed => write!(f, "QTableSeed"),
        }
    }
}

/// Classification of the source and conformance of an extracted rights signal.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum RightsSignalKind {
    /// Canonical `plus:DataMining` property with a recognized PLUS vocabulary key.
    CanonicalPlusDataMining,
    /// Legacy StegoEggo `Iptc4xmpExt:DMI-*` property (v0.2 era).
    LegacyStegoEggoDmi,
    /// Legacy `tdm:reserve_tdm` property.
    LegacyTdmReservation,
    /// Unknown property or unrecognized value.
    Unknown,
}

impl std::fmt::Display for RightsSignalKind {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            RightsSignalKind::CanonicalPlusDataMining => write!(f, "CanonicalPlusDataMining"),
            RightsSignalKind::LegacyStegoEggoDmi => write!(f, "LegacyStegoEggoDmi"),
            RightsSignalKind::LegacyTdmReservation => write!(f, "LegacyTdmReservation"),
            RightsSignalKind::Unknown => write!(f, "Unknown"),
        }
    }
}

/// Legal-notice verification report for a protected image.
///
/// This struct reports the legal-notice metadata and steganographic status
/// of an image, enabling callers to present a structured evidence report
/// without interpreting legal conclusions.
///
/// # Fields
///
/// All metadata fields are `Option<String>`: `None` means the field was not
/// found in the image. An empty string means the field was found but empty.
///
/// # Examples
///
/// ```no_run
/// let img_bytes = std::fs::read("protected.png").unwrap();
/// let report = stegoeggo::verify_legal_notice(&img_bytes, b"my-mac-key");
/// println!("Evidence strength: {}", report.evidence_strength());
/// ```
#[derive(Debug, Clone)]
pub struct NoticeVerification {
    /// Copyright holder extracted from the image metadata.
    copyright_holder: Option<String>,
    /// Creator name extracted from the image metadata.
    creator: Option<String>,
    /// Contact email extracted from the image metadata.
    contact: Option<String>,
    /// Rights URL or web statement of rights extracted from the image metadata.
    rights_url: Option<String>,
    /// Usage terms extracted from the image metadata.
    usage_terms: Option<String>,
    /// AI training constraints extracted from the image metadata.
    ai_constraints: Option<String>,
    /// DMI (Data Mining) restriction value extracted from the image metadata.
    dmi: Option<DmiValue>,
    /// Whether TDM reservation was found in XMP metadata.
    tdm_reserved: Option<bool>,
    /// Classification of the rights signal source.
    rights_signal_kind: RightsSignalKind,
    /// DMI value from canonical `plus:DataMining` property.
    canonical_dmi: Option<DmiValue>,
    /// DMI value from legacy `Iptc4xmpExt:DMI-*` property.
    legacy_dmi: Option<DmiValue>,
    /// Protection seed extracted from metadata or steganographic payload.
    protection_seed: Option<u64>,
    /// Steganographic payload verification status.
    stego_status: VerificationStatus,
    /// The extracted steganographic payload, if verified.
    stego_payload: Option<crate::StegoPayload>,
    /// Whether the steganographic payload was authenticated via HMAC.
    authenticated: bool,
    /// Overall evidence strength combining metadata and stego channels.
    evidence_strength: EvidenceStrength,
    /// Evidence channels through which data was detected.
    channels: Vec<EvidenceChannel>,
    /// License URL extracted from the image metadata.
    license_url: Option<String>,
    /// Web statement of rights URL extracted from the image metadata.
    web_statement_of_rights: Option<String>,
    /// Credit line extracted from the image metadata.
    credit_line: Option<String>,
    /// Copyright owner extracted from the image metadata.
    copyright_owner: Option<String>,
    /// Licensor name extracted from the image metadata.
    licensor_name: Option<String>,
    /// Licensor email extracted from the image metadata.
    licensor_email: Option<String>,
    /// Licensor URL extracted from the image metadata.
    licensor_url: Option<String>,
    /// Metadata date extracted from the image metadata.
    metadata_date: Option<String>,
    /// Notice-applied-at timestamp extracted from the image metadata.
    notice_applied_at: Option<String>,
}

impl NoticeVerification {
    /// Returns the copyright holder, if found.
    #[must_use]
    pub fn copyright_holder(&self) -> Option<&str> {
        self.copyright_holder.as_deref()
    }

    /// Returns the creator name, if found.
    #[must_use]
    pub fn creator(&self) -> Option<&str> {
        self.creator.as_deref()
    }

    /// Returns the contact email, if found.
    #[must_use]
    pub fn contact(&self) -> Option<&str> {
        self.contact.as_deref()
    }

    /// Returns the rights URL, if found.
    #[must_use]
    pub fn rights_url(&self) -> Option<&str> {
        self.rights_url
            .as_deref()
            .or(self.web_statement_of_rights.as_deref())
            .or(self.license_url.as_deref())
    }

    /// Returns the usage terms, if found.
    #[must_use]
    pub fn usage_terms(&self) -> Option<&str> {
        self.usage_terms.as_deref()
    }

    /// Returns the AI training constraints, if found.
    #[must_use]
    pub fn ai_constraints(&self) -> Option<&str> {
        self.ai_constraints.as_deref()
    }

    /// Returns the DMI restriction value, if found.
    #[must_use]
    pub fn dmi(&self) -> Option<DmiValue> {
        self.dmi
    }

    /// Returns whether TDM reservation was found.
    #[must_use]
    pub fn tdm_reserved(&self) -> Option<bool> {
        self.tdm_reserved
    }

    /// Returns the classification of the rights signal source.
    #[must_use]
    pub fn rights_signal_kind(&self) -> RightsSignalKind {
        self.rights_signal_kind
    }

    /// Returns the DMI value from canonical `plus:DataMining`, if found.
    #[must_use]
    pub fn canonical_dmi(&self) -> Option<DmiValue> {
        self.canonical_dmi
    }

    /// Returns the DMI value from legacy `Iptc4xmpExt:DMI-*`, if found.
    #[must_use]
    pub fn legacy_dmi(&self) -> Option<DmiValue> {
        self.legacy_dmi
    }

    /// Returns true if canonical and legacy DMI values were both found and disagree.
    #[must_use]
    pub fn has_dmi_conflict(&self) -> bool {
        if let (Some(canonical), Some(legacy)) = (self.canonical_dmi, self.legacy_dmi) {
            canonical != legacy
        } else {
            false
        }
    }

    /// Returns the protection seed, if found.
    #[must_use]
    pub fn protection_seed(&self) -> Option<u64> {
        self.protection_seed
    }

    /// Returns the steganographic verification status.
    #[must_use]
    pub fn stego_status(&self) -> VerificationStatus {
        self.stego_status
    }

    /// Returns the extracted steganographic payload, if verified.
    #[must_use]
    pub fn stego_payload(&self) -> Option<&crate::StegoPayload> {
        self.stego_payload.as_ref()
    }

    /// Returns whether the steganographic payload was authenticated.
    #[must_use]
    pub fn authenticated(&self) -> bool {
        self.authenticated
    }

    /// Returns the evidence strength.
    #[must_use]
    pub fn evidence_strength(&self) -> EvidenceStrength {
        self.evidence_strength
    }

    /// Returns the evidence channels detected.
    #[must_use]
    pub fn channels(&self) -> &[EvidenceChannel] {
        &self.channels
    }

    /// Returns the license URL, if found.
    #[must_use]
    pub fn license_url(&self) -> Option<&str> {
        self.license_url.as_deref()
    }

    /// Returns the web statement of rights URL, if found.
    #[must_use]
    pub fn web_statement_of_rights(&self) -> Option<&str> {
        self.web_statement_of_rights.as_deref()
    }

    /// Returns the credit line, if found.
    #[must_use]
    pub fn credit_line(&self) -> Option<&str> {
        self.credit_line.as_deref()
    }

    /// Returns the copyright owner, if found.
    #[must_use]
    pub fn copyright_owner(&self) -> Option<&str> {
        self.copyright_owner.as_deref()
    }

    /// Returns the licensor name, if found.
    #[must_use]
    pub fn licensor_name(&self) -> Option<&str> {
        self.licensor_name.as_deref()
    }

    /// Returns the licensor email, if found.
    #[must_use]
    pub fn licensor_email(&self) -> Option<&str> {
        self.licensor_email.as_deref()
    }

    /// Returns the licensor URL, if found.
    #[must_use]
    pub fn licensor_url(&self) -> Option<&str> {
        self.licensor_url.as_deref()
    }

    /// Returns the metadata date, if found.
    #[must_use]
    pub fn metadata_date(&self) -> Option<&str> {
        self.metadata_date.as_deref()
    }

    /// Returns the notice-applied-at timestamp, if found.
    #[must_use]
    pub fn notice_applied_at(&self) -> Option<&str> {
        self.notice_applied_at.as_deref()
    }

    /// Returns `true` if any legal-notice metadata was found.
    #[must_use]
    pub fn has_notice(&self) -> bool {
        self.copyright_holder.is_some()
            || self.creator.is_some()
            || self.contact.is_some()
            || self.rights_url.is_some()
            || self.usage_terms.is_some()
            || self.ai_constraints.is_some()
            || self.dmi.is_some()
            || self.license_url.is_some()
            || self.web_statement_of_rights.is_some()
            || self.credit_line.is_some()
            || self.copyright_owner.is_some()
            || self.licensor_name.is_some()
            || self.licensor_email.is_some()
            || self.licensor_url.is_some()
            || self.metadata_date.is_some()
            || self.notice_applied_at.is_some()
    }

    #[deprecated(since = "0.2.2", note = "use NoticeVerificationBuilder instead")]
    #[allow(clippy::too_many_arguments, dead_code)]
    pub(crate) fn new(
        copyright_holder: Option<String>,
        creator: Option<String>,
        contact: Option<String>,
        rights_url: Option<String>,
        usage_terms: Option<String>,
        ai_constraints: Option<String>,
        dmi: Option<DmiValue>,
        tdm_reserved: Option<bool>,
        rights_signal_kind: RightsSignalKind,
        canonical_dmi: Option<DmiValue>,
        legacy_dmi: Option<DmiValue>,
        protection_seed: Option<u64>,
        stego_status: VerificationStatus,
        stego_payload: Option<crate::StegoPayload>,
        authenticated: bool,
        evidence_strength: EvidenceStrength,
        channels: Vec<EvidenceChannel>,
        license_url: Option<String>,
        web_statement_of_rights: Option<String>,
        credit_line: Option<String>,
        copyright_owner: Option<String>,
        licensor_name: Option<String>,
        licensor_email: Option<String>,
        licensor_url: Option<String>,
        metadata_date: Option<String>,
        notice_applied_at: Option<String>,
    ) -> Self {
        Self {
            copyright_holder,
            creator,
            contact,
            rights_url,
            usage_terms,
            ai_constraints,
            dmi,
            tdm_reserved,
            rights_signal_kind,
            canonical_dmi,
            legacy_dmi,
            protection_seed,
            stego_status,
            stego_payload,
            authenticated,
            evidence_strength,
            channels,
            license_url,
            web_statement_of_rights,
            credit_line,
            copyright_owner,
            licensor_name,
            licensor_email,
            licensor_url,
            metadata_date,
            notice_applied_at,
        }
    }

    /// Creates a new [`NoticeVerificationBuilder`] with default values.
    #[must_use]
    pub fn builder() -> NoticeVerificationBuilder {
        NoticeVerificationBuilder::default()
    }
}

/// Builder for [`NoticeVerification`].
///
/// Construct via [`NoticeVerification::builder()`], chain setter methods, then
/// call [`build()`](NoticeVerificationBuilder::build).
#[derive(Debug, Clone)]
pub struct NoticeVerificationBuilder {
    copyright_holder: Option<String>,
    creator: Option<String>,
    contact: Option<String>,
    rights_url: Option<String>,
    usage_terms: Option<String>,
    ai_constraints: Option<String>,
    dmi: Option<DmiValue>,
    tdm_reserved: Option<bool>,
    rights_signal_kind: RightsSignalKind,
    canonical_dmi: Option<DmiValue>,
    legacy_dmi: Option<DmiValue>,
    protection_seed: Option<u64>,
    stego_status: VerificationStatus,
    stego_payload: Option<crate::StegoPayload>,
    authenticated: bool,
    evidence_strength: EvidenceStrength,
    channels: Vec<EvidenceChannel>,
    license_url: Option<String>,
    web_statement_of_rights: Option<String>,
    credit_line: Option<String>,
    copyright_owner: Option<String>,
    licensor_name: Option<String>,
    licensor_email: Option<String>,
    licensor_url: Option<String>,
    metadata_date: Option<String>,
    notice_applied_at: Option<String>,
}

impl Default for NoticeVerificationBuilder {
    fn default() -> Self {
        Self {
            copyright_holder: None,
            creator: None,
            contact: None,
            rights_url: None,
            usage_terms: None,
            ai_constraints: None,
            dmi: None,
            tdm_reserved: None,
            rights_signal_kind: RightsSignalKind::Unknown,
            canonical_dmi: None,
            legacy_dmi: None,
            protection_seed: None,
            stego_status: VerificationStatus::NotFound,
            stego_payload: None,
            authenticated: false,
            evidence_strength: EvidenceStrength::NoNoticeFound,
            channels: Vec::new(),
            license_url: None,
            web_statement_of_rights: None,
            credit_line: None,
            copyright_owner: None,
            licensor_name: None,
            licensor_email: None,
            licensor_url: None,
            metadata_date: None,
            notice_applied_at: None,
        }
    }
}

impl NoticeVerificationBuilder {
    /// Sets the copyright holder.
    #[must_use]
    pub fn copyright_holder(mut self, v: Option<String>) -> Self {
        self.copyright_holder = v;
        self
    }

    /// Sets the creator name.
    #[must_use]
    pub fn creator(mut self, v: Option<String>) -> Self {
        self.creator = v;
        self
    }

    /// Sets the contact email.
    #[must_use]
    pub fn contact(mut self, v: Option<String>) -> Self {
        self.contact = v;
        self
    }

    /// Sets the rights URL.
    #[must_use]
    pub fn rights_url(mut self, v: Option<String>) -> Self {
        self.rights_url = v;
        self
    }

    /// Sets the usage terms.
    #[must_use]
    pub fn usage_terms(mut self, v: Option<String>) -> Self {
        self.usage_terms = v;
        self
    }

    /// Sets the AI training constraints.
    #[must_use]
    pub fn ai_constraints(mut self, v: Option<String>) -> Self {
        self.ai_constraints = v;
        self
    }

    /// Sets the DMI restriction value.
    #[must_use]
    pub fn dmi(mut self, v: Option<DmiValue>) -> Self {
        self.dmi = v;
        self
    }

    /// Sets the TDM reservation flag.
    #[must_use]
    pub fn tdm_reserved(mut self, v: Option<bool>) -> Self {
        self.tdm_reserved = v;
        self
    }

    /// Sets the rights signal kind.
    #[must_use]
    pub fn rights_signal_kind(mut self, v: RightsSignalKind) -> Self {
        self.rights_signal_kind = v;
        self
    }

    /// Sets the canonical DMI value.
    #[must_use]
    pub fn canonical_dmi(mut self, v: Option<DmiValue>) -> Self {
        self.canonical_dmi = v;
        self
    }

    /// Sets the legacy DMI value.
    #[must_use]
    pub fn legacy_dmi(mut self, v: Option<DmiValue>) -> Self {
        self.legacy_dmi = v;
        self
    }

    /// Sets the protection seed.
    #[must_use]
    pub fn protection_seed(mut self, v: Option<u64>) -> Self {
        self.protection_seed = v;
        self
    }

    /// Sets the steganographic verification status.
    #[must_use]
    pub fn stego_status(mut self, v: VerificationStatus) -> Self {
        self.stego_status = v;
        self
    }

    /// Sets the extracted steganographic payload.
    #[must_use]
    pub fn stego_payload(mut self, v: Option<crate::StegoPayload>) -> Self {
        self.stego_payload = v;
        self
    }

    /// Sets whether the payload was authenticated via HMAC.
    #[must_use]
    pub fn authenticated(mut self, v: bool) -> Self {
        self.authenticated = v;
        self
    }

    /// Sets the overall evidence strength.
    #[must_use]
    pub fn evidence_strength(mut self, v: EvidenceStrength) -> Self {
        self.evidence_strength = v;
        self
    }

    /// Sets the evidence channels.
    #[must_use]
    pub fn channels(mut self, v: Vec<EvidenceChannel>) -> Self {
        self.channels = v;
        self
    }

    /// Sets the license URL.
    #[must_use]
    pub fn license_url(mut self, v: Option<String>) -> Self {
        self.license_url = v;
        self
    }

    /// Sets the web statement of rights URL.
    #[must_use]
    pub fn web_statement_of_rights(mut self, v: Option<String>) -> Self {
        self.web_statement_of_rights = v;
        self
    }

    /// Sets the credit line.
    #[must_use]
    pub fn credit_line(mut self, v: Option<String>) -> Self {
        self.credit_line = v;
        self
    }

    /// Sets the copyright owner.
    #[must_use]
    pub fn copyright_owner(mut self, v: Option<String>) -> Self {
        self.copyright_owner = v;
        self
    }

    /// Sets the licensor name.
    #[must_use]
    pub fn licensor_name(mut self, v: Option<String>) -> Self {
        self.licensor_name = v;
        self
    }

    /// Sets the licensor email.
    #[must_use]
    pub fn licensor_email(mut self, v: Option<String>) -> Self {
        self.licensor_email = v;
        self
    }

    /// Sets the licensor URL.
    #[must_use]
    pub fn licensor_url(mut self, v: Option<String>) -> Self {
        self.licensor_url = v;
        self
    }

    /// Sets the metadata date.
    #[must_use]
    pub fn metadata_date(mut self, v: Option<String>) -> Self {
        self.metadata_date = v;
        self
    }

    /// Sets the notice-applied-at timestamp.
    #[must_use]
    pub fn notice_applied_at(mut self, v: Option<String>) -> Self {
        self.notice_applied_at = v;
        self
    }

    /// Builds the [`NoticeVerification`] from the accumulated fields.
    #[must_use]
    pub fn build(self) -> NoticeVerification {
        NoticeVerification {
            copyright_holder: self.copyright_holder,
            creator: self.creator,
            contact: self.contact,
            rights_url: self.rights_url,
            usage_terms: self.usage_terms,
            ai_constraints: self.ai_constraints,
            dmi: self.dmi,
            tdm_reserved: self.tdm_reserved,
            rights_signal_kind: self.rights_signal_kind,
            canonical_dmi: self.canonical_dmi,
            legacy_dmi: self.legacy_dmi,
            protection_seed: self.protection_seed,
            stego_status: self.stego_status,
            stego_payload: self.stego_payload,
            authenticated: self.authenticated,
            evidence_strength: self.evidence_strength,
            channels: self.channels,
            license_url: self.license_url,
            web_statement_of_rights: self.web_statement_of_rights,
            credit_line: self.credit_line,
            copyright_owner: self.copyright_owner,
            licensor_name: self.licensor_name,
            licensor_email: self.licensor_email,
            licensor_url: self.licensor_url,
            metadata_date: self.metadata_date,
            notice_applied_at: self.notice_applied_at,
        }
    }
}

/// Warning about degraded protection during image processing.
///
/// Returned by [`process_image_bytes_with_info`](crate::process_image_bytes_with_info)
/// and [`process_image_bytes_with_warnings`](crate::process_image_bytes_with_warnings)
/// when protection was applied with reduced effectiveness or with an advisory
/// configuration.
/// For legal defense use cases, callers should check for warnings to understand
/// what level of protection was actually applied.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum ProtectionWarning {
    /// No MAC key was configured.
    ///
    /// The embedded payload can still detect accidental corruption via CRC32,
    /// but it is forgeable. Reverse proxies serving adversarial traffic should
    /// configure a MAC key and verify with the same key.
    MissingMacKey,
    /// Metadata injection was disabled.
    ///
    /// The steganographic payload may still be present, but visible legal/DMI
    /// markers will not be available to scrapers or downstream evidence tools.
    MetadataInjectionDisabled,
    /// Progressive JPEG detected — fell back to Q-table seed only.
    ///
    /// Full F5 DCT steganography was not applied because the JPEG uses
    /// progressive encoding, which the transcoder cannot decode. Only the
    /// seed was stored in quantization tables. This provides weaker protection
    /// than the standard DCT steganography path.
    ProgressiveJpegFallback,
    /// JPEG output was requested.
    ///
    /// The protection is efficient for byte-preserving JPEG serving through the
    /// stegoeggo fast path, but generic downstream JPEG re-encoding destroys
    /// COM/APP metadata, Q-table seed bits, and DCT payload evidence.
    JpegReencodeFragile,
    /// Image is too small for LSB steganographic embedding.
    ///
    /// The payload requires more pixels than the image provides. No LSB payload
    /// was embedded. Only metadata markers (and Q-table seeds for JPEG) were applied.
    /// Use a larger image or a smaller payload to enable steganographic protection.
    LsbCapacitySkipped,
    /// JPEG DCT coefficients insufficient for full F5 embedding.
    ///
    /// The image has too few DCT coefficients (e.g., a very small or heavily
    /// compressed JPEG) to embed the full payload. Only the seed was stored in
    /// quantization tables. This provides weaker protection than the standard
    /// DCT steganography path.
    DctCapacityInsufficient,
    /// Legal claims were explicitly disabled while legal metadata is present.
    ///
    /// The caller set `inject_legal_claims` to `false` but also provided
    /// non-empty [`LegalMetadata`]. This is contradictory: legal metadata
    /// should not be provided if injection is not desired. The legal metadata
    /// will be silently ignored.
    ContradictoryLegalClaims,
}

impl std::fmt::Display for ProtectionWarning {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ProtectionWarning::MissingMacKey => write!(
                f,
                "No MAC key configured: payload integrity is CRC32-only and forgeable."
            ),
            ProtectionWarning::MetadataInjectionDisabled => write!(
                f,
                "Metadata injection disabled: visible DMI/legal evidence will not be emitted."
            ),
            ProtectionWarning::ProgressiveJpegFallback => write!(
                f,
                "Progressive JPEG detected: fell back to Q-table seed only. \
                 Full F5 DCT steganography was not applied."
            ),
            ProtectionWarning::JpegReencodeFragile => write!(
                f,
                "JPEG output is fragile under downstream re-encoding; serve byte-identical \
                 output or expect metadata/Q-table/DCT evidence loss."
            ),
            ProtectionWarning::LsbCapacitySkipped => write!(
                f,
                "Image too small for LSB steganographic embedding: no payload embedded. \
                 Only metadata markers were applied."
            ),
            ProtectionWarning::DctCapacityInsufficient => write!(
                f,
                "JPEG DCT coefficients insufficient for full F5 embedding: \
                 fell back to Q-table seed only. Weaker protection applied."
            ),
            ProtectionWarning::ContradictoryLegalClaims => write!(
                f,
                "Legal claims explicitly disabled but legal metadata is present: \
                 the legal metadata will be ignored. Remove the legal metadata or \
                 stop disabling legal claims."
            ),
        }
    }
}

/// Categorizes protection warnings by their relevance to evidence profiles.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum WarningCategory {
    /// Warnings relevant to legal-notice evidence models.
    LegalNotice,
    /// Warnings about steganographic capacity limitations (best-effort).
    BestEffortStego,
    /// Warnings relevant to authenticated provenance models.
    AuthenticatedProvenance,
    /// Warnings about format-specific fragility or fallbacks.
    FormatFragility,
}

/// Severity level for a protection warning within a specific evidence profile.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum WarningSeverity {
    /// Informational — no action required; expected behavior for this profile.
    Info,
    /// Warning — protection is degraded; caller should be aware.
    Warning,
    /// Error — the evidence model cannot be satisfied with current configuration.
    Error,
}

impl std::fmt::Display for WarningSeverity {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            WarningSeverity::Info => write!(f, "info"),
            WarningSeverity::Warning => write!(f, "warning"),
            WarningSeverity::Error => write!(f, "error"),
        }
    }
}

impl ProtectionWarning {
    /// Returns the category this warning belongs to.
    #[must_use]
    pub fn category(&self) -> WarningCategory {
        match self {
            ProtectionWarning::MissingMacKey => WarningCategory::AuthenticatedProvenance,
            ProtectionWarning::MetadataInjectionDisabled => WarningCategory::LegalNotice,
            ProtectionWarning::ProgressiveJpegFallback => WarningCategory::FormatFragility,
            ProtectionWarning::JpegReencodeFragile => WarningCategory::FormatFragility,
            ProtectionWarning::LsbCapacitySkipped => WarningCategory::BestEffortStego,
            ProtectionWarning::DctCapacityInsufficient => WarningCategory::BestEffortStego,
            ProtectionWarning::ContradictoryLegalClaims => WarningCategory::LegalNotice,
        }
    }

    /// Returns the severity of this warning for the given evidence profile.
    #[allow(deprecated)]
    #[must_use]
    pub fn severity_for_profile(&self, profile: EvidenceProfile) -> WarningSeverity {
        match self {
            ProtectionWarning::MissingMacKey => match profile {
                EvidenceProfile::AuthenticatedProvenance | EvidenceProfile::Maximal => {
                    WarningSeverity::Warning
                }
                _ => WarningSeverity::Info,
            },
            ProtectionWarning::MetadataInjectionDisabled => match profile {
                EvidenceProfile::LegalNotice | EvidenceProfile::LegalNoticeWithStego => {
                    WarningSeverity::Error
                }
                _ => WarningSeverity::Warning,
            },
            ProtectionWarning::ProgressiveJpegFallback | ProtectionWarning::JpegReencodeFragile => {
                WarningSeverity::Warning
            }
            ProtectionWarning::LsbCapacitySkipped | ProtectionWarning::DctCapacityInsufficient => {
                match profile {
                    EvidenceProfile::LegalNotice => WarningSeverity::Info,
                    _ => WarningSeverity::Warning,
                }
            }
            ProtectionWarning::ContradictoryLegalClaims => WarningSeverity::Warning,
        }
    }
}

/// Explicit rights policy expressing data-mining intent.
///
/// This is the caller-facing representation of data-mining restrictions.
/// It maps to [`DmiValue`] for serialization but is never inferred from
/// processing intensity, output format, or channel selection.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
#[non_exhaustive]
pub enum RightsPolicy {
    /// No DMI claim is emitted.
    #[default]
    Unspecified,
    /// Explicit permission for data mining.
    Allowed,
    /// Prohibited for AI/ML training.
    ProhibitedAiMlTraining,
    /// Prohibited for generative AI training.
    ProhibitedGenerativeAiTraining,
    /// Prohibited except for search engine indexing.
    ProhibitedExceptSearchIndexing,
    /// All data mining prohibited.
    ProhibitedAllDataMining,
    /// Prohibited, see constraints for details.
    ProhibitedSeeConstraints,
}

impl RightsPolicy {
    /// Returns the string representation of this policy.
    #[must_use]
    pub fn as_str(&self) -> &'static str {
        match self {
            RightsPolicy::Unspecified => "Unspecified",
            RightsPolicy::Allowed => "Allowed",
            RightsPolicy::ProhibitedAiMlTraining => "ProhibitedAiMlTraining",
            RightsPolicy::ProhibitedGenerativeAiTraining => "ProhibitedGenerativeAiTraining",
            RightsPolicy::ProhibitedExceptSearchIndexing => "ProhibitedExceptSearchIndexing",
            RightsPolicy::ProhibitedAllDataMining => "ProhibitedAllDataMining",
            RightsPolicy::ProhibitedSeeConstraints => "ProhibitedSeeConstraints",
        }
    }

    /// Converts to the corresponding [`DmiValue`], if any.
    #[must_use]
    pub fn to_dmi_value(&self) -> Option<DmiValue> {
        match self {
            RightsPolicy::Unspecified => None,
            RightsPolicy::Allowed => Some(DmiValue::Allowed),
            RightsPolicy::ProhibitedAiMlTraining => Some(DmiValue::ProhibitedAiMlTraining),
            RightsPolicy::ProhibitedGenerativeAiTraining => {
                Some(DmiValue::ProhibitedGenAiMlTraining)
            }
            RightsPolicy::ProhibitedExceptSearchIndexing => {
                Some(DmiValue::ProhibitedExceptSearchEngineIndexing)
            }
            RightsPolicy::ProhibitedAllDataMining => Some(DmiValue::Prohibited),
            RightsPolicy::ProhibitedSeeConstraints => Some(DmiValue::ProhibitedSeeConstraints),
        }
    }

    /// Creates a `RightsPolicy` from the corresponding [`DmiValue`].
    #[must_use]
    pub fn from_dmi_value(dmi: DmiValue) -> Self {
        match dmi {
            DmiValue::Unspecified => RightsPolicy::Unspecified,
            DmiValue::Allowed => RightsPolicy::Allowed,
            DmiValue::ProhibitedAiMlTraining => RightsPolicy::ProhibitedAiMlTraining,
            DmiValue::ProhibitedGenAiMlTraining => RightsPolicy::ProhibitedGenerativeAiTraining,
            DmiValue::ProhibitedExceptSearchEngineIndexing => {
                RightsPolicy::ProhibitedExceptSearchIndexing
            }
            DmiValue::Prohibited => RightsPolicy::ProhibitedAllDataMining,
            DmiValue::ProhibitedSeeConstraints => RightsPolicy::ProhibitedSeeConstraints,
        }
    }

    /// Returns `true` if this policy requires constraint details.
    #[must_use]
    pub fn requires_constraints(&self) -> bool {
        matches!(self, RightsPolicy::ProhibitedSeeConstraints)
    }
}

/// Controls steganographic hidden-marker embedding.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[non_exhaustive]
pub enum HiddenMarkerMode {
    /// No LSB, DCT, Q-table, or tiled hidden marker work.
    Disabled,
    /// Existing non-tiled LSB/DCT behavior.
    BestEffort,
    /// Crop-resistant tiled mode with validated tile size.
    Tiled {
        /// Tile dimension in pixels. Must be >= 16.
        tile_size: u32,
    },
}

/// Controls payload authentication mode.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[non_exhaustive]
pub enum AuthenticationMode {
    /// Non-cryptographic CRC32 checksum.
    None,
    /// HMAC-SHA256 cryptographic authentication.
    Hmac,
}

/// Explicit configuration of protection channels.
///
/// Each channel maps to concrete pipeline work. Invalid combinations
/// are rejected during resolution.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProtectionChannels {
    /// Whether to emit/merge canonical rights metadata.
    pub rights_metadata: bool,
    /// Hidden marker embedding mode.
    pub hidden_marker: HiddenMarkerMode,
    /// Authentication mode for steganographic payloads.
    pub authentication: AuthenticationMode,
}

impl ProtectionChannels {
    /// Creates a metadata-only configuration (no hidden marker, no authentication).
    #[must_use]
    pub fn metadata_only() -> Self {
        Self {
            rights_metadata: true,
            hidden_marker: HiddenMarkerMode::Disabled,
            authentication: AuthenticationMode::None,
        }
    }

    /// Creates a metadata + best-effort hidden marker configuration.
    #[must_use]
    pub fn with_hidden_marker() -> Self {
        Self {
            rights_metadata: true,
            hidden_marker: HiddenMarkerMode::BestEffort,
            authentication: AuthenticationMode::None,
        }
    }

    /// Creates a metadata + hidden marker + HMAC authentication configuration.
    #[must_use]
    pub fn authenticated() -> Self {
        Self {
            rights_metadata: true,
            hidden_marker: HiddenMarkerMode::BestEffort,
            authentication: AuthenticationMode::Hmac,
        }
    }

    /// Returns true if this configuration performs any steganographic work.
    #[must_use]
    pub fn has_stego(&self) -> bool {
        !matches!(self.hidden_marker, HiddenMarkerMode::Disabled)
    }
}

/// Image processing options for the protection pipeline.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProcessingOptions {
    /// Override output format. `None` means same as input.
    pub output_format: Option<ImageOutputFormat>,
    /// JPEG quality (1-100, default 90).
    pub jpeg_quality: u8,
    /// Whether to produce progressive JPEG output.
    pub progressive_jpeg: bool,
    /// Maximum image dimension in pixels.
    pub max_dimension: Option<u32>,
    /// Metadata update policy for re-processing.
    pub metadata_update_policy: MetadataUpdatePolicy,
}

impl Default for ProcessingOptions {
    fn default() -> Self {
        Self {
            output_format: None,
            jpeg_quality: 90,
            progressive_jpeg: false,
            max_dimension: None,
            metadata_update_policy: MetadataUpdatePolicy::default(),
        }
    }
}

/// A validated protection request combining rights notice, policy, channels, and processing options.
///
/// This is the primary entry point for the new request-based API.
#[derive(Debug, Clone)]
pub struct ProtectionRequest {
    notice: RightsNotice,
    policy: RightsPolicy,
    channels: ProtectionChannels,
    processing: ProcessingOptions,
    seed: Option<u64>,
    intensity: f32,
    legal_metadata: Option<LegalMetadata>,
    mac_key: Option<Vec<u8>>,
    resource_limits: Option<crate::resource_limits::ResourceLimits>,
}

impl ProtectionRequest {
    /// Creates a new protection request.
    #[must_use]
    pub fn new(notice: RightsNotice, policy: RightsPolicy, channels: ProtectionChannels) -> Self {
        Self {
            notice,
            policy,
            channels,
            processing: ProcessingOptions::default(),
            seed: None,
            intensity: 0.5,
            legal_metadata: None,
            mac_key: None,
            resource_limits: None,
        }
    }

    /// Creates a metadata-only protection request (fastest path).
    #[must_use]
    pub fn metadata_only(notice: RightsNotice, policy: RightsPolicy) -> Self {
        Self::new(notice, policy, ProtectionChannels::metadata_only())
    }

    /// Creates a request with best-effort hidden marker.
    #[must_use]
    pub fn with_hidden_marker(notice: RightsNotice, policy: RightsPolicy) -> Self {
        Self::new(notice, policy, ProtectionChannels::with_hidden_marker())
    }

    /// Sets processing options.
    #[must_use]
    pub fn with_processing(mut self, processing: ProcessingOptions) -> Self {
        self.processing = processing;
        self
    }

    /// Sets the random seed for steganographic embedding.
    #[must_use]
    pub fn with_seed(mut self, seed: u64) -> Self {
        self.seed = Some(seed);
        self
    }

    /// Sets the embedding intensity (0.0-1.0).
    #[must_use]
    pub fn with_intensity(mut self, intensity: f32) -> Self {
        self.intensity = intensity.clamp(0.0, 1.0);
        self
    }

    /// Sets legal metadata for the request.
    #[must_use]
    pub fn with_legal_metadata(mut self, metadata: LegalMetadata) -> Self {
        self.legal_metadata = Some(metadata);
        self
    }

    /// Sets the MAC key for HMAC authentication.
    #[must_use]
    pub fn with_mac_key(mut self, key: Vec<u8>) -> Self {
        self.mac_key = Some(key);
        self
    }

    /// Sets custom resource limits for parser safety.
    #[must_use]
    pub fn with_resource_limits(mut self, limits: crate::resource_limits::ResourceLimits) -> Self {
        self.resource_limits = Some(limits);
        self
    }

    /// Sets the output format.
    #[must_use]
    pub fn with_output_format(mut self, format: ImageOutputFormat) -> Self {
        self.processing.output_format = Some(format);
        self
    }

    /// Sets JPEG quality.
    #[must_use]
    pub fn with_jpeg_quality(mut self, quality: u8) -> Self {
        self.processing.jpeg_quality = quality.clamp(1, 100);
        self
    }

    /// Enables progressive JPEG output.
    #[must_use]
    pub fn with_progressive_jpeg(mut self) -> Self {
        self.processing.progressive_jpeg = true;
        self
    }

    /// Sets maximum image dimension.
    #[must_use]
    pub fn with_max_dimension(mut self, max: u32) -> Self {
        self.processing.max_dimension = Some(max);
        self
    }

    /// Sets the metadata update policy.
    #[must_use]
    pub fn with_metadata_update_policy(mut self, policy: MetadataUpdatePolicy) -> Self {
        self.processing.metadata_update_policy = policy;
        self
    }

    /// Returns the rights notice.
    #[must_use]
    pub fn notice(&self) -> &RightsNotice {
        &self.notice
    }

    /// Returns the rights policy.
    #[must_use]
    pub fn policy(&self) -> RightsPolicy {
        self.policy
    }

    /// Returns the protection channels.
    #[must_use]
    pub fn channels(&self) -> &ProtectionChannels {
        &self.channels
    }

    /// Returns the processing options.
    #[must_use]
    pub fn processing(&self) -> &ProcessingOptions {
        &self.processing
    }

    /// Returns the seed, if set.
    #[must_use]
    pub fn seed(&self) -> Option<u64> {
        self.seed
    }

    /// Returns the intensity.
    #[must_use]
    pub fn intensity(&self) -> f32 {
        self.intensity
    }

    /// Returns the legal metadata, if set.
    #[must_use]
    pub fn legal_metadata(&self) -> Option<&LegalMetadata> {
        self.legal_metadata.as_ref()
    }

    /// Returns the MAC key, if set.
    #[must_use]
    pub fn mac_key(&self) -> Option<&[u8]> {
        self.mac_key.as_deref()
    }

    /// Returns the resource limits, if set.
    #[must_use]
    pub fn resource_limits(&self) -> Option<&crate::resource_limits::ResourceLimits> {
        self.resource_limits.as_ref()
    }

    /// Creates a protection request from a preset, notice, and policy.
    ///
    /// The preset determines the channel configuration. Additional options
    /// can be chained with builder methods.
    #[must_use]
    pub fn from_preset(
        preset: ProtectionPreset,
        notice: RightsNotice,
        policy: RightsPolicy,
    ) -> Self {
        Self::new(notice, policy, preset.to_channels())
    }
}

/// An immutable, validated execution plan produced by resolving a [`ProtectionRequest`].
///
/// Pipeline stages consume this plan rather than repeatedly querying
/// mutable/optional context fields.
#[derive(Debug, Clone)]
pub struct ResolvedProtectionPlan {
    effective_policy: RightsPolicy,
    effective_dmi: Option<DmiValue>,
    effective_notice: RightsNotice,
    channels: ProtectionChannels,
    processing: ProcessingOptions,
    seed: u64,
    intensity: f32,
    input_format: ImageOutputFormat,
    output_format: ImageOutputFormat,
    legal_metadata: Option<LegalMetadata>,
    mac_key: Option<Vec<u8>>,
    warnings: Vec<ProtectionWarning>,
    resource_limits: crate::resource_limits::ResourceLimits,
}

impl ResolvedProtectionPlan {
    /// Returns the effective rights policy.
    #[must_use]
    pub fn effective_policy(&self) -> RightsPolicy {
        self.effective_policy
    }

    /// Returns the effective DMI value for serialization.
    #[must_use]
    pub fn effective_dmi(&self) -> Option<DmiValue> {
        self.effective_dmi
    }

    /// Returns the effective rights notice.
    #[must_use]
    pub fn effective_notice(&self) -> &RightsNotice {
        &self.effective_notice
    }

    /// Returns the resolved channels.
    #[must_use]
    pub fn channels(&self) -> &ProtectionChannels {
        &self.channels
    }

    /// Returns the processing options.
    #[must_use]
    pub fn processing(&self) -> &ProcessingOptions {
        &self.processing
    }

    /// Returns the resolved seed.
    #[must_use]
    pub fn seed(&self) -> u64 {
        self.seed
    }

    /// Returns the intensity.
    #[must_use]
    pub fn intensity(&self) -> f32 {
        self.intensity
    }

    /// Returns the input format.
    #[must_use]
    pub fn input_format(&self) -> ImageOutputFormat {
        self.input_format
    }

    /// Returns the output format.
    #[must_use]
    pub fn output_format(&self) -> ImageOutputFormat {
        self.output_format
    }

    /// Returns the legal metadata.
    #[must_use]
    pub fn legal_metadata(&self) -> Option<&LegalMetadata> {
        self.legal_metadata.as_ref()
    }

    /// Returns the MAC key.
    #[must_use]
    pub fn mac_key(&self) -> Option<&[u8]> {
        self.mac_key.as_deref()
    }

    /// Returns any warnings generated during resolution.
    #[must_use]
    pub fn warnings(&self) -> &[ProtectionWarning] {
        &self.warnings
    }

    /// Returns the resource limits for this plan.
    #[must_use]
    pub fn resource_limits(&self) -> &crate::resource_limits::ResourceLimits {
        &self.resource_limits
    }

    /// Returns true if any pixel-modifying work is required.
    #[must_use]
    pub fn modifies_pixels(&self) -> bool {
        self.channels.has_stego()
    }

    /// Returns true if this is a metadata-only plan.
    #[must_use]
    pub fn is_metadata_only(&self) -> bool {
        !self.channels.has_stego() && self.channels.rights_metadata
    }

    /// Construct a resolved plan from validated parts.
    ///
    /// This is crate-internal — external code should use [`resolve_request`](crate::resolve_request).
    #[allow(clippy::too_many_arguments)]
    pub(crate) fn new(
        effective_policy: RightsPolicy,
        effective_dmi: Option<DmiValue>,
        effective_notice: RightsNotice,
        channels: ProtectionChannels,
        processing: ProcessingOptions,
        seed: u64,
        intensity: f32,
        input_format: ImageOutputFormat,
        output_format: ImageOutputFormat,
        legal_metadata: Option<LegalMetadata>,
        mac_key: Option<Vec<u8>>,
        warnings: Vec<ProtectionWarning>,
        resource_limits: crate::resource_limits::ResourceLimits,
    ) -> Self {
        Self {
            effective_policy,
            effective_dmi,
            effective_notice,
            channels,
            processing,
            seed,
            intensity,
            input_format,
            output_format,
            legal_metadata,
            mac_key,
            warnings,
            resource_limits,
        }
    }
}

/// Executable presets that expand into concrete channel configurations.
///
/// Each preset deterministically maps to [`ProtectionChannels`] plus
/// validation expectations. This replaces the non-executable
/// [`EvidenceProfile`] for new request-based API usage.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[non_exhaustive]
pub enum ProtectionPreset {
    /// Standards-aligned metadata notice. No hidden marker, no MAC.
    LegalNotice,
    /// Metadata notice plus best-effort hidden marker. No MAC required.
    LegalNoticeWithStego,
    /// Metadata + hidden marker + HMAC authentication. MAC key required.
    AuthenticatedProvenance,
    /// All available channels. MAC used if provided.
    Maximal,
}

impl ProtectionPreset {
    /// Expands this preset into concrete [`ProtectionChannels`].
    #[must_use]
    pub fn to_channels(&self) -> ProtectionChannels {
        match self {
            ProtectionPreset::LegalNotice => ProtectionChannels::metadata_only(),
            ProtectionPreset::LegalNoticeWithStego => ProtectionChannels::with_hidden_marker(),
            ProtectionPreset::AuthenticatedProvenance => ProtectionChannels::authenticated(),
            ProtectionPreset::Maximal => ProtectionChannels {
                rights_metadata: true,
                hidden_marker: HiddenMarkerMode::BestEffort,
                authentication: AuthenticationMode::Hmac,
            },
        }
    }

    /// Returns the lowercase string representation.
    #[must_use]
    pub fn as_str(&self) -> &'static str {
        match self {
            ProtectionPreset::LegalNotice => "legal-notice",
            ProtectionPreset::LegalNoticeWithStego => "legal-notice-stego",
            ProtectionPreset::AuthenticatedProvenance => "authenticated-provenance",
            ProtectionPreset::Maximal => "maximal",
        }
    }

    /// Returns `true` if this preset requires a MAC key.
    #[must_use]
    pub fn requires_mac_key(&self) -> bool {
        matches!(
            self,
            ProtectionPreset::AuthenticatedProvenance | ProtectionPreset::Maximal
        )
    }
}

/// Describes which channels were requested, executed, and degraded
/// during processing. Returned alongside the processed bytes.
#[derive(Debug, Clone, Default)]
pub struct ExecutionReport {
    /// The effective rights policy after resolution.
    pub effective_policy: RightsPolicy,
    /// The DMI value serialized into metadata, if any.
    pub effective_dmi: Option<DmiValue>,
    /// Whether metadata was injected.
    pub metadata_injected: bool,
    /// Whether steganographic embedding was attempted.
    pub stego_attempted: bool,
    /// Whether steganographic embedding succeeded.
    pub stego_succeeded: bool,
    /// Whether the output format differs from input.
    pub format_transcoded: bool,
    /// Warnings generated during execution.
    pub warnings: Vec<ProtectionWarning>,
    /// Observed resource usage during processing, if tracked.
    pub resource_usage: Option<crate::resource_limits::ResourceUsage>,
}

impl ExecutionReport {
    /// The effective rights policy after resolution.
    #[must_use]
    pub fn effective_policy(&self) -> RightsPolicy {
        self.effective_policy
    }

    /// The DMI value serialized into metadata, if any.
    #[must_use]
    pub fn effective_dmi(&self) -> Option<DmiValue> {
        self.effective_dmi
    }

    /// Whether metadata was injected.
    #[must_use]
    pub fn metadata_injected(&self) -> bool {
        self.metadata_injected
    }

    /// Whether steganographic embedding was attempted.
    #[must_use]
    pub fn stego_attempted(&self) -> bool {
        self.stego_attempted
    }

    /// Whether steganographic embedding succeeded.
    #[must_use]
    pub fn stego_succeeded(&self) -> bool {
        self.stego_succeeded
    }

    /// Whether the output format differs from input.
    #[must_use]
    pub fn format_transcoded(&self) -> bool {
        self.format_transcoded
    }

    /// Warnings generated during execution.
    #[must_use]
    pub fn warnings(&self) -> &[ProtectionWarning] {
        &self.warnings
    }

    /// Observed resource usage during processing, if tracked.
    #[must_use]
    pub fn resource_usage(&self) -> Option<&crate::resource_limits::ResourceUsage> {
        self.resource_usage.as_ref()
    }

    /// Returns true if any channel executed successfully.
    #[must_use]
    pub fn any_succeeded(&self) -> bool {
        self.metadata_injected || self.stego_succeeded
    }

    /// Returns true if any requested channel was degraded or skipped.
    #[allow(deprecated)]
    #[must_use]
    pub fn has_degradation(&self) -> bool {
        self.warnings.iter().any(|w| {
            matches!(
                w.severity_for_profile(EvidenceProfile::LegalNotice),
                WarningSeverity::Warning | WarningSeverity::Error
            )
        })
    }
}

impl From<DmiValue> for RightsPolicy {
    fn from(dmi: DmiValue) -> Self {
        RightsPolicy::from_dmi_value(dmi)
    }
}

impl From<RightsPolicy> for DmiValue {
    fn from(policy: RightsPolicy) -> Self {
        match policy {
            RightsPolicy::Unspecified => DmiValue::Unspecified,
            RightsPolicy::Allowed => DmiValue::Allowed,
            RightsPolicy::ProhibitedAiMlTraining => DmiValue::ProhibitedAiMlTraining,
            RightsPolicy::ProhibitedGenerativeAiTraining => DmiValue::ProhibitedGenAiMlTraining,
            RightsPolicy::ProhibitedExceptSearchIndexing => {
                DmiValue::ProhibitedExceptSearchEngineIndexing
            }
            RightsPolicy::ProhibitedAllDataMining => DmiValue::Prohibited,
            RightsPolicy::ProhibitedSeeConstraints => DmiValue::ProhibitedSeeConstraints,
        }
    }
}

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

    #[test]
    fn builder_chain() {
        let ctx = ProtectionContext::new(0.5, 42)
            .with_format(ImageOutputFormat::Png)
            .with_stego_redundancy(3);
        assert_eq!(ctx.intensity(), 0.5);
        assert_eq!(ctx.seed(), 42);
        assert_eq!(ctx.stego_redundancy(), 3);
    }

    #[test]
    fn intensity_clamped() {
        let ctx = ProtectionContext::new(2.0, 42);
        assert_eq!(ctx.intensity(), 1.0);

        let ctx = ProtectionContext::new(-1.0, 42);
        assert_eq!(ctx.intensity(), 0.0);
    }

    #[test]
    fn seed_roundtrip_through_serde() {
        let ctx = ProtectionContext::new(0.7, 12345);
        let json = serde_json::to_string(&ctx).unwrap();
        let restored: ProtectionContext = serde_json::from_str(&json).unwrap();
        assert_eq!(restored.seed(), 12345);
        assert_eq!(restored.intensity(), 0.7);
    }

    #[test]
    fn serialize_emits_warning_when_config_set() {
        let ctx = ProtectionContext::new(0.5, 99).with_mac_key(b"key".to_vec());
        let json = serde_json::to_string(&ctx).unwrap();
        assert!(
            json.contains("_config_dropped_warning"),
            "Serialized JSON should contain a warning field when config is set: {json}"
        );
        assert!(
            json.contains("MAC key"),
            "Warning should mention the MAC key: {json}"
        );

        let restored: ProtectionContext = serde_json::from_str(&json).unwrap();
        assert_eq!(restored.seed(), 99);
        assert_eq!(restored.intensity(), 0.5);
        assert!(
            restored.mac_key().is_none(),
            "MAC key should be lost after serde roundtrip even when warning is emitted"
        );
    }

    #[test]
    fn serialize_no_warning_when_config_none() {
        let ctx = ProtectionContext::new(0.5, 99);
        let json = serde_json::to_string(&ctx).unwrap();
        assert!(
            !json.contains("_config_dropped_warning"),
            "No warning should be emitted when config is None: {json}"
        );
    }

    // ── Tile size configuration ───────────────────────────────────────

    #[test]
    fn tile_size_default_is_none() {
        let ctx = ProtectionContext::new(0.5, 42);
        assert_eq!(ctx.tile_size(), None);
        assert!(!ctx.is_tile_mode_enabled());
    }

    #[test]
    fn with_tile_size_zero_disables_tiling() {
        let ctx = ProtectionContext::new(0.5, 42).with_tile_size(0);
        assert_eq!(ctx.tile_size(), Some(0));
        assert!(!ctx.is_tile_mode_enabled());
    }

    #[test]
    fn with_tile_size_enables_tiling() {
        let ctx = ProtectionContext::new(0.5, 42).with_tile_size(64);
        assert_eq!(ctx.tile_size(), Some(64));
        assert!(ctx.is_tile_mode_enabled());
    }

    #[test]
    fn with_tile_size_clamps_below_minimum() {
        let ctx = ProtectionContext::new(0.5, 42).with_tile_size(8);
        assert_eq!(ctx.tile_size(), Some(32), "values below 32 clamp up to 32");
    }

    #[test]
    fn with_tile_size_clamps_above_maximum() {
        let ctx = ProtectionContext::new(0.5, 42).with_tile_size(4096);
        assert_eq!(
            ctx.tile_size(),
            Some(1024),
            "values above 1024 clamp down to 1024"
        );
    }

    #[test]
    fn with_tile_extraction_max_origins_defaults_to_64() {
        let ctx = ProtectionContext::new(0.5, 42);
        assert_eq!(ctx.tile_extraction_max_origins(), 64);
    }

    #[test]
    fn with_tile_extraction_max_origins_zero_clamps_to_one() {
        let ctx = ProtectionContext::new(0.5, 42).with_tile_extraction_max_origins(0);
        assert_eq!(ctx.tile_extraction_max_origins(), 1);
    }

    #[test]
    fn tile_settings_survive_serde_roundtrip() {
        let ctx = ProtectionContext::new(0.5, 42)
            .with_tile_size(64)
            .with_tile_extraction_max_origins(128);
        let json = serde_json::to_string(&ctx).unwrap();
        let restored: ProtectionContext = serde_json::from_str(&json).unwrap();
        assert_eq!(restored.tile_size(), Some(64));
        assert_eq!(restored.tile_extraction_max_origins(), 128);
    }

    #[test]
    fn protection_level_byte_roundtrip() {
        let levels = [
            ProtectionLevel::Disabled,
            ProtectionLevel::Light,
            ProtectionLevel::Standard,
        ];
        for level in &levels {
            let byte = level.to_byte();
            let restored = ProtectionLevel::from_byte(byte);
            assert_eq!(restored.as_ref(), Some(level));
        }
    }

    #[test]
    fn protection_level_from_invalid_byte() {
        assert!(ProtectionLevel::from_byte(3).is_none());
        assert!(ProtectionLevel::from_byte(255).is_none());
    }

    #[test]
    fn dmi_value_iptc_property_mapping() {
        use crate::types::DmiValue;

        let allowed = DmiValue::Allowed;
        assert!(allowed.to_iptc_property().contains("DMI-Allowed"));

        let prohibited_training = DmiValue::ProhibitedAiMlTraining;
        assert!(prohibited_training
            .to_iptc_property()
            .contains("DMI-Prohibited"));

        let prohibited_gen = DmiValue::ProhibitedGenAiMlTraining;
        assert!(prohibited_gen.to_iptc_property().contains("DMI-Prohibited"));

        let prohibited_all = DmiValue::Prohibited;
        assert!(prohibited_all.to_iptc_property().contains("DMI-Prohibited"));

        let prohibited_se = DmiValue::ProhibitedExceptSearchEngineIndexing;
        assert!(prohibited_se.to_iptc_property().contains("DMI-Prohibited"));

        let prohibited_see = DmiValue::ProhibitedSeeConstraints;
        assert!(prohibited_see.to_iptc_property().contains("DMI-Prohibited"));

        let unspecified = DmiValue::Unspecified;
        assert!(unspecified.to_iptc_property().contains("DMI"));
    }

    #[test]
    fn evidence_profile_default_is_legal_notice() {
        let ctx = ProtectionContext::new(0.5, 42);
        assert_eq!(ctx.evidence_profile(), EvidenceProfile::LegalNotice);
    }

    #[test]
    fn with_evidence_profile_sets_and_retrieves() {
        let ctx = ProtectionContext::new(0.5, 42)
            .with_evidence_profile(EvidenceProfile::AuthenticatedProvenance);
        assert_eq!(
            ctx.evidence_profile(),
            EvidenceProfile::AuthenticatedProvenance
        );
    }

    #[test]
    fn evidence_profile_serialization_roundtrip() {
        let profiles = [
            EvidenceProfile::LegalNotice,
            EvidenceProfile::LegalNoticeWithStego,
            EvidenceProfile::AuthenticatedProvenance,
            EvidenceProfile::Maximal,
        ];
        for profile in &profiles {
            let json = serde_json::to_string(profile).unwrap();
            let restored: EvidenceProfile = serde_json::from_str(&json).unwrap();
            assert_eq!(&restored, profile);
        }
    }

    #[test]
    fn evidence_profile_as_str() {
        assert_eq!(EvidenceProfile::LegalNotice.as_str(), "legal-notice");
        assert_eq!(
            EvidenceProfile::LegalNoticeWithStego.as_str(),
            "legal-notice-stego"
        );
        assert_eq!(
            EvidenceProfile::AuthenticatedProvenance.as_str(),
            "authenticated-provenance"
        );
        assert_eq!(EvidenceProfile::Maximal.as_str(), "maximal");
    }

    #[test]
    fn evidence_profile_serde_roundtrip_in_context() {
        let ctx = ProtectionContext::new(0.5, 42)
            .with_evidence_profile(EvidenceProfile::AuthenticatedProvenance);
        let json = serde_json::to_string(&ctx).unwrap();
        let restored: ProtectionContext = serde_json::from_str(&json).unwrap();
        assert_eq!(
            restored.evidence_profile(),
            EvidenceProfile::AuthenticatedProvenance
        );
    }

    #[test]
    fn evidence_profile_default_context_backward_compatible() {
        let ctx = ProtectionContext::new(0.5, 42);
        let json = serde_json::to_string(&ctx).unwrap();
        let restored: ProtectionContext = serde_json::from_str(&json).unwrap();
        assert_eq!(restored.evidence_profile(), EvidenceProfile::LegalNotice);
        assert_eq!(restored.intensity(), 0.5);
        assert_eq!(restored.seed(), 42);
    }

    #[test]
    fn helper_constructors_set_correct_profile() {
        assert_eq!(
            ProtectionContext::legal_notice().evidence_profile(),
            EvidenceProfile::LegalNotice
        );
        assert_eq!(
            ProtectionContext::legal_notice_with_stego().evidence_profile(),
            EvidenceProfile::LegalNoticeWithStego
        );
        assert_eq!(
            ProtectionContext::authenticated_provenance().evidence_profile(),
            EvidenceProfile::AuthenticatedProvenance
        );
        assert_eq!(
            ProtectionContext::maximal().evidence_profile(),
            EvidenceProfile::Maximal
        );
    }

    #[test]
    fn warning_category_mapping() {
        assert_eq!(
            ProtectionWarning::MissingMacKey.category(),
            WarningCategory::AuthenticatedProvenance
        );
        assert_eq!(
            ProtectionWarning::MetadataInjectionDisabled.category(),
            WarningCategory::LegalNotice
        );
        assert_eq!(
            ProtectionWarning::ProgressiveJpegFallback.category(),
            WarningCategory::FormatFragility
        );
        assert_eq!(
            ProtectionWarning::JpegReencodeFragile.category(),
            WarningCategory::FormatFragility
        );
        assert_eq!(
            ProtectionWarning::LsbCapacitySkipped.category(),
            WarningCategory::BestEffortStego
        );
        assert_eq!(
            ProtectionWarning::DctCapacityInsufficient.category(),
            WarningCategory::BestEffortStego
        );
    }

    #[test]
    fn missing_mac_key_severity_by_profile() {
        let w = ProtectionWarning::MissingMacKey;
        assert_eq!(
            w.severity_for_profile(EvidenceProfile::AuthenticatedProvenance),
            WarningSeverity::Warning
        );
        assert_eq!(
            w.severity_for_profile(EvidenceProfile::Maximal),
            WarningSeverity::Warning
        );
        assert_eq!(
            w.severity_for_profile(EvidenceProfile::LegalNotice),
            WarningSeverity::Info
        );
        assert_eq!(
            w.severity_for_profile(EvidenceProfile::LegalNoticeWithStego),
            WarningSeverity::Info
        );
    }

    #[test]
    fn metadata_injection_disabled_severity_by_profile() {
        let w = ProtectionWarning::MetadataInjectionDisabled;
        assert_eq!(
            w.severity_for_profile(EvidenceProfile::LegalNotice),
            WarningSeverity::Error
        );
        assert_eq!(
            w.severity_for_profile(EvidenceProfile::LegalNoticeWithStego),
            WarningSeverity::Error
        );
        assert_eq!(
            w.severity_for_profile(EvidenceProfile::AuthenticatedProvenance),
            WarningSeverity::Warning
        );
        assert_eq!(
            w.severity_for_profile(EvidenceProfile::Maximal),
            WarningSeverity::Warning
        );
    }

    #[test]
    fn format_fragility_severity_is_always_warning() {
        for w in [
            ProtectionWarning::ProgressiveJpegFallback,
            ProtectionWarning::JpegReencodeFragile,
        ] {
            for profile in [
                EvidenceProfile::LegalNotice,
                EvidenceProfile::LegalNoticeWithStego,
                EvidenceProfile::AuthenticatedProvenance,
                EvidenceProfile::Maximal,
            ] {
                assert_eq!(
                    w.severity_for_profile(profile),
                    WarningSeverity::Warning,
                    "{:?} should be Warning for {:?}",
                    w,
                    profile
                );
            }
        }
    }

    #[test]
    fn stego_capacity_severity_by_profile() {
        for w in [
            ProtectionWarning::LsbCapacitySkipped,
            ProtectionWarning::DctCapacityInsufficient,
        ] {
            assert_eq!(
                w.severity_for_profile(EvidenceProfile::LegalNotice),
                WarningSeverity::Info,
                "{:?} should be Info for LegalNotice",
                w
            );
            assert_eq!(
                w.severity_for_profile(EvidenceProfile::LegalNoticeWithStego),
                WarningSeverity::Warning,
                "{:?} should be Warning for LegalNoticeWithStego",
                w
            );
            assert_eq!(
                w.severity_for_profile(EvidenceProfile::AuthenticatedProvenance),
                WarningSeverity::Warning,
                "{:?} should be Warning for AuthenticatedProvenance",
                w
            );
            assert_eq!(
                w.severity_for_profile(EvidenceProfile::Maximal),
                WarningSeverity::Warning,
                "{:?} should be Warning for Maximal",
                w
            );
        }
    }
}

#[cfg(test)]
#[allow(deprecated)]
mod plus_mapping_tests {
    use super::*;

    #[test]
    fn all_variants_have_plus_vocab_key() {
        let variants = [
            DmiValue::Unspecified,
            DmiValue::Allowed,
            DmiValue::ProhibitedAiMlTraining,
            DmiValue::ProhibitedGenAiMlTraining,
            DmiValue::ProhibitedExceptSearchEngineIndexing,
            DmiValue::Prohibited,
            DmiValue::ProhibitedSeeConstraints,
        ];
        for v in variants {
            let key = v.plus_vocab_key();
            assert!(key.starts_with("DMI-"), "key must start with DMI-: {key}");
            assert_eq!(DmiValue::from_plus_vocab_key(key), Some(v));
        }
    }

    #[test]
    fn from_plus_vocab_key_rejects_unknown() {
        assert_eq!(DmiValue::from_plus_vocab_key("DMI-UNKNOWN"), None);
        assert_eq!(DmiValue::from_plus_vocab_key(""), None);
        assert_eq!(DmiValue::from_plus_vocab_key("Prohibited"), None);
    }

    #[test]
    fn plus_vocab_keys_match_exiftool() {
        assert_eq!(
            DmiValue::ProhibitedSeeConstraints.plus_vocab_key(),
            "DMI-PROHIBITED-SEECONSTRAINT"
        );
        assert_eq!(
            DmiValue::ProhibitedAiMlTraining.plus_vocab_key(),
            "DMI-PROHIBITED-AIMLTRAINING"
        );
    }
}

#[cfg(test)]
#[allow(deprecated)]
mod rights_policy_tests {
    use super::*;

    #[test]
    fn unspecified_to_dmi_returns_none() {
        assert_eq!(RightsPolicy::Unspecified.to_dmi_value(), None);
    }

    #[test]
    fn allowed_to_dmi() {
        assert_eq!(
            RightsPolicy::Allowed.to_dmi_value(),
            Some(DmiValue::Allowed)
        );
    }

    #[test]
    fn prohibited_ai_ml_training_to_dmi() {
        assert_eq!(
            RightsPolicy::ProhibitedAiMlTraining.to_dmi_value(),
            Some(DmiValue::ProhibitedAiMlTraining)
        );
    }

    #[test]
    fn prohibited_generative_ai_training_to_dmi() {
        assert_eq!(
            RightsPolicy::ProhibitedGenerativeAiTraining.to_dmi_value(),
            Some(DmiValue::ProhibitedGenAiMlTraining)
        );
    }

    #[test]
    fn prohibited_except_search_indexing_to_dmi() {
        assert_eq!(
            RightsPolicy::ProhibitedExceptSearchIndexing.to_dmi_value(),
            Some(DmiValue::ProhibitedExceptSearchEngineIndexing)
        );
    }

    #[test]
    fn prohibited_all_data_mining_to_dmi() {
        assert_eq!(
            RightsPolicy::ProhibitedAllDataMining.to_dmi_value(),
            Some(DmiValue::Prohibited)
        );
    }

    #[test]
    fn prohibited_see_constraints_to_dmi() {
        assert_eq!(
            RightsPolicy::ProhibitedSeeConstraints.to_dmi_value(),
            Some(DmiValue::ProhibitedSeeConstraints)
        );
    }

    #[test]
    fn from_dmi_unspecified() {
        assert_eq!(
            RightsPolicy::from_dmi_value(DmiValue::Unspecified),
            RightsPolicy::Unspecified
        );
    }

    #[test]
    fn from_dmi_allowed() {
        assert_eq!(
            RightsPolicy::from_dmi_value(DmiValue::Allowed),
            RightsPolicy::Allowed
        );
    }

    #[test]
    fn from_dmi_prohibited_ai_ml_training() {
        assert_eq!(
            RightsPolicy::from_dmi_value(DmiValue::ProhibitedAiMlTraining),
            RightsPolicy::ProhibitedAiMlTraining
        );
    }

    #[test]
    fn from_dmi_prohibited_gen_ai_ml_training() {
        assert_eq!(
            RightsPolicy::from_dmi_value(DmiValue::ProhibitedGenAiMlTraining),
            RightsPolicy::ProhibitedGenerativeAiTraining
        );
    }

    #[test]
    fn from_dmi_prohibited_except_search_engine_indexing() {
        assert_eq!(
            RightsPolicy::from_dmi_value(DmiValue::ProhibitedExceptSearchEngineIndexing),
            RightsPolicy::ProhibitedExceptSearchIndexing
        );
    }

    #[test]
    fn from_dmi_prohibited() {
        assert_eq!(
            RightsPolicy::from_dmi_value(DmiValue::Prohibited),
            RightsPolicy::ProhibitedAllDataMining
        );
    }

    #[test]
    fn from_dmi_prohibited_see_constraints() {
        assert_eq!(
            RightsPolicy::from_dmi_value(DmiValue::ProhibitedSeeConstraints),
            RightsPolicy::ProhibitedSeeConstraints
        );
    }

    #[test]
    fn roundtrip_to_dmi_from_dmi() {
        let policies = [
            RightsPolicy::Allowed,
            RightsPolicy::ProhibitedAiMlTraining,
            RightsPolicy::ProhibitedGenerativeAiTraining,
            RightsPolicy::ProhibitedExceptSearchIndexing,
            RightsPolicy::ProhibitedAllDataMining,
            RightsPolicy::ProhibitedSeeConstraints,
        ];
        for policy in policies {
            let dmi = policy.to_dmi_value().unwrap();
            let roundtripped = RightsPolicy::from_dmi_value(dmi);
            assert_eq!(roundtripped, policy);
        }
    }

    #[test]
    fn roundtrip_from_dmi_to_dmi() {
        let dmi_values = [
            DmiValue::Allowed,
            DmiValue::ProhibitedAiMlTraining,
            DmiValue::ProhibitedGenAiMlTraining,
            DmiValue::ProhibitedExceptSearchEngineIndexing,
            DmiValue::Prohibited,
            DmiValue::ProhibitedSeeConstraints,
        ];
        for dmi in dmi_values {
            let policy = RightsPolicy::from_dmi_value(dmi);
            let roundtripped = policy.to_dmi_value().unwrap();
            assert_eq!(roundtripped, dmi);
        }
    }

    #[test]
    fn from_trait_matches_function() {
        for dmi in [
            DmiValue::Allowed,
            DmiValue::ProhibitedAiMlTraining,
            DmiValue::ProhibitedGenAiMlTraining,
        ] {
            let via_from: RightsPolicy = dmi.into();
            let via_fn = RightsPolicy::from_dmi_value(dmi);
            assert_eq!(via_from, via_fn);
        }
    }

    #[test]
    fn into_trait_matches_to_dmi_value() {
        for policy in [
            RightsPolicy::Allowed,
            RightsPolicy::ProhibitedAiMlTraining,
            RightsPolicy::ProhibitedGenerativeAiTraining,
        ] {
            let via_into: DmiValue = policy.into();
            let via_fn = policy.to_dmi_value().unwrap();
            assert_eq!(via_into, via_fn);
        }
    }

    #[test]
    fn requires_constraints_only_for_see_constraints() {
        assert!(!RightsPolicy::Allowed.requires_constraints());
        assert!(!RightsPolicy::ProhibitedAiMlTraining.requires_constraints());
        assert!(RightsPolicy::ProhibitedSeeConstraints.requires_constraints());
    }

    #[test]
    fn as_str_matches_variant_name() {
        assert_eq!(RightsPolicy::Unspecified.as_str(), "Unspecified");
        assert_eq!(RightsPolicy::Allowed.as_str(), "Allowed");
        assert_eq!(
            RightsPolicy::ProhibitedAllDataMining.as_str(),
            "ProhibitedAllDataMining"
        );
    }
}

#[cfg(test)]
#[allow(deprecated)]
mod protection_preset_tests {
    use super::*;

    #[test]
    fn legal_notice_expands_to_metadata_only() {
        let channels = ProtectionPreset::LegalNotice.to_channels();
        assert!(channels.rights_metadata);
        assert_eq!(channels.hidden_marker, HiddenMarkerMode::Disabled);
        assert_eq!(channels.authentication, AuthenticationMode::None);
        assert!(!channels.has_stego());
    }

    #[test]
    fn legal_notice_with_stego_expands_correctly() {
        let channels = ProtectionPreset::LegalNoticeWithStego.to_channels();
        assert!(channels.rights_metadata);
        assert_eq!(channels.hidden_marker, HiddenMarkerMode::BestEffort);
        assert_eq!(channels.authentication, AuthenticationMode::None);
        assert!(channels.has_stego());
    }

    #[test]
    fn authenticated_provenance_expands_correctly() {
        let channels = ProtectionPreset::AuthenticatedProvenance.to_channels();
        assert!(channels.rights_metadata);
        assert_eq!(channels.hidden_marker, HiddenMarkerMode::BestEffort);
        assert_eq!(channels.authentication, AuthenticationMode::Hmac);
        assert!(channels.has_stego());
    }

    #[test]
    fn maximal_expands_correctly() {
        let channels = ProtectionPreset::Maximal.to_channels();
        assert!(channels.rights_metadata);
        assert_eq!(channels.hidden_marker, HiddenMarkerMode::BestEffort);
        assert_eq!(channels.authentication, AuthenticationMode::Hmac);
        assert!(channels.has_stego());
    }

    #[test]
    fn requires_mac_key_only_for_authenticated_presets() {
        assert!(!ProtectionPreset::LegalNotice.requires_mac_key());
        assert!(!ProtectionPreset::LegalNoticeWithStego.requires_mac_key());
        assert!(ProtectionPreset::AuthenticatedProvenance.requires_mac_key());
        assert!(ProtectionPreset::Maximal.requires_mac_key());
    }

    #[test]
    fn as_str_returns_lowercase() {
        assert_eq!(ProtectionPreset::LegalNotice.as_str(), "legal-notice");
        assert_eq!(
            ProtectionPreset::LegalNoticeWithStego.as_str(),
            "legal-notice-stego"
        );
        assert_eq!(
            ProtectionPreset::AuthenticatedProvenance.as_str(),
            "authenticated-provenance"
        );
        assert_eq!(ProtectionPreset::Maximal.as_str(), "maximal");
    }

    #[test]
    fn from_preset_uses_preset_channels() {
        let notice = RightsNotice::new();
        let request = ProtectionRequest::from_preset(
            ProtectionPreset::LegalNotice,
            notice,
            RightsPolicy::Allowed,
        );
        assert!(request.channels().rights_metadata);
        assert_eq!(request.channels().hidden_marker, HiddenMarkerMode::Disabled);
    }
}

#[cfg(test)]
#[allow(deprecated)]
mod url_validation_tests {
    use super::*;

    #[test]
    fn valid_https_url_passes() {
        let meta = LegalMetadata::new().with_license_url("https://example.com/license");
        assert!(meta.validate().is_ok());
    }

    #[test]
    fn valid_http_url_passes() {
        let meta = LegalMetadata::new().with_license_url("http://example.com/license");
        assert!(meta.validate().is_ok());
    }

    #[test]
    fn valid_ftp_url_passes() {
        let meta = LegalMetadata::new().with_license_url("ftp://files.example.com/doc");
        assert!(meta.validate().is_ok());
    }

    #[test]
    fn missing_scheme_fails() {
        let meta = LegalMetadata::new().with_license_url("example.com/license");
        let err = meta.validate().unwrap_err();
        assert!(
            err.to_string().contains("must include a scheme"),
            "Expected scheme error, got: {}",
            err
        );
    }

    #[test]
    fn empty_url_fails() {
        let meta = LegalMetadata::new().with_license_url("");
        let err = meta.validate().unwrap_err();
        assert!(
            err.to_string().contains("must not be empty"),
            "Expected empty error, got: {}",
            err
        );
    }

    #[test]
    fn scheme_only_fails() {
        let meta = LegalMetadata::new().with_license_url("https://");
        let err = meta.validate().unwrap_err();
        assert!(
            err.to_string().contains("must include an authority"),
            "Expected authority error, got: {}",
            err
        );
    }

    #[test]
    fn web_statement_validates() {
        let meta = LegalMetadata::new().with_web_statement_of_rights("not-a-url");
        let err = meta.validate().unwrap_err();
        assert!(err.to_string().contains("web_statement_of_rights"));
    }

    #[test]
    fn licensor_url_validates() {
        let meta = LegalMetadata::new().with_licensor_url("missing-scheme");
        let err = meta.validate().unwrap_err();
        assert!(err.to_string().contains("licensor_url"));
    }

    #[test]
    fn non_url_fields_not_affected() {
        let meta = LegalMetadata::new()
            .with_copyright_holder("Test")
            .with_creator("Author");
        assert!(meta.validate().is_ok());
    }
}

#[cfg(test)]
#[allow(deprecated)]
mod localized_text_tests {
    use super::*;

    #[test]
    fn new_defaults_to_x_default() {
        let lt = LocalizedText::new("All rights reserved");
        assert_eq!(lt.text(), "All rights reserved");
        assert_eq!(lt.lang(), "x-default");
    }

    #[test]
    fn with_lang_sets_language() {
        let lt = LocalizedText::with_lang("Tous droits réservés.", "fr");
        assert_eq!(lt.text(), "Tous droits réservés.");
        assert_eq!(lt.lang(), "fr");
    }

    #[test]
    fn from_string_uses_default_lang() {
        let lt: LocalizedText = "test".into();
        assert_eq!(lt.lang(), "x-default");
    }

    #[test]
    fn display_returns_text() {
        let lt = LocalizedText::new("hello");
        assert_eq!(format!("{}", lt), "hello");
    }

    #[test]
    fn usage_terms_localized_sets_both_fields() {
        let meta = LegalMetadata::new()
            .with_usage_terms_localized(LocalizedText::with_lang("Tous droits réservés.", "fr"));
        assert_eq!(meta.usage_terms(), Some("Tous droits réservés."));
        assert_eq!(meta.usage_terms_lang(), Some("fr"));
    }

    #[test]
    fn usage_terms_localized_from_string_uses_default_lang() {
        let meta = LegalMetadata::new().with_usage_terms_localized("All rights reserved");
        assert_eq!(meta.usage_terms(), Some("All rights reserved"));
        assert_eq!(meta.usage_terms_lang(), Some("x-default"));
    }

    #[test]
    fn usage_terms_plain_has_no_lang() {
        let meta = LegalMetadata::new().with_usage_terms("All rights reserved");
        assert_eq!(meta.usage_terms(), Some("All rights reserved"));
        assert_eq!(meta.usage_terms_lang(), None);
    }
}

#[cfg(test)]
#[allow(deprecated)]
mod date_validation_tests {
    use super::*;

    #[test]
    fn valid_date_only() {
        let meta = LegalMetadata::new().with_creation_date("2024-01-15");
        assert!(meta.validate().is_ok());
    }

    #[test]
    fn valid_datetime_utc() {
        let meta = LegalMetadata::new().with_notice_applied_at("2024-01-15T12:30:45Z");
        assert!(meta.validate().is_ok());
    }

    #[test]
    fn valid_datetime_offset() {
        let meta = LegalMetadata::new().with_metadata_date("2024-01-15T12:30:45+05:30");
        assert!(meta.validate().is_ok());
    }

    #[test]
    fn valid_datetime_negative_offset() {
        let meta = LegalMetadata::new().with_creation_date("2024-01-15T12:30:45-08:00");
        assert!(meta.validate().is_ok());
    }

    #[test]
    fn invalid_date_too_short() {
        let meta = LegalMetadata::new().with_creation_date("2024-01");
        let err = meta.validate().unwrap_err();
        assert!(
            err.to_string().contains("ISO 8601"),
            "Expected ISO 8601 error, got: {}",
            err
        );
    }

    #[test]
    fn invalid_date_wrong_separator() {
        let meta = LegalMetadata::new().with_creation_date("2024/01/15");
        let err = meta.validate().unwrap_err();
        assert!(err.to_string().contains("ISO 8601"));
    }

    #[test]
    fn invalid_datetime_missing_t() {
        let meta = LegalMetadata::new().with_notice_applied_at("2024-01-15 12:30:45Z");
        let err = meta.validate().unwrap_err();
        assert!(err.to_string().contains("ISO 8601"));
    }

    #[test]
    fn empty_date_fails() {
        let meta = LegalMetadata::new().with_creation_date("");
        let err = meta.validate().unwrap_err();
        assert!(err.to_string().contains("must not be empty"));
    }

    #[test]
    fn date_only_with_time_component_fails() {
        let meta = LegalMetadata::new().with_creation_date("2024-01-15T");
        let err = meta.validate().unwrap_err();
        assert!(err.to_string().contains("ISO 8601"));
    }

    #[test]
    fn all_date_fields_valid() {
        let meta = LegalMetadata::new()
            .with_creation_date("2024-01-15")
            .with_metadata_date("2024-01-15T12:30:45Z")
            .with_notice_applied_at("2024-01-15T12:30:45+05:30");
        assert!(meta.validate().is_ok());
    }
}