brain-brew-formats 1.0.0-alpha.8

Implementation package: YAML and CrowdAnki codecs for Brain Brew; no public Rust API commitment
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
use std::collections::{BTreeMap, BTreeSet};
use std::fmt;
use std::str::FromStr;

use crate::media;
use brain_brew_core::{
    AdapterIds, CanonicalDeck, CardTemplate, DeckPath, FieldDefinition, FieldImageReference,
    FieldValue, MediaReference, Note, NoteType, SemanticChangeKind, StableId, TombstoneAddress,
    Tombstones, ValidationReport, VariableRenderReport,
};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use unicode_normalization::UnicodeNormalization;

/// Normalized CrowdAnki export artifacts and adapter report data.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct CrowdAnkiExport {
    pub deck_json: String,
    pub omitted_tombstones: Vec<TombstoneAddress>,
}

/// Export a CanonicalDeck to deterministic normalized CrowdAnki `deck.json` bytes.
pub fn export_deck(deck: &CanonicalDeck) -> Result<CrowdAnkiExport, CrowdAnkiError> {
    deck.validate().map_err(CrowdAnkiError::Validation)?;
    media::validate_paths(deck).map_err(CrowdAnkiError::Media)?;
    let rendered_deck = deck
        .render_variables()
        .map_err(CrowdAnkiError::VariableRender)?;
    rendered_deck
        .validate()
        .map_err(CrowdAnkiError::Validation)?;
    validate_crowdanki_identity(CrowdAnkiIdentityInput::Export(&rendered_deck))?;
    let deck = &rendered_deck;

    let note_models = deck
        .note_types
        .values()
        .filter(|note_type| {
            deck.tombstones
                .blocking(&TombstoneAddress::NoteType {
                    note_type_id: note_type.id.clone(),
                })
                .is_none()
        })
        .map(|note_type| export_note_model(note_type, deck))
        .collect::<Result<Vec<_>, _>>()?;

    let note_type_uuids = deck
        .note_types
        .iter()
        .filter(|(id, _)| {
            deck.tombstones
                .blocking(&TombstoneAddress::NoteType {
                    note_type_id: (*id).clone(),
                })
                .is_none()
        })
        .map(|(id, note_type)| Ok((id.clone(), crowdanki_note_model_uuid(note_type)?)))
        .collect::<Result<BTreeMap<_, _>, CrowdAnkiError>>()?;

    let mut omitted_tombstones = Vec::new();
    let mut notes = Vec::new();
    for (id, note) in &deck.notes {
        let address = TombstoneAddress::Note {
            note_id: id.clone(),
        };
        if deck.tombstones.blocking(&address).is_some() {
            omitted_tombstones.push(address);
            continue;
        }
        notes.push(export_note(note, deck, &note_type_uuids)?);
    }

    let deck_config_uuid = crowdanki_deck_config_uuid(deck);
    let deck_json = CrowdAnkiDeckJson {
        type_: "Deck".to_owned(),
        children: Vec::new(),
        crowdanki_uuid: crowdanki_deck_uuid(deck),
        deck_config_uuid: deck_config_uuid.clone(),
        deck_configurations: vec![default_deck_config_json(
            &deck_config_uuid,
            &crowdanki_deck_config_name(deck),
        )],
        desc: deck.description.clone(),
        dyn_: 0,
        extend_new: 10,
        extend_rev: 50,
        media_files: deck
            .media
            .values()
            .filter(|media| {
                deck.tombstones
                    .blocking(&TombstoneAddress::MediaReference {
                        media_id: media.id.clone(),
                    })
                    .is_none()
            })
            .map(|media| media.path.clone())
            .collect::<Vec<_>>(),
        name: deck.name.clone(),
        note_models,
        notes,
    };

    let mut serialized = serde_json::to_string_pretty(&deck_json).map_err(CrowdAnkiError::Json)?;
    serialized.push('\n');

    Ok(CrowdAnkiExport {
        deck_json: serialized,
        omitted_tombstones,
    })
}

/// Plan a CrowdAnki import without creating Canonical Deck source.
///
/// The returned versioned artifact contains source-byte provenance and every generated identity.
/// It is intentionally separate from application: callers must validate the same source and
/// explicitly approve automatic decisions before any canonical deck is produced.
pub fn plan_import(input: &[u8]) -> Result<CrowdAnkiImportPlan, CrowdAnkiError> {
    let deck = parse_import_source(input)?;
    deck.import_plan(input)
}

/// A byte handoff from the adapter boundary. `path` must be one declared CrowdAnki
/// media path; bytes are deliberately not serialized into the review plan.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct CrowdAnkiImportMediaBytes {
    pub path: String,
    pub bytes: Vec<u8>,
}

/// Bind a reviewed import plan to the exact media bytes that will be published.
///
/// This is intentionally separate from [`plan_import`]: format parsing remains filesystem-free,
/// while the CLI reads every authorized source file exactly once and hands its bytes here.
pub fn plan_import_with_media(
    input: &[u8],
    supplied: &[CrowdAnkiImportMediaBytes],
) -> Result<CrowdAnkiImportPlan, CrowdAnkiError> {
    let mut plan = plan_import(input)?;
    plan.provenance.media = import_media_evidence(input, supplied)?;
    Ok(plan)
}

/// Apply a byte-bound reviewed plan and populate canonical media declarations with their
/// verified SHA-256 values.
pub fn apply_import_plan_with_media(
    input: &[u8],
    plan: &CrowdAnkiImportPlan,
    approve_automatic: bool,
    supplied: &[CrowdAnkiImportMediaBytes],
) -> Result<CanonicalDeck, CrowdAnkiError> {
    let evidence = import_media_evidence(input, supplied)?;
    if plan.provenance.media != evidence {
        return Err(CrowdAnkiError::Plan(
            "stale or mutated import plan: media byte evidence does not match".to_owned(),
        ));
    }
    let source = parse_import_source(input)?;
    let expected = plan_import_with_media(input, supplied)?;
    let selections = plan.validate_against(&expected, approve_automatic)?;
    let mut deck = source.into_deck_with_ids(&selections)?;
    for declaration in deck.media.values_mut() {
        let evidence = evidence
            .iter()
            .find(|evidence| evidence.path == declaration.path)
            .expect("validated media evidence covers every declaration");
        declaration.sha256 = evidence.sha256.clone();
    }
    Ok(deck)
}

/// Return canonical, safe CrowdAnki media declarations and their source locations.
pub fn import_media_references(
    input: &[u8],
) -> Result<Vec<CrowdAnkiImportMediaReference>, CrowdAnkiError> {
    parse_import_source(input)?.import_media_references()
}

/// Apply a reviewed import plan to exactly the CrowdAnki source bytes it describes.
///
/// `approve_automatic` is the explicit review acknowledgement for deterministic automatic
/// suggestions. Entries requiring an override remain fail-closed until the plan selects one.
pub fn apply_import_plan(
    input: &[u8],
    plan: &CrowdAnkiImportPlan,
    approve_automatic: bool,
) -> Result<CanonicalDeck, CrowdAnkiError> {
    let deck = parse_import_source(input)?;
    let expected = deck.import_plan(input)?;
    let selections = plan.validate_against(&expected, approve_automatic)?;
    deck.into_deck_with_ids(&selections)
}

fn parse_import_source(input: &[u8]) -> Result<CrowdAnkiDeckJson, CrowdAnkiError> {
    let text = std::str::from_utf8(input)
        .map_err(|error| CrowdAnkiError::Plan(format!("CrowdAnki source is not UTF-8: {error}")))?;
    let mut deserializer = serde_json::Deserializer::from_str(text);
    serde_path_to_error::deserialize(&mut deserializer).map_err(|error| CrowdAnkiError::JsonPath {
        path: json_path(error.path()),
        message: error.inner().to_string(),
    })
}

fn import_media_evidence(
    input: &[u8],
    supplied: &[CrowdAnkiImportMediaBytes],
) -> Result<Vec<CrowdAnkiImportMediaEvidence>, CrowdAnkiError> {
    let references = import_media_references(input)?;
    let expected = references
        .iter()
        .map(|reference| reference.path.as_str())
        .collect::<BTreeSet<_>>();
    let deck = parse_import_source(input)?;
    let used = deck.content_media_paths();
    let declared = expected
        .iter()
        .map(|path| (*path).to_owned())
        .collect::<BTreeSet<_>>();
    if let Some(path) = used.difference(&declared).next() {
        return Err(CrowdAnkiError::Plan(format!(
            "CrowdAnki content references undeclared media path {path:?}"
        )));
    }
    if let Some(path) = declared.difference(&used).next() {
        return Err(CrowdAnkiError::Plan(format!(
            "unused supplied CrowdAnki media declaration {path:?}; remove it or use it in supported content"
        )));
    }
    let mut supplied_by_path = BTreeMap::new();
    for asset in supplied {
        if !expected.contains(asset.path.as_str()) {
            return Err(CrowdAnkiError::Plan(format!(
                "unused supplied CrowdAnki media bytes for {:?}; bytes must name one declared media path",
                asset.path
            )));
        }
        if supplied_by_path
            .insert(asset.path.as_str(), asset)
            .is_some()
        {
            return Err(CrowdAnkiError::Plan(format!(
                "duplicate supplied CrowdAnki media bytes for {:?}",
                asset.path
            )));
        }
    }
    references
        .into_iter()
        .map(|reference| {
            let asset = supplied_by_path
                .get(reference.path.as_str())
                .ok_or_else(|| {
                    CrowdAnkiError::Plan(format!(
                        "missing supplied CrowdAnki media bytes for {} {:?}",
                        reference.source_path, reference.path
                    ))
                })?;
            Ok(CrowdAnkiImportMediaEvidence {
                source_path: reference.source_path,
                path: reference.path,
                sha256: format!("{:x}", Sha256::digest(&asset.bytes)),
                bytes: asset.bytes.len() as u64,
            })
        })
        .collect()
}

/// Named canonical equivalence profile for a CrowdAnki export/import round trip.
///
/// Exact canonical diff is never weakened. Callers explicitly project both sides with this
/// profile, then use [`CanonicalDeck::semantic_diff`] as the exact oracle.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct CrowdAnkiRoundTripProfile {
    pub name: &'static str,
    pub losses: &'static [CrowdAnkiRoundTripLoss],
}

/// Canonical information CrowdAnki cannot preserve through `deck.json`.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum CrowdAnkiRoundTripLoss {
    SourceVariablesAreRendered,
    StructuredFieldRepresentationsAreLowered,
    FieldMessagePatternsAreSourceOnly,
    MediaHashesAreNotStored,
    TypedTombstonesBecomePhysicalOmissions,
    UnsupportedAdapterIdsAreDiscarded,
    StableIdsAreRegeneratedFromAdapterContent,
}

pub const CROWDANKI_ROUND_TRIP_PROFILE: CrowdAnkiRoundTripProfile = CrowdAnkiRoundTripProfile {
    name: "crowdanki-export-import-v1",
    losses: &[
        CrowdAnkiRoundTripLoss::SourceVariablesAreRendered,
        CrowdAnkiRoundTripLoss::StructuredFieldRepresentationsAreLowered,
        CrowdAnkiRoundTripLoss::FieldMessagePatternsAreSourceOnly,
        CrowdAnkiRoundTripLoss::MediaHashesAreNotStored,
        CrowdAnkiRoundTripLoss::TypedTombstonesBecomePhysicalOmissions,
        CrowdAnkiRoundTripLoss::UnsupportedAdapterIdsAreDiscarded,
        CrowdAnkiRoundTripLoss::StableIdsAreRegeneratedFromAdapterContent,
    ],
};

/// The outcome of a successful canonical-to-CrowdAnki comparison.
///
/// `NotProven` is deliberately distinct from equality: a reference-only `deck.json` contains
/// media names but no bytes or hashes, and therefore cannot establish media-byte equivalence.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct CrowdAnkiEquivalenceSuccess {
    pub profile: &'static str,
    pub media_bytes: CrowdAnkiMediaByteProof,
}

/// Whether the successful comparison also checked media bytes against canonical hashes.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum CrowdAnkiMediaByteProof {
    NotProven,
    Verified,
}

/// One complete, typed difference found by the normalized CrowdAnki equivalence oracle.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct CrowdAnkiEquivalenceDifference {
    /// The complete semantic-diff canonical path, after the named round-trip projection.
    pub canonical_path: String,
    /// The exact CrowdAnki JSON location when the differing actual value has one.
    pub crowdanki_path: Option<String>,
    pub category: CrowdAnkiEquivalenceDifferenceCategory,
    pub expected: Option<String>,
    pub actual: Option<String>,
}

/// Classification of an oracle difference.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum CrowdAnkiEquivalenceDifferenceCategory {
    Added,
    Removed,
    Modified,
    Tombstoned,
    MediaBytes,
}

/// All semantic differences from one canonical-to-CrowdAnki comparison.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct CrowdAnkiEquivalenceReport {
    pub profile: &'static str,
    pub differences: Vec<CrowdAnkiEquivalenceDifference>,
}

/// Fail-closed result from the normalized CrowdAnki equivalence oracle.
#[derive(Debug)]
pub enum CrowdAnkiEquivalenceError {
    /// The source uses a CrowdAnki property that Brain Brew does not model.
    Unsupported(CrowdAnkiError),
    /// The canonical source cannot be projected through the named adapter profile.
    Canonical(CrowdAnkiError),
    /// A canonical media hash exists but only reference-only CrowdAnki input was supplied.
    MediaBytesRequired {
        canonical_paths: Vec<String>,
        crowdanki_paths: Vec<String>,
    },
    /// Both states are supported but differ after the documented projection.
    Differences(CrowdAnkiEquivalenceReport),
}

impl fmt::Display for CrowdAnkiEquivalenceError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Unsupported(error) => {
                write!(f, "unsupported CrowdAnki equivalence input: {error}")
            }
            Self::Canonical(error) => write!(f, "canonical CrowdAnki projection failed: {error}"),
            Self::MediaBytesRequired {
                canonical_paths,
                crowdanki_paths,
            } => write!(
                f,
                "CrowdAnki reference-only input cannot prove media bytes for canonical paths {:?}; supply bytes for {:?}",
                canonical_paths, crowdanki_paths
            ),
            Self::Differences(report) => write!(
                f,
                "{} CrowdAnki equivalence difference(s) under {}",
                report.differences.len(),
                report.profile
            ),
        }
    }
}

impl std::error::Error for CrowdAnkiEquivalenceError {}

/// Compare canonical state to CrowdAnki JSON with the only normalization permitted by
/// [`CROWDANKI_ROUND_TRIP_PROFILE`]. This is a typed adapter oracle, not a JSON-tree subset
/// comparison. Unsupported JSON is rejected before comparison.
///
/// Passing media bytes binds them through the import plan and compares every non-empty canonical
/// SHA-256 declaration. Omitting bytes is accepted only when canonical media hashes are empty;
/// success then explicitly returns [`CrowdAnkiMediaByteProof::NotProven`].
pub fn canonical_crowdanki_equivalence(
    canonical: &CanonicalDeck,
    input: &[u8],
    media_bytes: Option<&[CrowdAnkiImportMediaBytes]>,
) -> Result<CrowdAnkiEquivalenceSuccess, CrowdAnkiEquivalenceError> {
    let source = parse_import_source(input).map_err(CrowdAnkiEquivalenceError::Unsupported)?;
    let hashed_media = canonical
        .media
        .values()
        .filter(|media| !media.sha256.is_empty())
        .collect::<Vec<_>>();
    if media_bytes.is_none() && !hashed_media.is_empty() {
        return Err(CrowdAnkiEquivalenceError::MediaBytesRequired {
            canonical_paths: hashed_media
                .iter()
                .map(|media| format!("media.{}.sha256", media.id))
                .collect(),
            crowdanki_paths: hashed_media
                .iter()
                .map(|media| format!("$.media_files[path={}]", json_path_label(&media.path)))
                .collect(),
        });
    }

    let imported = match media_bytes {
        Some(bytes) => {
            let plan = plan_import_with_media(input, bytes)
                .map_err(CrowdAnkiEquivalenceError::Unsupported)?;
            apply_import_plan_with_media(input, &plan, true, bytes)
                .map_err(CrowdAnkiEquivalenceError::Unsupported)?
        }
        None => {
            let plan = source
                .import_plan(input)
                .map_err(CrowdAnkiEquivalenceError::Unsupported)?;
            apply_import_plan(input, &plan, true).map_err(CrowdAnkiEquivalenceError::Unsupported)?
        }
    };
    let expected = project_deck_for_crowdanki_round_trip(canonical)
        .map_err(CrowdAnkiEquivalenceError::Canonical)?;
    let actual = project_deck_for_crowdanki_round_trip(&imported)
        .map_err(CrowdAnkiEquivalenceError::Unsupported)?;

    let mut differences = expected
        .semantic_diff(&actual)
        .changes
        .into_iter()
        .map(|change| CrowdAnkiEquivalenceDifference {
            canonical_path: change.path.clone(),
            crowdanki_path: crowdanki_source_path(&change.path, &actual, &source),
            category: match change.kind {
                SemanticChangeKind::Added => CrowdAnkiEquivalenceDifferenceCategory::Added,
                SemanticChangeKind::Removed => CrowdAnkiEquivalenceDifferenceCategory::Removed,
                SemanticChangeKind::Modified => CrowdAnkiEquivalenceDifferenceCategory::Modified,
                SemanticChangeKind::Tombstoned => {
                    CrowdAnkiEquivalenceDifferenceCategory::Tombstoned
                }
            },
            expected: change.before,
            actual: change.after,
        })
        .collect::<Vec<_>>();

    if media_bytes.is_some() {
        differences.extend(media_byte_differences(canonical, &imported, &source));
    }
    if !differences.is_empty() {
        return Err(CrowdAnkiEquivalenceError::Differences(
            CrowdAnkiEquivalenceReport {
                profile: CROWDANKI_ROUND_TRIP_PROFILE.name,
                differences,
            },
        ));
    }

    Ok(CrowdAnkiEquivalenceSuccess {
        profile: CROWDANKI_ROUND_TRIP_PROFILE.name,
        media_bytes: if media_bytes.is_some()
            && !canonical.media.is_empty()
            && canonical
                .media
                .values()
                .all(|media| !media.sha256.is_empty())
        {
            CrowdAnkiMediaByteProof::Verified
        } else {
            CrowdAnkiMediaByteProof::NotProven
        },
    })
}

fn media_byte_differences(
    canonical: &CanonicalDeck,
    imported: &CanonicalDeck,
    source: &CrowdAnkiDeckJson,
) -> Vec<CrowdAnkiEquivalenceDifference> {
    canonical
        .media
        .values()
        .filter(|media| !media.sha256.is_empty())
        .filter_map(|expected| {
            let actual = imported
                .media
                .values()
                .find(|media| media.path == expected.path);
            let actual_hash = actual.map(|media| media.sha256.as_str());
            (actual_hash != Some(expected.sha256.as_str())).then(|| {
                CrowdAnkiEquivalenceDifference {
                    canonical_path: format!("media.{}.sha256", expected.id),
                    crowdanki_path: source
                        .media_files
                        .iter()
                        .position(|path| path == &expected.path)
                        .map(|index| format!("$.media_files[{index}]")),
                    category: CrowdAnkiEquivalenceDifferenceCategory::MediaBytes,
                    expected: Some(expected.sha256.clone()),
                    actual: actual_hash.map(str::to_owned),
                }
            })
        })
        .collect()
}

fn crowdanki_source_path(
    canonical_path: &str,
    actual: &CanonicalDeck,
    source: &CrowdAnkiDeckJson,
) -> Option<String> {
    let path = DeckPath::from_str(canonical_path).ok()?;
    match path {
        DeckPath::DeckName => Some("$.name".to_owned()),
        DeckPath::DeckDescription => Some("$.desc".to_owned()),
        DeckPath::DeckAdapterId { key } => match key.as_str() {
            "crowdanki:uuid" => Some("$.crowdanki_uuid".to_owned()),
            "crowdanki:deck_config_uuid" => Some("$.deck_config_uuid".to_owned()),
            "crowdanki:deck_config_name" => Some("$.deck_configurations[0].name".to_owned()),
            _ => None,
        },
        DeckPath::NoteType { note_type_id }
        | DeckPath::NoteTypeId { note_type_id }
        | DeckPath::NoteTypeName { note_type_id }
        | DeckPath::NoteTypeStyling { note_type_id }
        | DeckPath::NoteTypeFields { note_type_id }
        | DeckPath::NoteTypeCardTemplates { note_type_id }
        | DeckPath::NoteTypeAdapterIds { note_type_id } => {
            note_model_path(actual, source, &note_type_id)
        }
        DeckPath::NoteTypeAdapterId { note_type_id, key } => {
            let index = note_model_index(actual, source, &note_type_id)?;
            (key == "crowdanki:uuid").then(|| format!("$.note_models[{index}].crowdanki_uuid"))
        }
        DeckPath::NoteTypeField {
            note_type_id,
            field_id,
        }
        | DeckPath::NoteTypeFieldId {
            note_type_id,
            field_id,
        }
        | DeckPath::NoteTypeFieldName {
            note_type_id,
            field_id,
        }
        | DeckPath::NoteTypeFieldRtl {
            note_type_id,
            field_id,
        } => {
            let (model, field) = note_field_index(actual, source, &note_type_id, &field_id)?;
            Some(format!("$.note_models[{model}].flds[{field}]"))
        }
        DeckPath::NoteTypeCardTemplate {
            note_type_id,
            template_id,
        }
        | DeckPath::NoteTypeCardTemplateId {
            note_type_id,
            template_id,
        }
        | DeckPath::NoteTypeCardTemplateName {
            note_type_id,
            template_id,
        }
        | DeckPath::NoteTypeCardTemplateQuestionFormat {
            note_type_id,
            template_id,
        }
        | DeckPath::NoteTypeCardTemplateAnswerFormat {
            note_type_id,
            template_id,
        }
        | DeckPath::NoteTypeCardTemplateAdapterIds {
            note_type_id,
            template_id,
        } => {
            let (model, template) =
                note_template_index(actual, source, &note_type_id, &template_id)?;
            Some(format!("$.note_models[{model}].tmpls[{template}]"))
        }
        DeckPath::Note { note_id }
        | DeckPath::NoteId { note_id }
        | DeckPath::NoteNoteTypeId { note_id }
        | DeckPath::NoteTags { note_id }
        | DeckPath::NoteAdapterIds { note_id } => note_path(actual, source, &note_id),
        DeckPath::NoteAdapterId { note_id, key } => {
            let index = note_index(actual, source, &note_id)?;
            (key == "crowdanki:guid").then(|| format!("$.notes[{index}].guid"))
        }
        DeckPath::NoteField { note_id, field_id }
        | DeckPath::NoteFieldImage {
            note_id, field_id, ..
        }
        | DeckPath::NoteFieldMessage { note_id, field_id }
        | DeckPath::NoteFieldMessageComponent {
            note_id, field_id, ..
        }
        | DeckPath::NoteFieldMessageFormat { note_id, field_id }
        | DeckPath::NoteFieldMessageVariable {
            note_id, field_id, ..
        } => {
            let note_index = note_index(actual, source, &note_id)?;
            let note = actual.notes.get(&note_id)?;
            let note_type = actual.note_types.get(&note.note_type_id)?;
            let field_index = note_type
                .fields
                .iter()
                .position(|field| field.id == field_id)?;
            Some(format!("$.notes[{note_index}].fields[{field_index}]"))
        }
        DeckPath::NoteTag { note_id, .. } => {
            note_path(actual, source, &note_id).map(|path| format!("{path}.tags"))
        }
        DeckPath::Media { media_id }
        | DeckPath::MediaId { media_id }
        | DeckPath::MediaPath { media_id }
        | DeckPath::MediaSha256 { media_id } => actual
            .media
            .get(&media_id)
            .and_then(|media| {
                source
                    .media_files
                    .iter()
                    .position(|path| path == &media.path)
            })
            .map(|index| format!("$.media_files[{index}]")),
        _ => None,
    }
}

fn note_model_index(
    actual: &CanonicalDeck,
    source: &CrowdAnkiDeckJson,
    note_type_id: &StableId,
) -> Option<usize> {
    let uuid = actual
        .note_types
        .get(note_type_id)?
        .adapter_ids
        .get("crowdanki:uuid")?;
    source
        .note_models
        .iter()
        .position(|model| model.crowdanki_uuid == uuid)
}

fn note_model_path(
    actual: &CanonicalDeck,
    source: &CrowdAnkiDeckJson,
    note_type_id: &StableId,
) -> Option<String> {
    note_model_index(actual, source, note_type_id).map(|index| format!("$.note_models[{index}]"))
}

fn note_field_index(
    actual: &CanonicalDeck,
    source: &CrowdAnkiDeckJson,
    note_type_id: &StableId,
    field_id: &StableId,
) -> Option<(usize, usize)> {
    let model = note_model_index(actual, source, note_type_id)?;
    let field = actual
        .note_types
        .get(note_type_id)?
        .fields
        .iter()
        .position(|field| &field.id == field_id)?;
    Some((model, field))
}

fn note_template_index(
    actual: &CanonicalDeck,
    source: &CrowdAnkiDeckJson,
    note_type_id: &StableId,
    template_id: &StableId,
) -> Option<(usize, usize)> {
    let model = note_model_index(actual, source, note_type_id)?;
    let template = actual
        .note_types
        .get(note_type_id)?
        .card_templates
        .iter()
        .position(|template| &template.id == template_id)?;
    Some((model, template))
}

fn note_index(
    actual: &CanonicalDeck,
    source: &CrowdAnkiDeckJson,
    note_id: &StableId,
) -> Option<usize> {
    let guid = actual
        .notes
        .get(note_id)?
        .adapter_ids
        .get("crowdanki:guid")?;
    source.notes.iter().position(|note| note.guid == guid)
}

fn note_path(
    actual: &CanonicalDeck,
    source: &CrowdAnkiDeckJson,
    note_id: &StableId,
) -> Option<String> {
    note_index(actual, source, note_id).map(|index| format!("$.notes[{index}]"))
}

/// Project a canonical deck to the exact semantics representable by a CrowdAnki round trip.
///
/// Stable IDs are normalized with the import suggestion algorithm because `deck.json` does not
/// store canonical identity. Colliding suggestions fail explicitly instead of being equated.
/// Adapter-visible fallback UUIDs/GUIDs are materialized before this normalization.
pub fn project_deck_for_crowdanki_round_trip(
    deck: &CanonicalDeck,
) -> Result<CanonicalDeck, CrowdAnkiError> {
    deck.validate().map_err(CrowdAnkiError::Validation)?;
    let mut projected = deck
        .render_variables()
        .map_err(CrowdAnkiError::VariableRender)?;
    let tombstones = projected.tombstones.clone();

    projected.note_types.retain(|note_type_id, _| {
        tombstones
            .blocking(&TombstoneAddress::NoteType {
                note_type_id: note_type_id.clone(),
            })
            .is_none()
    });
    for (note_type_id, note_type) in &mut projected.note_types {
        note_type.fields.retain(|field| {
            tombstones
                .blocking(&TombstoneAddress::FieldDefinition {
                    note_type_id: note_type_id.clone(),
                    field_id: field.id.clone(),
                })
                .is_none()
        });
        note_type.card_templates.retain(|template| {
            tombstones
                .blocking(&TombstoneAddress::CardTemplate {
                    note_type_id: note_type_id.clone(),
                    template_id: template.id.clone(),
                })
                .is_none()
        });
    }
    projected.notes.retain(|note_id, _| {
        tombstones
            .blocking(&TombstoneAddress::Note {
                note_id: note_id.clone(),
            })
            .is_none()
    });
    for note in projected.notes.values_mut() {
        if let Some(note_type) = projected.note_types.get(&note.note_type_id) {
            let exported_fields = note_type
                .fields
                .iter()
                .map(|field| field.id.clone())
                .collect::<BTreeSet<_>>();
            note.fields
                .retain(|field_id, _| exported_fields.contains(field_id));
        }
    }
    projected.media.retain(|media_id, _| {
        tombstones
            .blocking(&TombstoneAddress::MediaReference {
                media_id: media_id.clone(),
            })
            .is_none()
    });
    validate_crowdanki_identity(CrowdAnkiIdentityInput::Export(&projected))?;

    // Materialize adapter-visible fallback identities before canonical stable IDs are
    // normalized to the IDs import will suggest.
    projected.adapter_ids = projected_deck_adapter_ids(&projected);
    for note_type in projected.note_types.values_mut() {
        note_type.adapter_ids = projected_note_type_adapter_ids(note_type)?;
    }
    for note in projected.notes.values_mut() {
        note.adapter_ids = projected_note_adapter_ids(note);
    }

    normalize_projected_stable_ids(&mut projected)?;
    projected.variables.clear();
    for note_type in projected.note_types.values_mut() {
        note_type.variables.clear();
        for field in &mut note_type.fields {
            field.message_pattern = None;
        }
        for template in &mut note_type.card_templates {
            template.variables.clear();
            template.adapter_ids = AdapterIds::new();
        }
    }
    for note in projected.notes.values_mut() {
        note.variables.clear();
    }
    for media in projected.media.values_mut() {
        media.sha256.clear();
    }
    projected.tombstones = Tombstones::default();
    Ok(projected)
}

fn normalize_projected_stable_ids(deck: &mut CanonicalDeck) -> Result<(), CrowdAnkiError> {
    deck.id = prefixed_stable_id("deck", &deck.name)?;

    let mut note_type_ids = BTreeMap::new();
    let mut field_ids = BTreeMap::<StableId, BTreeMap<StableId, StableId>>::new();
    let mut normalized_note_types = BTreeMap::new();
    for (old_note_type_id, mut note_type) in std::mem::take(&mut deck.note_types) {
        let new_note_type_id = prefixed_stable_id("note-type", &note_type.name)?;
        let mut note_type_field_ids = BTreeMap::new();
        for field in &mut note_type.fields {
            let old_field_id = field.id.clone();
            field.id = prefixed_stable_id("field", &field.name)?;
            note_type_field_ids.insert(old_field_id, field.id.clone());
        }
        for template in &mut note_type.card_templates {
            template.id = prefixed_stable_id("template", &template.name)?;
        }
        note_type.id = new_note_type_id.clone();
        if normalized_note_types
            .insert(new_note_type_id.clone(), note_type)
            .is_some()
        {
            return Err(CrowdAnkiError::Unsupported(format!(
                "{} profile generated duplicate note type stable ID {}",
                CROWDANKI_ROUND_TRIP_PROFILE.name, new_note_type_id
            )));
        }
        field_ids.insert(old_note_type_id.clone(), note_type_field_ids);
        note_type_ids.insert(old_note_type_id, new_note_type_id);
    }
    deck.note_types = normalized_note_types;

    let mut normalized_note_values = Vec::new();
    let mut note_identities = Vec::new();
    for (_old_note_id, mut note) in std::mem::take(&mut deck.notes) {
        let old_note_type_id = note.note_type_id.clone();
        let new_note_type_id = note_type_ids.get(&old_note_type_id).ok_or_else(|| {
            CrowdAnkiError::Unsupported(format!(
                "{} profile cannot map note type {}",
                CROWDANKI_ROUND_TRIP_PROFILE.name, old_note_type_id
            ))
        })?;
        let note_type = deck
            .note_types
            .get(new_note_type_id)
            .expect("normalized note type ID was inserted");
        let mapping = field_ids
            .get(&old_note_type_id)
            .expect("normalized field IDs were recorded");
        note.fields = note
            .fields
            .iter()
            .map(|(old_field_id, value)| {
                mapping
                    .get(old_field_id)
                    .cloned()
                    .map(|field_id| (field_id, value.clone()))
                    .ok_or_else(|| {
                        CrowdAnkiError::Unsupported(format!(
                            "{} profile cannot map field {}",
                            CROWDANKI_ROUND_TRIP_PROFILE.name, old_field_id
                        ))
                    })
            })
            .collect::<Result<BTreeMap<_, _>, _>>()?
            .into();
        note.note_type_id = new_note_type_id.clone();
        let first_field = note_type
            .fields
            .first()
            .and_then(|field| note.fields.get(&field.id))
            .and_then(FieldValue::as_scalar)
            .unwrap_or_default()
            .to_owned();
        let source_guid = note
            .adapter_ids
            .get("crowdanki:guid")
            .expect("exported notes have an effective GUID")
            .to_owned();
        note_identities.push(ImportedNoteIdentity {
            first_field,
            source_guid,
        });
        normalized_note_values.push(note);
    }
    let mut normalized_notes = BTreeMap::new();
    for (mut note, id) in normalized_note_values
        .into_iter()
        .zip(suggest_imported_note_stable_ids(&note_identities)?)
    {
        note.id = id.clone();
        if normalized_notes.insert(id, note).is_some() {
            return Err(CrowdAnkiError::Unsupported(format!(
                "{} profile generated duplicate note stable ID",
                CROWDANKI_ROUND_TRIP_PROFILE.name
            )));
        }
    }
    deck.notes = normalized_notes;

    let mut normalized_media = BTreeMap::new();
    for (_old_media_id, mut media) in std::mem::take(&mut deck.media) {
        media.id = prefixed_stable_id("media", &media.path)?;
        if normalized_media.insert(media.id.clone(), media).is_some() {
            return Err(CrowdAnkiError::Unsupported(format!(
                "{} profile generated duplicate media stable ID",
                CROWDANKI_ROUND_TRIP_PROFILE.name
            )));
        }
    }
    deck.media = normalized_media;
    Ok(())
}

fn projected_deck_adapter_ids(deck: &CanonicalDeck) -> AdapterIds {
    let mut ids = AdapterIds::new();
    ids.insert("crowdanki:uuid", crowdanki_deck_uuid(deck));
    ids.insert(
        "crowdanki:deck_config_uuid",
        crowdanki_deck_config_uuid(deck),
    );
    ids.insert(
        "crowdanki:deck_config_name",
        crowdanki_deck_config_name(deck),
    );
    ids
}

fn projected_note_type_adapter_ids(note_type: &NoteType) -> Result<AdapterIds, CrowdAnkiError> {
    let mut ids = AdapterIds::new();
    ids.insert("crowdanki:uuid", crowdanki_note_model_uuid(note_type)?);
    Ok(ids)
}

fn projected_note_adapter_ids(note: &Note) -> AdapterIds {
    let mut ids = AdapterIds::new();
    ids.insert("crowdanki:guid", crowdanki_note_guid(note));
    ids
}

fn json_path(path: &serde_path_to_error::Path) -> String {
    let path = path.to_string();
    if path.is_empty() || path == "." {
        "$".to_owned()
    } else if path.starts_with('[') {
        format!("${path}")
    } else {
        format!("$.{path}")
    }
}

/// Options for comparing generated CrowdAnki JSON with an expected oracle.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct CrowdAnkiParityOptions {
    /// JSON path globs explicitly allowed to differ.
    pub allowed_path_globs: BTreeSet<String>,
}

/// A CrowdAnki parity comparison failure report.
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct CrowdAnkiParityReport {
    pub differences: Vec<CrowdAnkiParityDifference>,
}

/// One exact JSON difference between expected and actual CrowdAnki output.
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct CrowdAnkiParityDifference {
    pub path: String,
    pub kind: CrowdAnkiParityDifferenceKind,
    pub expected: Option<serde_json::Value>,
    pub actual: Option<serde_json::Value>,
}

/// The broad shape of a CrowdAnki JSON parity difference.
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum CrowdAnkiParityDifferenceKind {
    MissingActual,
    ExtraActual,
    ValueMismatch,
    LengthMismatch,
}

/// Compare two CrowdAnki `deck.json` values exactly, with only explicit path allowlists.
pub fn compare_deck_json_values(
    expected: &serde_json::Value,
    actual: &serde_json::Value,
    options: &CrowdAnkiParityOptions,
) -> Result<(), CrowdAnkiParityReport> {
    let mut differences = Vec::new();
    compare_json_value(expected, actual, "$", options, &mut differences);
    if differences.is_empty() {
        Ok(())
    } else {
        Err(CrowdAnkiParityReport { differences })
    }
}

impl fmt::Display for CrowdAnkiParityReport {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        writeln!(f, "{} CrowdAnki JSON difference(s)", self.differences.len())?;
        let grouped_paths = repeated_difference_groups(&self.differences);
        if !grouped_paths.is_empty() {
            writeln!(f, "Repeated differences:")?;
            for group in &grouped_paths {
                writeln!(
                    f,
                    "{} × {} ({:?}): expected {}, actual {}",
                    group.count,
                    group.path_pattern,
                    group.kind,
                    json_value_summary(group.expected.as_ref()),
                    json_value_summary(group.actual.as_ref())
                )?;
            }
        }
        let grouped_patterns = grouped_paths
            .iter()
            .map(|group| group.path_pattern.as_str())
            .collect::<BTreeSet<_>>();
        let mut shown = 0;
        for difference in &self.differences {
            if grouped_patterns.contains(normalize_repeated_path(&difference.path).as_str()) {
                continue;
            }
            if shown >= 20 {
                break;
            }
            writeln!(
                f,
                "{} ({:?}): expected {}, actual {}",
                difference.path,
                difference.kind,
                json_value_summary(difference.expected.as_ref()),
                json_value_summary(difference.actual.as_ref())
            )?;
            shown += 1;
        }
        let ungrouped_count = self
            .differences
            .iter()
            .filter(|difference| {
                !grouped_patterns.contains(normalize_repeated_path(&difference.path).as_str())
            })
            .count();
        if ungrouped_count > shown {
            writeln!(f, "... {} more", ungrouped_count - shown)?;
        }
        Ok(())
    }
}

struct RepeatedDifferenceGroup {
    path_pattern: String,
    kind: CrowdAnkiParityDifferenceKind,
    expected: Option<serde_json::Value>,
    actual: Option<serde_json::Value>,
    count: usize,
}

fn repeated_difference_groups(
    differences: &[CrowdAnkiParityDifference],
) -> Vec<RepeatedDifferenceGroup> {
    let mut groups = BTreeMap::<(String, String, String, String), RepeatedDifferenceGroup>::new();
    for difference in differences {
        let path_pattern = normalize_repeated_path(&difference.path);
        if path_pattern == difference.path {
            continue;
        }
        let key = (
            path_pattern.clone(),
            format!("{:?}", difference.kind),
            json_value_summary(difference.expected.as_ref()),
            json_value_summary(difference.actual.as_ref()),
        );
        groups
            .entry(key)
            .and_modify(|group| group.count += 1)
            .or_insert_with(|| RepeatedDifferenceGroup {
                path_pattern,
                kind: difference.kind.clone(),
                expected: difference.expected.clone(),
                actual: difference.actual.clone(),
                count: 1,
            });
    }

    groups
        .into_values()
        .filter(|group| group.count > 1)
        .collect()
}

fn normalize_repeated_path(path: &str) -> String {
    let mut normalized = String::new();
    let mut chars = path.chars().peekable();
    while let Some(ch) = chars.next() {
        if ch != '[' {
            normalized.push(ch);
            continue;
        }

        let mut bracket = String::from("[");
        for bracket_ch in chars.by_ref() {
            bracket.push(bracket_ch);
            if bracket_ch == ']' {
                break;
            }
        }
        if bracket
            .chars()
            .skip(1)
            .all(|ch| ch.is_ascii_digit() || ch == ']')
            || bracket.contains('=')
        {
            normalized.push_str("[*]");
        } else {
            normalized.push_str(&bracket);
        }
    }
    normalized
}

fn compare_json_value(
    expected: &serde_json::Value,
    actual: &serde_json::Value,
    path: &str,
    options: &CrowdAnkiParityOptions,
    differences: &mut Vec<CrowdAnkiParityDifference>,
) {
    if expected == actual || is_allowed_parity_path(options, path) {
        return;
    }

    match (expected, actual) {
        (serde_json::Value::Object(expected), serde_json::Value::Object(actual)) => {
            let keys = expected
                .keys()
                .chain(actual.keys())
                .collect::<BTreeSet<_>>();
            for key in keys {
                let child_path = json_path_key(path, key);
                if is_allowed_parity_path(options, &child_path) {
                    continue;
                }
                match (expected.get(key), actual.get(key)) {
                    (Some(expected), Some(actual)) => {
                        compare_json_value(expected, actual, &child_path, options, differences);
                    }
                    (Some(expected), None) => differences.push(CrowdAnkiParityDifference {
                        path: child_path,
                        kind: CrowdAnkiParityDifferenceKind::MissingActual,
                        expected: Some(expected.clone()),
                        actual: None,
                    }),
                    (None, Some(actual)) => differences.push(CrowdAnkiParityDifference {
                        path: child_path,
                        kind: CrowdAnkiParityDifferenceKind::ExtraActual,
                        expected: None,
                        actual: Some(actual.clone()),
                    }),
                    (None, None) => {}
                }
            }
        }
        (serde_json::Value::Array(expected), serde_json::Value::Array(actual)) => {
            if compare_json_array_by_identity(expected, actual, path, options, differences) {
                return;
            }
            for index in 0..expected.len().min(actual.len()) {
                let child_path = format!("{path}[{index}]");
                compare_json_value(
                    &expected[index],
                    &actual[index],
                    &child_path,
                    options,
                    differences,
                );
            }
            if expected.len() != actual.len() {
                let length_path = format!("{path}.length");
                if !is_allowed_parity_path(options, &length_path) {
                    differences.push(CrowdAnkiParityDifference {
                        path: length_path,
                        kind: CrowdAnkiParityDifferenceKind::LengthMismatch,
                        expected: Some(serde_json::json!(expected.len())),
                        actual: Some(serde_json::json!(actual.len())),
                    });
                }
            }
            for (index, value) in expected.iter().enumerate().skip(actual.len()) {
                let child_path = format!("{path}[{index}]");
                if !is_allowed_parity_path(options, &child_path) {
                    differences.push(CrowdAnkiParityDifference {
                        path: child_path,
                        kind: CrowdAnkiParityDifferenceKind::MissingActual,
                        expected: Some(value.clone()),
                        actual: None,
                    });
                }
            }
            for (index, value) in actual.iter().enumerate().skip(expected.len()) {
                let child_path = format!("{path}[{index}]");
                if !is_allowed_parity_path(options, &child_path) {
                    differences.push(CrowdAnkiParityDifference {
                        path: child_path,
                        kind: CrowdAnkiParityDifferenceKind::ExtraActual,
                        expected: None,
                        actual: Some(value.clone()),
                    });
                }
            }
        }
        _ => differences.push(CrowdAnkiParityDifference {
            path: path.to_owned(),
            kind: CrowdAnkiParityDifferenceKind::ValueMismatch,
            expected: Some(expected.clone()),
            actual: Some(actual.clone()),
        }),
    }
}

fn compare_json_array_by_identity(
    expected: &[serde_json::Value],
    actual: &[serde_json::Value],
    path: &str,
    options: &CrowdAnkiParityOptions,
    differences: &mut Vec<CrowdAnkiParityDifference>,
) -> bool {
    if path == "$.media_files" {
        return compare_json_string_array_as_multiset(expected, actual, path, options, differences);
    }

    let Some(identity) = array_identity(path) else {
        return false;
    };

    let Some(expected_by_key) = array_by_identity(expected, identity) else {
        return false;
    };
    let Some(actual_by_key) = array_by_identity(actual, identity) else {
        return false;
    };

    let keys = expected_by_key
        .keys()
        .chain(actual_by_key.keys())
        .collect::<BTreeSet<_>>();
    for key in keys {
        let child_path = format!("{path}[{}={}]", identity.name, json_path_label(key));
        if is_allowed_parity_path(options, &child_path) {
            continue;
        }
        match (expected_by_key.get(key), actual_by_key.get(key)) {
            (Some(expected), Some(actual)) => {
                compare_json_value(expected, actual, &child_path, options, differences);
            }
            (Some(expected), None) => differences.push(CrowdAnkiParityDifference {
                path: child_path,
                kind: CrowdAnkiParityDifferenceKind::MissingActual,
                expected: Some((*expected).clone()),
                actual: None,
            }),
            (None, Some(actual)) => differences.push(CrowdAnkiParityDifference {
                path: child_path,
                kind: CrowdAnkiParityDifferenceKind::ExtraActual,
                expected: None,
                actual: Some((*actual).clone()),
            }),
            (None, None) => {}
        }
    }

    true
}

fn compare_json_string_array_as_multiset(
    expected: &[serde_json::Value],
    actual: &[serde_json::Value],
    path: &str,
    options: &CrowdAnkiParityOptions,
    differences: &mut Vec<CrowdAnkiParityDifference>,
) -> bool {
    let Some(expected_counts) = string_array_multiset(expected) else {
        return false;
    };
    let Some(actual_counts) = string_array_multiset(actual) else {
        return false;
    };

    let keys = expected_counts
        .keys()
        .chain(actual_counts.keys())
        .collect::<BTreeSet<_>>();
    for key in keys {
        let child_path = format!("{path}[path={}]", json_path_label(key));
        if is_allowed_parity_path(options, &child_path) {
            continue;
        }
        let expected_count = expected_counts.get(key).copied().unwrap_or_default();
        let actual_count = actual_counts.get(key).copied().unwrap_or_default();
        match (expected_count, actual_count) {
            (expected_count, actual_count) if expected_count == actual_count => {}
            (0, actual_count) => differences.push(CrowdAnkiParityDifference {
                path: child_path,
                kind: CrowdAnkiParityDifferenceKind::ExtraActual,
                expected: None,
                actual: Some(serde_json::json!(actual_count)),
            }),
            (expected_count, 0) => differences.push(CrowdAnkiParityDifference {
                path: child_path,
                kind: CrowdAnkiParityDifferenceKind::MissingActual,
                expected: Some(serde_json::json!(expected_count)),
                actual: None,
            }),
            (expected_count, actual_count) => differences.push(CrowdAnkiParityDifference {
                path: child_path,
                kind: CrowdAnkiParityDifferenceKind::LengthMismatch,
                expected: Some(serde_json::json!(expected_count)),
                actual: Some(serde_json::json!(actual_count)),
            }),
        }
    }

    true
}

fn string_array_multiset(values: &[serde_json::Value]) -> Option<BTreeMap<String, usize>> {
    let mut counts = BTreeMap::new();
    for value in values {
        let key = value.as_str()?.to_owned();
        *counts.entry(key).or_insert(0) += 1;
    }
    Some(counts)
}

#[derive(Clone, Copy)]
struct ArrayIdentity {
    name: &'static str,
    value: fn(&serde_json::Value) -> Option<String>,
}

fn array_identity(path: &str) -> Option<ArrayIdentity> {
    match path {
        "$.notes" => Some(ArrayIdentity {
            name: "guid",
            value: |value| value.get("guid")?.as_str().map(str::to_owned),
        }),
        "$.note_models" => Some(ArrayIdentity {
            name: "model",
            value: |value| {
                value
                    .get("crowdanki_uuid")
                    .and_then(serde_json::Value::as_str)
                    .or_else(|| value.get("name").and_then(serde_json::Value::as_str))
                    .map(str::to_owned)
            },
        }),
        path if path.ends_with(".flds") => Some(ArrayIdentity {
            name: "name",
            value: |value| value.get("name")?.as_str().map(str::to_owned),
        }),
        _ => None,
    }
}

fn array_by_identity(
    values: &[serde_json::Value],
    identity: ArrayIdentity,
) -> Option<BTreeMap<String, &serde_json::Value>> {
    let mut by_key = BTreeMap::new();
    for value in values {
        let key = (identity.value)(value)?;
        if by_key.insert(key, value).is_some() {
            return None;
        }
    }
    Some(by_key)
}

fn json_path_label(value: &str) -> String {
    serde_json::to_string(value).expect("serializing a JSON path label cannot fail")
}

fn is_allowed_parity_path(options: &CrowdAnkiParityOptions, path: &str) -> bool {
    options
        .allowed_path_globs
        .iter()
        .any(|pattern| brain_brew_core::glob_matches(pattern, path))
}

fn json_path_key(parent: &str, key: &str) -> String {
    if key
        .chars()
        .all(|ch| ch.is_ascii_alphanumeric() || ch == '_')
    {
        format!("{parent}.{key}")
    } else {
        format!(
            "{parent}[{}]",
            serde_json::to_string(key).expect("serializing a JSON key cannot fail")
        )
    }
}

fn json_value_summary(value: Option<&serde_json::Value>) -> String {
    let Some(value) = value else {
        return "<missing>".to_owned();
    };
    let mut summary = serde_json::to_string(value).expect("serializing JSON value cannot fail");
    if summary.len() > 120 {
        summary.truncate(117);
        summary.push_str("...");
    }
    summary
}

fn export_note_model(
    note_type: &NoteType,
    deck: &CanonicalDeck,
) -> Result<CrowdAnkiNoteModelJson, CrowdAnkiError> {
    Ok(CrowdAnkiNoteModelJson {
        kind: "NoteModel".to_owned(),
        crowdanki_uuid: crowdanki_note_model_uuid(note_type)?,
        css: note_type.styling.clone(),
        flds: note_type
            .fields
            .iter()
            .filter(|field| {
                deck.tombstones
                    .blocking(&TombstoneAddress::FieldDefinition {
                        note_type_id: note_type.id.clone(),
                        field_id: field.id.clone(),
                    })
                    .is_none()
            })
            .enumerate()
            .map(|(ord, field)| CrowdAnkiFieldJson {
                font: "Arial".to_owned(),
                media: Vec::new(),
                name: field.name.clone(),
                ord,
                rtl: field.rtl,
                size: 20,
                sticky: false,
            })
            .collect(),
        latex_post: "\\end{document}".to_owned(),
        latex_pre: default_latex_pre(),
        latex_svg: false,
        name: note_type.name.clone(),
        req: Vec::new(),
        sortf: 0,
        tags: Vec::new(),
        tmpls: note_type
            .card_templates
            .iter()
            .filter(|template| {
                deck.tombstones
                    .blocking(&TombstoneAddress::CardTemplate {
                        note_type_id: note_type.id.clone(),
                        template_id: template.id.clone(),
                    })
                    .is_none()
            })
            .enumerate()
            .map(|(ord, template)| {
                Ok(CrowdAnkiTemplateJson {
                    afmt: template.answer_format.clone(),
                    bafmt: String::new(),
                    bfont: Some(String::new()),
                    bqfmt: String::new(),
                    bsize: Some(0),
                    did: None,
                    name: template.name.clone(),
                    ord: i64::try_from(ord).map_err(|_| {
                        CrowdAnkiError::Unsupported(
                            "template array index is not representable as a CrowdAnki ordinal"
                                .to_owned(),
                        )
                    })?,
                    qfmt: template.question_format.clone(),
                    scratch_pad: Some(0),
                })
            })
            .collect::<Result<_, CrowdAnkiError>>()?,
        model_type: 0,
        vers: Vec::new(),
    })
}

fn export_note(
    note: &Note,
    deck: &CanonicalDeck,
    note_type_uuids: &BTreeMap<StableId, String>,
) -> Result<CrowdAnkiNoteJson, CrowdAnkiError> {
    let note_type = deck.note_types.get(&note.note_type_id).ok_or_else(|| {
        CrowdAnkiError::Unsupported(format!(
            "note {} references missing note type {}",
            note.id, note.note_type_id
        ))
    })?;
    let note_model_uuid = note_type_uuids
        .get(&note.note_type_id)
        .cloned()
        .expect("note type uuid was precomputed");

    let fields = note_type
        .fields
        .iter()
        .filter(|field| {
            deck.tombstones
                .blocking(&TombstoneAddress::FieldDefinition {
                    note_type_id: note_type.id.clone(),
                    field_id: field.id.clone(),
                })
                .is_none()
        })
        .map(|field| {
            note.fields
                .get(&field.id)
                .and_then(FieldValue::as_scalar)
                .map(str::to_owned)
                .ok_or_else(|| {
                    CrowdAnkiError::Unsupported(format!(
                        "note {} field {} was not lowered to scalar adapter text",
                        note.id, field.id
                    ))
                })
        })
        .collect::<Result<_, _>>()?;

    Ok(CrowdAnkiNoteJson {
        type_: "Note".to_owned(),
        data: String::new(),
        fields,
        flags: 0,
        guid: crowdanki_note_guid(note),
        note_model_uuid,
        tags: note.tags.iter().cloned().collect(),
    })
}

fn crowdanki_deck_uuid(deck: &CanonicalDeck) -> String {
    deck.adapter_ids
        .get("crowdanki:uuid")
        .map(str::to_owned)
        .unwrap_or_else(|| deck.id.to_string())
}

fn crowdanki_deck_config_uuid(deck: &CanonicalDeck) -> String {
    deck.adapter_ids
        .get("crowdanki:deck_config_uuid")
        .map(str::to_owned)
        .unwrap_or_else(|| format!("{}:deck-config", deck.id))
}

fn crowdanki_deck_config_name(deck: &CanonicalDeck) -> String {
    deck.adapter_ids
        .get("crowdanki:deck_config_name")
        .map(str::to_owned)
        .unwrap_or_else(|| deck.name.clone())
}

fn crowdanki_note_model_uuid(note_type: &NoteType) -> Result<String, CrowdAnkiError> {
    note_type
        .adapter_ids
        .get("crowdanki:uuid")
        .map(str::to_owned)
        .ok_or_else(|| {
            CrowdAnkiError::Unsupported(format!(
                "note type {} is missing crowdanki:uuid adapter id",
                note_type.id
            ))
        })
}

fn crowdanki_note_guid(note: &Note) -> String {
    note.adapter_ids
        .get("crowdanki:guid")
        .map(str::to_owned)
        .unwrap_or_else(|| note.id.to_string())
}

/// Validate the effective GUIDs that an export or round-trip projection would emit.
///
/// An absent `crowdanki:guid` deliberately falls back to the unique canonical stable ID;
/// an explicitly present empty GUID is invalid. As with raw imports, GUIDs are opaque and
/// collide only when their exact UTF-8 strings are equal.
fn export_identity_diagnostics(deck: &CanonicalDeck) -> Vec<CrowdAnkiIdentityDiagnostic> {
    let mut diagnostics = Vec::new();
    let active_notes = deck
        .notes
        .iter()
        .filter(|(id, _)| {
            deck.tombstones
                .blocking(&TombstoneAddress::Note {
                    note_id: (*id).clone(),
                })
                .is_none()
        })
        .collect::<Vec<_>>();
    let mut guid_notes = BTreeMap::<String, Vec<(usize, StableId)>>::new();
    for (note_index, (id, note)) in active_notes.into_iter().enumerate() {
        let guid = crowdanki_note_guid(note);
        let path = format!("notes.{id}.adapter_ids.crowdanki:guid");
        if guid.is_empty() {
            diagnostics.push(CrowdAnkiIdentityDiagnostic {
                kind: CrowdAnkiIdentityDiagnosticKind::EmptyGuid,
                source_paths: vec![path],
                note_indices: vec![note_index],
                note_ids: vec![id.clone()],
                note_model_index: None,
                template_indices: Vec::new(),
                guid: Some(guid),
                found_ordinal: None,
                expected_ordinal: None,
            });
        } else {
            guid_notes
                .entry(guid)
                .or_default()
                .push((note_index, id.clone()));
        }
    }
    for (guid, occurrences) in guid_notes {
        if occurrences.len() > 1 {
            let (note_indices, note_ids): (Vec<_>, Vec<_>) = occurrences.into_iter().unzip();
            diagnostics.push(CrowdAnkiIdentityDiagnostic {
                kind: CrowdAnkiIdentityDiagnosticKind::DuplicateGuid,
                source_paths: note_ids
                    .iter()
                    .map(|id| format!("notes.{id}.adapter_ids.crowdanki:guid"))
                    .collect(),
                note_indices,
                note_ids,
                note_model_index: None,
                template_indices: Vec::new(),
                guid: Some(guid),
                found_ordinal: None,
                expected_ordinal: None,
            });
        }
    }
    diagnostics
}

fn default_latex_pre() -> String {
    "\\documentclass[12pt]{article}\n\\special{papersize=3in,5in}\n\\usepackage{amssymb,amsmath}\n\\pagestyle{empty}\n\\setlength{\\parindent}{0in}\n\\begin{document}\n"
        .to_owned()
}

fn default_deck_config_json(uuid: &str, name: &str) -> serde_json::Value {
    serde_json::json!({
        "__type__": "DeckConfig",
        "crowdanki_uuid": uuid,
        "name": name,
        "autoplay": false,
        "dyn": false,
        "lapse": {
            "delays": [10],
            "leechAction": 0,
            "leechFails": 8,
            "minInt": 1,
            "mult": 0,
        },
        "maxTaken": 60,
        "new": {
            "bury": true,
            "delays": [1, 10],
            "initialFactor": 2500,
            "ints": [1, 4, 7],
            "order": 0,
            "perDay": 15,
            "separate": true,
        },
        "replayq": true,
        "rev": {
            "bury": true,
            "ease4": 1.3,
            "fuzz": 0.05,
            "ivlFct": 1,
            "maxIvl": 36500,
            "minSpace": 1,
            "perDay": 100,
        },
        "timer": 0,
    })
}

fn validate_supported_deck_configurations(
    uuid: &str,
    configurations: &[serde_json::Value],
) -> Result<String, CrowdAnkiError> {
    if configurations.len() != 1 {
        return Err(CrowdAnkiError::Unsupported(format!(
            "expected one default deck configuration, found {}",
            configurations.len()
        )));
    }
    let Some(name) = configurations[0]
        .get("name")
        .and_then(serde_json::Value::as_str)
    else {
        return Err(CrowdAnkiError::Unsupported(
            "deck configuration is missing a name".to_owned(),
        ));
    };
    let expected = default_deck_config_json(uuid, name);
    if configurations[0] != expected {
        return Err(CrowdAnkiError::Unsupported(
            "non-default deck configurations are not modeled yet".to_owned(),
        ));
    }
    Ok(name.to_owned())
}

/// One machine-readable CrowdAnki identity defect. `source_paths` are JSON schema
/// locations on import or canonical deck paths on export/project; array indices retain
/// every source occurrence needed to fix an identity collision without guessing.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct CrowdAnkiIdentityDiagnostic {
    pub kind: CrowdAnkiIdentityDiagnosticKind,
    pub source_paths: Vec<String>,
    pub note_indices: Vec<usize>,
    pub note_ids: Vec<StableId>,
    pub note_model_index: Option<usize>,
    pub template_indices: Vec<usize>,
    pub guid: Option<String>,
    pub found_ordinal: Option<i64>,
    pub expected_ordinal: Option<usize>,
}

/// Stable classification for a CrowdAnki identity defect.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum CrowdAnkiIdentityDiagnosticKind {
    EmptyGuid,
    DuplicateGuid,
    DuplicateTemplateOrdinal,
    TemplateOrdinalMismatch,
}

/// Aggregated identity diagnostics produced before a CrowdAnki conversion boundary.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct CrowdAnkiIdentityReport {
    pub diagnostics: Vec<CrowdAnkiIdentityDiagnostic>,
}

impl fmt::Display for CrowdAnkiIdentityReport {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        writeln!(f, "CrowdAnki identity validation failed:")?;
        for diagnostic in &self.diagnostics {
            let paths = diagnostic.source_paths.join(", ");
            match diagnostic.kind {
                CrowdAnkiIdentityDiagnosticKind::EmptyGuid => writeln!(
                    f,
                    "- empty GUID at {paths}: CrowdAnki GUID must not be empty"
                )?,
                CrowdAnkiIdentityDiagnosticKind::DuplicateGuid => writeln!(
                    f,
                    "- duplicate GUID at {paths}: CrowdAnki GUID {:?} is duplicated at note indices {:?} (canonical notes {:?})",
                    diagnostic.guid.as_deref().unwrap_or_default(),
                    diagnostic.note_indices,
                    diagnostic.note_ids,
                )?,
                CrowdAnkiIdentityDiagnosticKind::DuplicateTemplateOrdinal => writeln!(
                    f,
                    "- duplicate template ordinal at {paths}: note model index {} has duplicate template ordinal {} at template indices {:?}",
                    diagnostic.note_model_index.unwrap_or_default(),
                    diagnostic.found_ordinal.unwrap_or_default(),
                    diagnostic.template_indices,
                )?,
                CrowdAnkiIdentityDiagnosticKind::TemplateOrdinalMismatch => {
                    let non_negative = diagnostic
                        .found_ordinal
                        .filter(|ordinal| *ordinal < 0)
                        .map(|_| "; template ordinal must be non-negative")
                        .unwrap_or_default();
                    writeln!(
                        f,
                        "- template ordinal at {paths}: note model index {}, template index {} found {}, expected {}; template ordinals must be zero-based, contiguous, and match array order{non_negative}",
                        diagnostic.note_model_index.unwrap_or_default(),
                        diagnostic
                            .template_indices
                            .first()
                            .copied()
                            .unwrap_or_default(),
                        diagnostic.found_ordinal.unwrap_or_default(),
                        diagnostic.expected_ordinal.unwrap_or_default(),
                    )?
                }
            }
        }
        Ok(())
    }
}

#[derive(Debug)]
pub enum CrowdAnkiError {
    Json(serde_json::Error),
    JsonPath { path: String, message: String },
    Identity(CrowdAnkiIdentityReport),
    Plan(String),
    StableId(String),
    Unsupported(String),
    Validation(ValidationReport),
    VariableRender(VariableRenderReport),
    Media(media::MediaValidationReport),
}

impl fmt::Display for CrowdAnkiError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Json(error) => write!(f, "CrowdAnki JSON error: {error}"),
            Self::JsonPath { path, message } => {
                write!(f, "CrowdAnki JSON error at schema path {path}: {message}")
            }
            Self::Identity(report) => report.fmt(f),
            Self::Plan(message) => write!(f, "CrowdAnki import plan failed: {message}"),
            Self::StableId(id) => write!(f, "generated invalid stable id {id:?}"),
            Self::Unsupported(message) => write!(f, "unsupported CrowdAnki data: {message}"),
            Self::Validation(report) => write!(f, "imported deck failed validation: {report}"),
            Self::VariableRender(report) => write!(f, "deck variable rendering failed: {report}"),
            Self::Media(report) => write!(f, "CrowdAnki media path validation failed: {report}"),
        }
    }
}

impl std::error::Error for CrowdAnkiError {}

/// Versioned, reviewable CrowdAnki stable-ID import plan.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct CrowdAnkiImportPlan {
    pub format: String,
    pub version: u32,
    pub provenance: CrowdAnkiImportProvenance,
    pub entries: Vec<CrowdAnkiImportPlanEntry>,
}

/// Byte-level source and import-policy binding for a plan.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct CrowdAnkiImportProvenance {
    pub source_sha256: String,
    pub source_bytes: u64,
    pub import_options_sha256: String,
    /// Ordered media evidence is absent only for the explicitly reference-only API.
    #[serde(default)]
    pub media: Vec<CrowdAnkiImportMediaEvidence>,
}

/// One declared media path, source location, and byte-level proof selected at import time.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct CrowdAnkiImportMediaEvidence {
    pub source_path: String,
    pub path: String,
    pub sha256: String,
    pub bytes: u64,
}

/// A media declaration discovered in a CrowdAnki document before any filesystem access.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct CrowdAnkiImportMediaReference {
    pub source_path: String,
    pub path: String,
}

/// One source identity proposed for a Canonical Deck stable ID.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct CrowdAnkiImportPlanEntry {
    pub kind: CrowdAnkiImportPlanEntryKind,
    pub source_path: String,
    pub suggested_id: String,
    pub status: CrowdAnkiImportPlanStatus,
    pub decision: CrowdAnkiImportPlanDecision,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub source_guid: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub model_uuid: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub model_name: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub template_name: Option<String>,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CrowdAnkiImportPlanEntryKind {
    Deck,
    NoteType,
    Field,
    Template,
    Note,
    Media,
}

impl CrowdAnkiImportPlanEntryKind {
    pub fn name(self) -> &'static str {
        match self {
            Self::Deck => "deck",
            Self::NoteType => "note_type",
            Self::Field => "field",
            Self::Template => "template",
            Self::Note => "note",
            Self::Media => "media",
        }
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CrowdAnkiImportPlanStatus {
    Automatic,
    RequiresOverride,
    Rejected,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum CrowdAnkiImportPlanDecision {
    Automatic,
    Override { stable_id: String },
    Reject,
}

impl CrowdAnkiImportPlan {
    /// Deterministic canonical JSON form (pretty, sorted plan entries, and trailing newline).
    pub fn to_canonical_json(&self) -> Result<String, CrowdAnkiError> {
        let mut plan = self.clone();
        plan.entries.sort_by(|left, right| {
            (&left.source_path, left.kind, &left.suggested_id).cmp(&(
                &right.source_path,
                right.kind,
                &right.suggested_id,
            ))
        });
        let mut json = serde_json::to_string_pretty(&plan).map_err(CrowdAnkiError::Json)?;
        json.push('\n');
        Ok(json)
    }

    /// Deterministic YAML representation for human review.
    pub fn to_canonical_yaml(&self) -> Result<String, CrowdAnkiError> {
        let mut plan = self.clone();
        plan.entries.sort_by(|left, right| {
            (&left.source_path, left.kind, &left.suggested_id).cmp(&(
                &right.source_path,
                right.kind,
                &right.suggested_id,
            ))
        });
        serde_yaml::to_string(&plan).map_err(|error| {
            CrowdAnkiError::Plan(format!("cannot serialize import plan YAML: {error}"))
        })
    }

    /// Parse either the canonical JSON form or a review-friendly YAML representation.
    pub fn from_bytes(bytes: &[u8]) -> Result<Self, CrowdAnkiError> {
        serde_json::from_slice(bytes)
            .or_else(|json_error| {
                serde_yaml::from_slice(bytes).map_err(|yaml_error| {
                    CrowdAnkiError::Plan(format!(
                        "invalid import plan (JSON: {json_error}; YAML: {yaml_error})"
                    ))
                })
            })
            .map_err(|error| match error {
                CrowdAnkiError::Plan(_) => error,
                other => CrowdAnkiError::Plan(other.to_string()),
            })
    }

    fn validate_against(
        &self,
        expected: &Self,
        approve_automatic: bool,
    ) -> Result<BTreeMap<String, StableId>, CrowdAnkiError> {
        if self.format != IMPORT_PLAN_FORMAT || self.version != IMPORT_PLAN_VERSION {
            return Err(CrowdAnkiError::Plan(format!(
                "unsupported import plan format/version {}/{}; expected {}/{}",
                self.format, self.version, IMPORT_PLAN_FORMAT, IMPORT_PLAN_VERSION
            )));
        }
        if self.provenance != expected.provenance {
            return Err(CrowdAnkiError::Plan(
                "stale or mutated import plan: source bytes or import options fingerprint do not match"
                    .to_owned(),
            ));
        }
        if self.entries.len() != expected.entries.len() {
            return Err(CrowdAnkiError::Plan(
                "mutated import plan does not contain the complete source identity inventory"
                    .to_owned(),
            ));
        }
        let expected_by_path = expected
            .entries
            .iter()
            .map(|entry| (entry.source_path.as_str(), entry))
            .collect::<BTreeMap<_, _>>();
        let mut selections = BTreeMap::new();
        let mut selected = BTreeMap::<String, String>::new();
        for entry in &self.entries {
            let Some(source) = expected_by_path.get(entry.source_path.as_str()) else {
                return Err(CrowdAnkiError::Plan(format!(
                    "plan entry {} is not present in the source identity inventory",
                    entry.source_path
                )));
            };
            if entry.kind != source.kind
                || entry.suggested_id != source.suggested_id
                || entry.status != source.status
                || entry.source_guid != source.source_guid
                || entry.model_uuid != source.model_uuid
                || entry.model_name != source.model_name
                || entry.template_name != source.template_name
            {
                return Err(CrowdAnkiError::Plan(format!(
                    "plan entry {} changed generated identity evidence or status",
                    entry.source_path
                )));
            }
            let selected_id = match (&source.status, &entry.decision) {
                (CrowdAnkiImportPlanStatus::Automatic, CrowdAnkiImportPlanDecision::Automatic) => {
                    if !approve_automatic {
                        return Err(CrowdAnkiError::Plan(
                            "automatic suggestions are unreviewed; rerun apply with --approve-plan"
                                .to_owned(),
                        ));
                    }
                    entry.suggested_id.clone()
                }
                (
                    CrowdAnkiImportPlanStatus::RequiresOverride,
                    CrowdAnkiImportPlanDecision::Override { stable_id },
                ) => stable_id.clone(),
                (_, CrowdAnkiImportPlanDecision::Reject)
                | (CrowdAnkiImportPlanStatus::Rejected, _) => {
                    return Err(CrowdAnkiError::Plan(format!(
                        "plan entry {} is rejected and cannot be applied",
                        entry.source_path
                    )));
                }
                (CrowdAnkiImportPlanStatus::RequiresOverride, _) => {
                    return Err(CrowdAnkiError::Plan(format!(
                        "plan entry {} has an unresolved collision; select an override stable_id",
                        entry.source_path
                    )));
                }
                (
                    CrowdAnkiImportPlanStatus::Automatic,
                    CrowdAnkiImportPlanDecision::Override { stable_id },
                ) => stable_id.clone(),
            };
            let stable_id = StableId::new(selected_id.clone()).map_err(|error| {
                CrowdAnkiError::Plan(format!(
                    "plan entry {} has invalid override stable ID {:?}: {error}",
                    entry.source_path, selected_id
                ))
            })?;
            if let Some(other_path) =
                selected.insert(selected_id.clone(), entry.source_path.clone())
            {
                return Err(CrowdAnkiError::Plan(format!(
                    "plan stable ID {:?} is selected by both {} and {}",
                    selected_id, other_path, entry.source_path
                )));
            }
            selections.insert(entry.source_path.clone(), stable_id);
        }
        if selections.len() != expected.entries.len() {
            return Err(CrowdAnkiError::Plan(
                "plan contains duplicate source locations".to_owned(),
            ));
        }
        Ok(selections)
    }
}

const IMPORT_PLAN_FORMAT: &str = "brain-brew.crowdanki-import-plan";
const IMPORT_PLAN_VERSION: u32 = 2;
const IMPORT_OPTIONS_FINGERPRINT_INPUT: &[u8] =
    b"brain-brew/crowdanki-import/options/v1;strict-image-reverse-map=true";

#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct CrowdAnkiDeckJson {
    #[serde(rename = "__type__")]
    type_: String,
    children: Vec<serde_json::Value>,
    crowdanki_uuid: String,
    deck_config_uuid: String,
    deck_configurations: Vec<serde_json::Value>,
    desc: String,
    #[serde(rename = "dyn")]
    dyn_: i64,
    #[serde(rename = "extendNew")]
    extend_new: i64,
    #[serde(rename = "extendRev")]
    extend_rev: i64,
    media_files: Vec<String>,
    name: String,
    note_models: Vec<CrowdAnkiNoteModelJson>,
    notes: Vec<CrowdAnkiNoteJson>,
}

enum CrowdAnkiIdentityInput<'a> {
    Import(&'a CrowdAnkiDeckJson),
    Export(&'a CanonicalDeck),
}

/// The single identity-validation gateway for import, export, and round-trip projection.
fn validate_crowdanki_identity(input: CrowdAnkiIdentityInput<'_>) -> Result<(), CrowdAnkiError> {
    let diagnostics = match input {
        CrowdAnkiIdentityInput::Import(deck) => deck.identity_diagnostics()?,
        CrowdAnkiIdentityInput::Export(deck) => export_identity_diagnostics(deck),
    };
    if diagnostics.is_empty() {
        Ok(())
    } else {
        Err(CrowdAnkiError::Identity(CrowdAnkiIdentityReport {
            diagnostics,
        }))
    }
}

impl CrowdAnkiDeckJson {
    fn content_media_paths(&self) -> BTreeSet<String> {
        let mut paths = media::extract_media_references_from_rendered_field(&self.desc);
        for model in &self.note_models {
            paths.extend(media::extract_media_references_from_rendered_field(
                &model.css,
            ));
            for template in &model.tmpls {
                paths.extend(media::extract_media_references_from_rendered_field(
                    &template.qfmt,
                ));
                paths.extend(media::extract_media_references_from_rendered_field(
                    &template.afmt,
                ));
            }
        }
        for note in &self.notes {
            for field in &note.fields {
                paths.extend(media::extract_media_references_from_rendered_field(field));
            }
        }
        paths
    }

    fn import_media_references(
        &self,
    ) -> Result<Vec<CrowdAnkiImportMediaReference>, CrowdAnkiError> {
        let mut references = Vec::new();
        let mut exact = BTreeMap::<String, String>::new();
        let mut portable_case = BTreeMap::<String, String>::new();
        for (index, path) in self.media_files.iter().enumerate() {
            let source_path = format!("$.media_files[{index}]");
            crate::safe_relative_path::SafeRelativePath::new(path).map_err(|error| {
                CrowdAnkiError::Plan(format!(
                    "unsafe CrowdAnki media path at {source_path} {path:?}: {error}"
                ))
            })?;
            if let Some(first) = exact.insert(path.clone(), source_path.clone()) {
                return Err(CrowdAnkiError::Plan(format!(
                    "duplicate CrowdAnki media path {path:?} at {first} and {source_path}"
                )));
            }
            // Case-insensitive filesystems would otherwise let two declarations select one
            // physical file. Unicode lowercase is deliberately conservative: collisions reject.
            let folded = path.to_lowercase();
            if let Some(first) = portable_case.insert(folded, source_path.clone()) {
                return Err(CrowdAnkiError::Plan(format!(
                    "case-colliding CrowdAnki media path {path:?} at {first} and {source_path}"
                )));
            }
            references.push(CrowdAnkiImportMediaReference {
                source_path,
                path: path.clone(),
            });
        }
        Ok(references)
    }

    /// Collect raw CrowdAnki identity defects before any data is sorted, indexed, or converted.
    ///
    /// CrowdAnki GUIDs are opaque strings: Brain Brew performs no trimming, Unicode
    /// normalization, case folding, or other lossy canonicalization. Only exact non-empty
    /// text is an effective GUID identity. Template ordinals are zero-based positions, so a
    /// supported model has `tmpls[index].ord == index` for every template.
    fn identity_diagnostics(&self) -> Result<Vec<CrowdAnkiIdentityDiagnostic>, CrowdAnkiError> {
        let mut diagnostics = Vec::new();
        let mut guid_indices = BTreeMap::<&str, Vec<usize>>::new();
        for (note_index, note) in self.notes.iter().enumerate() {
            let path = format!("$.notes[{note_index}].guid");
            if note.guid.is_empty() {
                diagnostics.push(CrowdAnkiIdentityDiagnostic {
                    kind: CrowdAnkiIdentityDiagnosticKind::EmptyGuid,
                    source_paths: vec![path],
                    note_indices: vec![note_index],
                    note_ids: Vec::new(),
                    note_model_index: None,
                    template_indices: Vec::new(),
                    guid: Some(note.guid.clone()),
                    found_ordinal: None,
                    expected_ordinal: None,
                });
            } else {
                guid_indices.entry(&note.guid).or_default().push(note_index);
            }
        }
        for (guid, note_indices) in guid_indices {
            if note_indices.len() > 1 {
                diagnostics.push(CrowdAnkiIdentityDiagnostic {
                    kind: CrowdAnkiIdentityDiagnosticKind::DuplicateGuid,
                    source_paths: note_indices
                        .iter()
                        .map(|index| format!("$.notes[{index}].guid"))
                        .collect(),
                    note_indices,
                    note_ids: Vec::new(),
                    note_model_index: None,
                    template_indices: Vec::new(),
                    guid: Some(guid.to_owned()),
                    found_ordinal: None,
                    expected_ordinal: None,
                });
            }
        }

        for (note_model_index, model) in self.note_models.iter().enumerate() {
            let mut ordinal_indices = BTreeMap::<i64, Vec<usize>>::new();
            for (template_index, template) in model.tmpls.iter().enumerate() {
                ordinal_indices
                    .entry(template.ord)
                    .or_default()
                    .push(template_index);
            }
            for (ordinal, template_indices) in ordinal_indices {
                if template_indices.len() > 1 {
                    diagnostics.push(CrowdAnkiIdentityDiagnostic {
                        kind: CrowdAnkiIdentityDiagnosticKind::DuplicateTemplateOrdinal,
                        source_paths: template_indices
                            .iter()
                            .map(|index| {
                                format!("$.note_models[{note_model_index}].tmpls[{index}].ord")
                            })
                            .collect(),
                        note_indices: Vec::new(),
                        note_ids: Vec::new(),
                        note_model_index: Some(note_model_index),
                        template_indices,
                        guid: None,
                        found_ordinal: Some(ordinal),
                        expected_ordinal: None,
                    });
                }
            }
            for (template_index, template) in model.tmpls.iter().enumerate() {
                let expected = i64::try_from(template_index).map_err(|_| {
                    CrowdAnkiError::Unsupported(
                        "CrowdAnki template array index is not representable as an ordinal"
                            .to_owned(),
                    )
                })?;
                if template.ord != expected {
                    diagnostics.push(CrowdAnkiIdentityDiagnostic {
                        kind: CrowdAnkiIdentityDiagnosticKind::TemplateOrdinalMismatch,
                        source_paths: vec![format!(
                            "$.note_models[{note_model_index}].tmpls[{template_index}].ord"
                        )],
                        note_indices: Vec::new(),
                        note_ids: Vec::new(),
                        note_model_index: Some(note_model_index),
                        template_indices: vec![template_index],
                        guid: None,
                        found_ordinal: Some(template.ord),
                        expected_ordinal: Some(template_index),
                    });
                }
            }
        }

        Ok(diagnostics)
    }

    fn import_plan(&self, source_bytes: &[u8]) -> Result<CrowdAnkiImportPlan, CrowdAnkiError> {
        // Keep plan generation fail-closed on adapter identities and physical media paths whose
        // evidence is ambiguous. Byte handoff later uses this exact inventory.
        validate_crowdanki_identity(CrowdAnkiIdentityInput::Import(self))?;
        self.import_media_references()?;
        let mut model_by_uuid = BTreeMap::<&str, &str>::new();
        for model in &self.note_models {
            if let Some(existing_name) = model_by_uuid.insert(&model.crowdanki_uuid, &model.name) {
                return Err(CrowdAnkiError::Unsupported(format!(
                    "CrowdAnki note models {:?} and {:?} share crowdanki_uuid {:?}; {}",
                    existing_name,
                    model.name,
                    model.crowdanki_uuid,
                    suggested_id_collision_resolution()
                )));
            }
        }
        let mut entries = vec![CrowdAnkiImportPlanEntry {
            kind: CrowdAnkiImportPlanEntryKind::Deck,
            source_path: "$.name".to_owned(),
            suggested_id: prefixed_stable_id("deck", &self.name)?.to_string(),
            status: CrowdAnkiImportPlanStatus::Automatic,
            decision: CrowdAnkiImportPlanDecision::Automatic,
            source_guid: None,
            model_uuid: None,
            model_name: None,
            template_name: None,
        }];
        for (model_index, model) in self.note_models.iter().enumerate() {
            let model_path = format!("$.note_models[{model_index}]");
            let model_id = prefixed_stable_id("note-type", &model.name)?.to_string();
            entries.push(CrowdAnkiImportPlanEntry {
                kind: CrowdAnkiImportPlanEntryKind::NoteType,
                source_path: format!("{model_path}.name"),
                suggested_id: model_id,
                status: CrowdAnkiImportPlanStatus::Automatic,
                decision: CrowdAnkiImportPlanDecision::Automatic,
                source_guid: None,
                model_uuid: Some(model.crowdanki_uuid.clone()),
                model_name: Some(model.name.clone()),
                template_name: None,
            });
            for (field_index, field) in model.flds.iter().enumerate() {
                entries.push(CrowdAnkiImportPlanEntry {
                    kind: CrowdAnkiImportPlanEntryKind::Field,
                    source_path: format!("{model_path}.flds[{field_index}].name"),
                    suggested_id: prefixed_stable_id("field", &field.name)?.to_string(),
                    status: CrowdAnkiImportPlanStatus::Automatic,
                    decision: CrowdAnkiImportPlanDecision::Automatic,
                    source_guid: None,
                    model_uuid: Some(model.crowdanki_uuid.clone()),
                    model_name: Some(model.name.clone()),
                    template_name: None,
                });
            }
            for (template_index, template) in model.tmpls.iter().enumerate() {
                entries.push(CrowdAnkiImportPlanEntry {
                    kind: CrowdAnkiImportPlanEntryKind::Template,
                    source_path: format!("{model_path}.tmpls[{template_index}].name"),
                    suggested_id: prefixed_stable_id("template", &template.name)?.to_string(),
                    status: CrowdAnkiImportPlanStatus::Automatic,
                    decision: CrowdAnkiImportPlanDecision::Automatic,
                    source_guid: None,
                    model_uuid: Some(model.crowdanki_uuid.clone()),
                    model_name: Some(model.name.clone()),
                    template_name: Some(template.name.clone()),
                });
            }
        }
        let note_identities = self
            .notes
            .iter()
            .map(CrowdAnkiNoteSource::from_note_json)
            .map(CrowdAnkiNoteSource::identity)
            .collect::<Vec<_>>();
        for (index, (note, id)) in self
            .notes
            .iter()
            .zip(suggest_imported_note_stable_ids(&note_identities)?)
            .enumerate()
        {
            let model = self
                .note_models
                .iter()
                .find(|model| model.crowdanki_uuid == note.note_model_uuid);
            entries.push(CrowdAnkiImportPlanEntry {
                kind: CrowdAnkiImportPlanEntryKind::Note,
                source_path: format!("$.notes[{index}].guid"),
                suggested_id: id.to_string(),
                status: CrowdAnkiImportPlanStatus::Automatic,
                decision: CrowdAnkiImportPlanDecision::Automatic,
                source_guid: Some(note.guid.clone()),
                model_uuid: Some(note.note_model_uuid.clone()),
                model_name: model.map(|model| model.name.clone()),
                template_name: None,
            });
        }
        for (index, path) in self.media_files.iter().enumerate() {
            entries.push(CrowdAnkiImportPlanEntry {
                kind: CrowdAnkiImportPlanEntryKind::Media,
                source_path: format!("$.media_files[{index}]"),
                suggested_id: prefixed_stable_id("media", path)?.to_string(),
                status: CrowdAnkiImportPlanStatus::Automatic,
                decision: CrowdAnkiImportPlanDecision::Automatic,
                source_guid: None,
                model_uuid: None,
                model_name: None,
                template_name: None,
            });
        }
        let mut collisions = BTreeMap::<String, usize>::new();
        for entry in &entries {
            *collisions.entry(entry.suggested_id.clone()).or_default() += 1;
        }
        for entry in &mut entries {
            if collisions[&entry.suggested_id] > 1 {
                entry.status = CrowdAnkiImportPlanStatus::RequiresOverride;
            }
        }
        entries.sort_by(|left, right| left.source_path.cmp(&right.source_path));
        Ok(CrowdAnkiImportPlan {
            format: IMPORT_PLAN_FORMAT.to_owned(),
            version: IMPORT_PLAN_VERSION,
            provenance: CrowdAnkiImportProvenance {
                source_sha256: format!("{:x}", Sha256::digest(source_bytes)),
                source_bytes: source_bytes.len() as u64,
                import_options_sha256: format!(
                    "{:x}",
                    Sha256::digest(IMPORT_OPTIONS_FINGERPRINT_INPUT)
                ),
                media: Vec::new(),
            },
            entries,
        })
    }

    fn into_deck_with_ids(
        self,
        selected_ids: &BTreeMap<String, StableId>,
    ) -> Result<CanonicalDeck, CrowdAnkiError> {
        if self.type_ != "Deck" {
            return Err(CrowdAnkiError::Unsupported(format!(
                "expected __type__ Deck, found {}",
                self.type_
            )));
        }
        if !self.children.is_empty() {
            return Err(CrowdAnkiError::Unsupported(
                "child decks are not modeled yet".to_owned(),
            ));
        }
        if self.dyn_ != 0 || self.extend_new != 10 || self.extend_rev != 50 {
            return Err(CrowdAnkiError::Unsupported(format!(
                "non-default deck scheduling header is not modeled yet (dyn={}, extendNew={}, extendRev={})",
                self.dyn_, self.extend_new, self.extend_rev
            )));
        }
        validate_crowdanki_identity(CrowdAnkiIdentityInput::Import(&self))?;

        let deck_config_name = validate_supported_deck_configurations(
            &self.deck_config_uuid,
            &self.deck_configurations,
        )?;

        let deck_id = selected_id(
            selected_ids,
            "$.name",
            prefixed_stable_id("deck", &self.name)?,
        )?;
        let mut deck_adapter_ids = AdapterIds::new();
        deck_adapter_ids.insert("crowdanki:uuid", self.crowdanki_uuid);
        deck_adapter_ids.insert("crowdanki:deck_config_uuid", self.deck_config_uuid);
        deck_adapter_ids.insert("crowdanki:deck_config_name", deck_config_name);

        let mut note_type_by_uuid: BTreeMap<String, StableId> = BTreeMap::new();
        let mut note_types: BTreeMap<StableId, NoteType> = BTreeMap::new();
        for (model_index, note_model) in self.note_models.into_iter().enumerate() {
            let model_path = format!("$.note_models[{model_index}]");
            let id = selected_id(
                selected_ids,
                &format!("{model_path}.name"),
                prefixed_stable_id("note-type", &note_model.name)?,
            )?;
            let field_ids = note_model
                .flds
                .iter()
                .enumerate()
                .map(|(index, field)| {
                    selected_id(
                        selected_ids,
                        &format!("{model_path}.flds[{index}].name"),
                        prefixed_stable_id("field", &field.name)?,
                    )
                })
                .collect::<Result<Vec<_>, CrowdAnkiError>>()?;
            let template_ids = note_model
                .tmpls
                .iter()
                .enumerate()
                .map(|(index, template)| {
                    selected_id(
                        selected_ids,
                        &format!("{model_path}.tmpls[{index}].name"),
                        prefixed_stable_id("template", &template.name)?,
                    )
                })
                .collect::<Result<Vec<_>, CrowdAnkiError>>()?;
            let (uuid, id, note_type) = note_model.into_note_type(id, field_ids, template_ids)?;
            if let Some(existing) = note_types.get(&id) {
                return Err(CrowdAnkiError::Unsupported(format!(
                    "CrowdAnki note models {:?} and {:?} both derive suggested stable ID {}; {}",
                    existing.name,
                    note_type.name,
                    id,
                    suggested_id_collision_resolution()
                )));
            }
            if let Some(existing_id) = note_type_by_uuid.get(&uuid) {
                let existing = note_types
                    .get(existing_id)
                    .expect("note type UUID map points at inserted note type");
                return Err(CrowdAnkiError::Unsupported(format!(
                    "CrowdAnki note models {:?} and {:?} share crowdanki_uuid {:?}; {}",
                    existing.name,
                    note_type.name,
                    uuid,
                    suggested_id_collision_resolution()
                )));
            }
            note_type_by_uuid.insert(uuid, id.clone());
            note_types.insert(id, note_type);
        }

        let note_identities = self
            .notes
            .iter()
            .map(CrowdAnkiNoteSource::from_note_json)
            .map(CrowdAnkiNoteSource::identity)
            .collect::<Vec<_>>();
        let suggested_note_ids = suggest_imported_note_stable_ids(&note_identities)?;
        let mut notes: BTreeMap<StableId, Note> = BTreeMap::new();
        for (index, (note_json, suggested_id)) in
            self.notes.into_iter().zip(suggested_note_ids).enumerate()
        {
            let id = selected_id(
                selected_ids,
                &format!("$.notes[{index}].guid"),
                suggested_id,
            )?;
            let note = note_json.into_note(&note_types, &note_type_by_uuid, id.clone())?;
            if notes.insert(id.clone(), note).is_some() {
                return Err(CrowdAnkiError::Unsupported(format!(
                    "CrowdAnki imported-note identity algorithm generated duplicate stable ID {id}"
                )));
            }
        }

        let ambiguous_media_file_paths = duplicate_paths(&self.media_files);
        let mut media_sources: BTreeMap<StableId, String> = BTreeMap::new();
        let mut media = BTreeMap::new();
        for (index, path) in self.media_files.into_iter().enumerate() {
            let id = selected_id(
                selected_ids,
                &format!("$.media_files[{index}]"),
                prefixed_stable_id("media", &path)?,
            )?;
            if let Some(existing_path) = media_sources.get(&id) {
                if existing_path != &path {
                    return Err(CrowdAnkiError::Unsupported(format!(
                        "CrowdAnki media files {:?} and {:?} both derive suggested stable ID {}; {}",
                        existing_path,
                        path,
                        id,
                        suggested_id_collision_resolution()
                    )));
                }
                continue;
            }
            media_sources.insert(id.clone(), path.clone());
            media.insert(
                id.clone(),
                MediaReference {
                    id,
                    path,
                    sha256: String::new(),
                },
            );
        }

        let media_path_lookup = media_path_lookup(&media, &ambiguous_media_file_paths);
        for note in notes.values_mut() {
            reverse_map_strict_image_fields(note, &media_path_lookup);
        }

        let deck = CanonicalDeck {
            id: deck_id,
            name: self.name,
            description: self.desc,
            note_types,
            notes,
            media,
            tombstones: Tombstones::default(),
            variables: BTreeMap::new(),
            adapter_ids: deck_adapter_ids,
        };
        deck.validate().map_err(CrowdAnkiError::Validation)?;
        media::validate_paths(&deck).map_err(CrowdAnkiError::Media)?;
        Ok(deck)
    }
}

#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct CrowdAnkiNoteModelJson {
    #[serde(rename = "__type__")]
    kind: String,
    crowdanki_uuid: String,
    css: String,
    flds: Vec<CrowdAnkiFieldJson>,
    #[serde(rename = "latexPost")]
    latex_post: String,
    #[serde(rename = "latexPre")]
    latex_pre: String,
    #[serde(rename = "latexsvg")]
    latex_svg: bool,
    name: String,
    req: Vec<serde_json::Value>,
    sortf: usize,
    tags: Vec<String>,
    tmpls: Vec<CrowdAnkiTemplateJson>,
    #[serde(rename = "type")]
    model_type: i64,
    vers: Vec<serde_json::Value>,
}

impl CrowdAnkiNoteModelJson {
    fn validate_supported_defaults(&self) -> Result<(), CrowdAnkiError> {
        if self.latex_post != "\\end{document}"
            || self.latex_pre != default_latex_pre()
            || self.latex_svg
            || !self.req.is_empty()
            || self.sortf != 0
            || !self.tags.is_empty()
            || !self.vers.is_empty()
        {
            return Err(CrowdAnkiError::Unsupported(format!(
                "note model {} has non-default CrowdAnki options that are not modeled yet",
                self.name
            )));
        }
        Ok(())
    }

    fn into_note_type(
        self,
        id: StableId,
        field_ids: Vec<StableId>,
        template_ids: Vec<StableId>,
    ) -> Result<(String, StableId, NoteType), CrowdAnkiError> {
        if self.kind != "NoteModel" {
            return Err(CrowdAnkiError::Unsupported(format!(
                "expected note model __type__ NoteModel, found {}",
                self.kind
            )));
        }
        if self.model_type != 0 {
            return Err(CrowdAnkiError::Unsupported(format!(
                "only standard note models are supported, found type {}",
                self.model_type
            )));
        }
        self.validate_supported_defaults()?;

        let mut adapter_ids = AdapterIds::new();
        adapter_ids.insert("crowdanki:uuid", self.crowdanki_uuid.clone());

        let fields = self
            .flds
            .into_iter()
            .zip(field_ids)
            .enumerate()
            .map(|(index, (field, id))| {
                field.validate_supported_defaults(index)?;
                Ok(FieldDefinition {
                    id,
                    name: field.name,
                    rtl: field.rtl,
                    message_pattern: None,
                })
            })
            .collect::<Result<Vec<_>, CrowdAnkiError>>()?;

        let card_templates = self
            .tmpls
            .into_iter()
            .zip(template_ids)
            .map(|(template, id)| {
                template.validate_supported_defaults()?;
                Ok(CardTemplate {
                    id,
                    name: template.name,
                    variables: BTreeMap::new(),
                    question_format: template.qfmt,
                    answer_format: template.afmt,
                    adapter_ids: AdapterIds::new(),
                })
            })
            .collect::<Result<Vec<_>, CrowdAnkiError>>()?;

        let note_type = NoteType {
            id: id.clone(),
            name: self.name,
            variables: BTreeMap::new(),
            fields,
            card_templates,
            styling: self.css,
            adapter_ids,
        };

        Ok((self.crowdanki_uuid, id, note_type))
    }
}

#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct CrowdAnkiFieldJson {
    font: String,
    media: Vec<serde_json::Value>,
    name: String,
    ord: usize,
    rtl: bool,
    size: usize,
    sticky: bool,
}

impl CrowdAnkiFieldJson {
    fn validate_supported_defaults(&self, expected_ord: usize) -> Result<(), CrowdAnkiError> {
        if self.font != "Arial"
            || !self.media.is_empty()
            || self.ord != expected_ord
            || self.size != 20
            || self.sticky
        {
            return Err(CrowdAnkiError::Unsupported(format!(
                "field {} has non-default CrowdAnki options that are not modeled yet",
                self.name
            )));
        }
        Ok(())
    }
}

#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct CrowdAnkiTemplateJson {
    afmt: String,
    bafmt: String,
    bfont: Option<String>,
    bqfmt: String,
    bsize: Option<i64>,
    did: Option<i64>,
    name: String,
    ord: i64,
    qfmt: String,
    #[serde(rename = "scratchPad")]
    scratch_pad: Option<i64>,
}

impl CrowdAnkiTemplateJson {
    fn validate_supported_defaults(&self) -> Result<(), CrowdAnkiError> {
        if !self.bafmt.is_empty()
            || self.bfont.as_deref().unwrap_or_default() != ""
            || !self.bqfmt.is_empty()
            || self.bsize.unwrap_or_default() != 0
            || self.did.is_some()
            || self.scratch_pad.unwrap_or_default() != 0
        {
            return Err(CrowdAnkiError::Unsupported(format!(
                "card template {} has non-default browser options that are not modeled yet",
                self.name
            )));
        }
        Ok(())
    }
}

#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct CrowdAnkiNoteJson {
    #[serde(rename = "__type__")]
    type_: String,
    data: String,
    fields: Vec<String>,
    flags: i64,
    guid: String,
    note_model_uuid: String,
    tags: Vec<String>,
}

struct CrowdAnkiNoteSource {
    guid: String,
    first_field: String,
}

impl CrowdAnkiNoteSource {
    fn from_note_json(note: &CrowdAnkiNoteJson) -> Self {
        Self {
            guid: note.guid.clone(),
            first_field: note.fields.first().cloned().unwrap_or_default(),
        }
    }

    fn identity(self) -> ImportedNoteIdentity {
        ImportedNoteIdentity {
            first_field: self.first_field,
            source_guid: self.guid,
        }
    }
}

/// The CrowdAnki-visible source identity used when suggesting an imported note ID.
///
/// `source_guid` is preserved separately as `crowdanki:guid`; it only makes a suggested
/// canonical ID collision-resistant and never replaces the adapter identity.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ImportedNoteIdentity {
    pub first_field: String,
    pub source_guid: String,
}

/// Suggest canonical note IDs from CrowdAnki-visible note identity.
///
/// The algorithm NFC-normalizes first-field text, uses an ASCII-only readable slug when one
/// exists, and otherwise uses `note.imported`. A 48-bit SHA-256 prefix of the normalized first
/// field and source GUID disambiguates every fallback or repeated slug. If that prefix collides
/// within a group, it deterministically expands by four hexadecimal characters through the full
/// 256-bit digest, then appends an ordinal sorted by normalized text and GUID. Consequently input
/// order, locale, and hash-map iteration cannot affect suggestions.
pub fn suggest_imported_note_stable_ids(
    identities: &[ImportedNoteIdentity],
) -> Result<Vec<StableId>, CrowdAnkiError> {
    let mut seen_guids = BTreeSet::new();
    let normalized = identities
        .iter()
        .map(|identity| {
            if identity.source_guid.is_empty() {
                return Err(CrowdAnkiError::Unsupported(
                    "CrowdAnki note has an empty guid; imported note identity requires a source GUID"
                        .to_owned(),
                ));
            }
            if !seen_guids.insert(identity.source_guid.as_str()) {
                return Err(CrowdAnkiError::Unsupported(format!(
                    "CrowdAnki notes share guid {:?}; source GUIDs must be unique",
                    identity.source_guid
                )));
            }
            Ok((
                identity.first_field.nfc().collect::<String>(),
                identity.source_guid.as_str(),
            ))
        })
        .collect::<Result<Vec<_>, CrowdAnkiError>>()?;

    let mut groups = BTreeMap::<String, Vec<usize>>::new();
    for (index, (first_field, _)) in normalized.iter().enumerate() {
        let slug = ascii_slug(first_field);
        let base = if slug.is_empty() {
            "note.imported".to_owned()
        } else {
            format!("note.{slug}")
        };
        groups.entry(base).or_default().push(index);
    }

    let mut suggestions = vec![None; identities.len()];
    for (base, indexes) in groups {
        let needs_suffix = indexes.len() > 1 || base == "note.imported";
        if !needs_suffix {
            suggestions[indexes[0]] = Some(stable_id(&base)?);
            continue;
        }

        let digests = indexes
            .iter()
            .map(|&index| {
                let (first_field, guid) = &normalized[index];
                (index, note_identity_digest(first_field, guid))
            })
            .collect::<Vec<_>>();
        let digest_length = (12..=64)
            .step_by(4)
            .find(|&length| {
                let mut prefixes = BTreeSet::new();
                digests
                    .iter()
                    .all(|(_, digest)| prefixes.insert(&digest[..length]))
            })
            .unwrap_or(64);

        let mut equal_digests = BTreeMap::<String, Vec<usize>>::new();
        for (index, digest) in digests {
            equal_digests
                .entry(digest[..digest_length].to_owned())
                .or_default()
                .push(index);
        }
        for (digest, mut equal_indexes) in equal_digests {
            equal_indexes.sort_by_key(|&index| normalized[index].clone());
            for (ordinal, index) in equal_indexes.into_iter().enumerate() {
                let suffix = if ordinal == 0 {
                    digest.clone()
                } else {
                    format!("{digest}-{}", ordinal + 1)
                };
                suggestions[index] = Some(stable_id(&format!("{base}-{suffix}"))?);
            }
        }
    }

    Ok(suggestions
        .into_iter()
        .map(|suggestion| suggestion.expect("every identity suggestion group was populated"))
        .collect())
}

impl CrowdAnkiNoteJson {
    fn into_note(
        self,
        note_types: &BTreeMap<StableId, NoteType>,
        note_type_by_uuid: &BTreeMap<String, StableId>,
        id: StableId,
    ) -> Result<Note, CrowdAnkiError> {
        if self.type_ != "Note" {
            return Err(CrowdAnkiError::Unsupported(format!(
                "expected note __type__ Note, found {}",
                self.type_
            )));
        }
        if !self.data.is_empty() || self.flags != 0 {
            return Err(CrowdAnkiError::Unsupported(format!(
                "note {} has non-default data/flags that are not modeled yet",
                self.guid
            )));
        }
        let note_type_id = note_type_by_uuid
            .get(&self.note_model_uuid)
            .ok_or_else(|| {
                CrowdAnkiError::Unsupported(format!(
                    "note references missing note_model_uuid {}",
                    self.note_model_uuid
                ))
            })?
            .clone();
        let note_type = note_types
            .get(&note_type_id)
            .expect("note type id came from note type map");
        if self.fields.len() != note_type.fields.len() {
            return Err(CrowdAnkiError::Unsupported(format!(
                "note {} has {} fields but note type {} has {} fields",
                self.guid,
                self.fields.len(),
                note_type.id,
                note_type.fields.len()
            )));
        }

        let fields = note_type
            .fields
            .iter()
            .zip(self.fields)
            .map(|(field, value)| (field.id.clone(), FieldValue::Scalar(value)))
            .collect();
        let mut adapter_ids = AdapterIds::new();
        adapter_ids.insert("crowdanki:guid", self.guid);

        Ok(Note {
            id,
            note_type_id,
            variables: BTreeMap::new(),
            fields,
            tags: self.tags.into_iter().collect(),
            adapter_ids,
        })
    }
}

fn selected_id(
    selected_ids: &BTreeMap<String, StableId>,
    source_path: &str,
    suggested: StableId,
) -> Result<StableId, CrowdAnkiError> {
    Ok(selected_ids.get(source_path).cloned().unwrap_or(suggested))
}

fn suggested_id_collision_resolution() -> &'static str {
    "generate a CrowdAnki import plan and select distinct reviewed overrides before applying it"
}

fn reverse_map_strict_image_fields(
    note: &mut Note,
    media_path_lookup: &BTreeMap<String, Option<StableId>>,
) {
    let field_ids = note.fields.keys().cloned().collect::<Vec<_>>();
    for field_id in field_ids {
        let Some(value) = note.fields.get(&field_id).and_then(FieldValue::as_scalar) else {
            continue;
        };
        let Some(paths) = media::strict_image_tag_paths(value) else {
            continue;
        };

        let mut images = Vec::new();
        for path in paths {
            let Some(Some(media_id)) = media_path_lookup.get(&path) else {
                images.clear();
                break;
            };
            images.push(FieldImageReference {
                media_id: media_id.clone(),
            });
        }
        if images.is_empty() {
            continue;
        }

        note.fields.insert(field_id, FieldValue::Images(images));
    }
}

fn media_path_lookup(
    media: &BTreeMap<StableId, MediaReference>,
    ambiguous_paths: &BTreeSet<String>,
) -> BTreeMap<String, Option<StableId>> {
    let mut lookup: BTreeMap<String, Option<StableId>> = ambiguous_paths
        .iter()
        .map(|path| (path.clone(), None))
        .collect();

    for (id, reference) in media {
        if ambiguous_paths.contains(&reference.path) {
            lookup.insert(reference.path.clone(), None);
            continue;
        }
        lookup
            .entry(reference.path.clone())
            .and_modify(|existing| *existing = None)
            .or_insert_with(|| Some(id.clone()));
    }

    lookup
}

fn duplicate_paths(paths: &[String]) -> BTreeSet<String> {
    let mut seen = BTreeSet::new();
    let mut duplicates = BTreeSet::new();
    for path in paths {
        if !seen.insert(path.clone()) {
            duplicates.insert(path.clone());
        }
    }
    duplicates
}

fn prefixed_stable_id(prefix: &str, source: &str) -> Result<StableId, CrowdAnkiError> {
    let normalized = source.nfc().collect::<String>();
    let slug = ascii_slug(&normalized);
    let suffix = if slug.is_empty() {
        format!(
            "imported-{}",
            text_identity_digest(prefix, &normalized)[..12].to_owned()
        )
    } else {
        slug
    };
    stable_id(&format!("{prefix}.{suffix}"))
}

fn ascii_slug(source: &str) -> String {
    let mut slug = String::new();
    let mut last_was_separator = false;
    for ch in source.chars() {
        if ch.is_ascii_alphanumeric() {
            slug.push(ch.to_ascii_lowercase());
            last_was_separator = false;
        } else if !last_was_separator && !slug.is_empty() {
            slug.push('-');
            last_was_separator = true;
        }
    }
    while slug.ends_with('-') {
        slug.pop();
    }
    slug
}

fn note_identity_digest(first_field: &str, source_guid: &str) -> String {
    let mut hasher = Sha256::new();
    hasher.update(b"brain-brew/crowdanki/imported-note-id/v1\0");
    hash_text_part(&mut hasher, first_field);
    hash_text_part(&mut hasher, source_guid);
    format!("{:x}", hasher.finalize())
}

fn text_identity_digest(prefix: &str, normalized_source: &str) -> String {
    let mut hasher = Sha256::new();
    hasher.update(b"brain-brew/crowdanki/imported-text-id/v1\0");
    hash_text_part(&mut hasher, prefix);
    hash_text_part(&mut hasher, normalized_source);
    format!("{:x}", hasher.finalize())
}

fn hash_text_part(hasher: &mut Sha256, text: &str) {
    hasher.update((text.len() as u64).to_be_bytes());
    hasher.update(text.as_bytes());
}

fn stable_id(value: &str) -> Result<StableId, CrowdAnkiError> {
    StableId::new(value).map_err(|_| CrowdAnkiError::StableId(value.to_owned()))
}