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

let fmt d = Printf.sprintf "%04d-%02d-%02d" (D.year d) (D.month d) (D.day d)

let easter_report y =
  [ ("easter", C.gregorian_easter y);
    ("ash-wednesday", C.ash_wednesday y);
    ("palm-sunday", C.palm_sunday y);
    ("ascension", C.ascension y);
    ("pentecost", C.pentecost y);
    ("corpus-christi", C.corpus_christi y) ]
  |> List.iter (fun (name, d) -> Printf.printf "%s %s\n" name (fmt d))

(* Fix 1 follow-up (cli-flags-report, 2026-08-27, coordinator review):
   `--rite` used to be refused here with the message "has no effect on
   `temporal`" -- FALSE, not merely stale: this function calls
   [Rite_ef.Temporal_ef.temporal] directly, the whole rite-specific
   temporal cycle (season, week numbering, slugs), so an OF run would
   differ on essentially every line (OF has five seasons, no
   Septuagesima, and every slug carries an "of-" prefix rather than
   "ef-"). The refusal comment this function's own dispatch site
   originally carried conflated two different flags' justifications:
   `--overlay` genuinely has no effect here ("runs the temporal cycle
   BEFORE any sanctoral layer exists" -- still true, still the reason
   --overlay stays refused, unaffected by this fix), but that says
   nothing about `--rite`, which this function was never actually
   insulated from -- only refused at the CLI layer, which is not the
   same claim. [Colitur_kernel.Record.of_temporal] was already fully
   polymorphic over [('s, 'r)] (record.mli), so this is the same
   plumbing already done for `day`/`readings`/etc, not new library work. *)
let temporal_report ~rite ~pretty y =
  let jan1 = match D.make ~year:y ~month:1 ~day:1 with
    | Ok t -> t
    | Error e -> failwith e
  in
  let dec31 = match D.make ~year:y ~month:12 ~day:31 with
    | Ok t -> t
    | Error e -> failwith e
  in
  (* [week] is "" for roughly 30 days a year (outside any numbered week);
     printed as-is, that collapses two of the seven space-separated fields
     into a double space, so naive field-position parsing (e.g. awk '{print
     $4}') silently reads the wrong column on those days. Emit "-" instead,
     so every line always has exactly seven single-space-separated fields. *)
  let field s = if s = "" then "-" else s in
  let record_of_day =
    match rite with
    | `Ef -> fun d -> Colitur_kernel.Record.of_temporal ~rite:Rite_ef.Temporal_ef.id
                Rite_ef.Vocab_ef.vocab d (Rite_ef.Temporal_ef.temporal d)
    | `Of -> fun d -> Colitur_kernel.Record.of_temporal ~rite:Rite_of.Temporal_of.id
                Rite_of.Vocab_of.vocab d (Rite_of.Temporal_of.temporal d)
  in
  let d = ref jan1 in
  while D.compare !d dec31 <= 0 do
    let r = record_of_day !d in
    (if pretty then
       (* The temporal cycle has no sanctoral, so there is never a
          commemoration to indent -- same row shape as `day --pretty`, minus
          that. Shown here from the flat Record rather than a Liturgical_day
          because that is all this report ever had. *)
       Printf.printf "%s  %s  %s%s  %s%s\n"
         (Pretty.pad Pretty.w_date r.Colitur_kernel.Record.date)
         (Pretty.pad Pretty.w_dow
            (let w = r.Colitur_kernel.Record.weekday in
             String.sub w 0 (min 3 (String.length w))))
         (Pretty.swatch r.Colitur_kernel.Record.colour)
         (Printf.sprintf "  %s" (Pretty.pad Pretty.w_rank r.Colitur_kernel.Record.rank))
         (Pretty.pad Pretty.w_season
            (match r.Colitur_kernel.Record.week with
             | "" -> r.Colitur_kernel.Record.season
             | w -> r.Colitur_kernel.Record.season ^ " " ^ w))
         r.Colitur_kernel.Record.slug
     else
       Printf.printf "%s %s %s %s %s %s %s\n" r.Colitur_kernel.Record.date
         r.Colitur_kernel.Record.weekday r.Colitur_kernel.Record.season
         (field r.Colitur_kernel.Record.week) r.Colitur_kernel.Record.slug
         r.Colitur_kernel.Record.rank r.Colitur_kernel.Record.colour);
    d := D.add_days !d 1
  done

(* Task 11: the fully resolved EF calendar (temporal AND sanctoral,
   occurrence and transfers applied), one line per civil-year day --
   "YYYY-MM-DD weekday season week slug rank colour [+commemoration-slug]...".
   [temporal_report] above only ever showed the temporal cycle in isolation
   ([Rite_ef.Temporal_ef.temporal] directly, no sanctoral layer, no
   [Precedence] contest); this is the first CLI path that runs every piece
   Plan 3 built -- [Colitur_kernel.Layer], [Overlay], [Precedence_ef],
   [Calendar] -- against real data. *)

(* [data/ef/sanctoral.sexp] and [data/ef/adjustments.sexp] are located
   relative to the BUILD TREE, not the process's own cwd: cwd varies with
   how the binary is invoked (a user's shell for `dune exec colitur --`, a
   dune cram test's own sandboxed temp directory for `test/cli.t`) and
   nothing in this project's build pins it to the repository root. A
   build-time constant substituted via dune's [%{workspace_root}] was tried
   first and rejected: it is resolved RELATIVE TO THE BUILD ACTION'S OWN
   directory (empirically "." here, not an absolute path -- dune keeps
   build actions relocatable), so it silently reproduces the same
   cwd-dependence this is trying to eliminate, just baked in at build time
   instead of read at run time; confirmed by the resulting `colitur day`
   failing to find its own data outside the exact directory the build
   happened to run in.

   [Sys.executable_name] does not have that problem -- on Linux it resolves
   through /proc/self/exe, which the kernel always reports as the
   executable's own canonical absolute path, even when the process was
   launched through a symlink (verified against dune's own cram sandbox,
   which places exactly such a symlink; see the task report). dune's default
   ("no [(sandbox ...)] declared") build context mirrors the ENTIRE source
   tree under _build/default/, unconditionally, so climbing from
   _build/default/bin/main.exe up two directories and back down into data/
   always finds both files, regardless of the caller's own cwd.

   RESOLVED: the "known limitation" this comment used to end on -- that a
   `dune install`-style deployment (executable copied to a prefix with no
   adjacent _build/default/data/) had no resolution strategy, and would exit 2
   unable to find sanctoral.sexp -- is now handled by probing candidates in
   order rather than computing one path and hoping. data/dune installs the
   four runtime files into <prefix>/share/colitur/ef/.

   Two layouts are probed, and one override short-circuits both:

     [COLITUR_DATA_DIR], when set and non-blank -- an explicit override. It
     NEVER falls through: if it is set and does not contain the data, that is
     an error naming the directory, not a reason to quietly use different
     data. A packager or operator who names a directory has stated an
     intent, and silently calendaring off some other copy because theirs was
     wrong is precisely the silent substitution this project refuses
     everywhere else (CLAUDE.md's first binding decision: divergence is
     flagged LOUDLY, never silently swallowed). Getting this wrong is not
     hypothetical -- the first version of this function did fall through, and
     a deliberately bogus COLITUR_DATA_DIR produced a full, plausible,
     entirely un-flagged year off the build tree's data.

     Otherwise, in order:
     1. <exedir>/../share/colitur/ef -- the INSTALLED layout, from an opam or
        `dune install` prefix where the binary sits at <prefix>/bin/colitur.
        data/dune puts the four runtime files there.
     2. <exedir>/../data/ef -- the BUILD TREE, which is what `dune exec` and
        the cram tests use.

   A candidate is accepted only if sanctoral.sexp is actually readable inside
   it, not merely because the directory exists: an empty or half-populated
   share/colitur/ef (a failed install, a partially removed package) falls
   through to a working build tree rather than shadowing it and then failing
   at load time with a confusing per-file error. Verified by simulation, not
   assumed.

   Environment reads are fine HERE and only here: this is bin/, not the
   kernel, whose contract forbids them (CLAUDE.md, "Kernel is total &
   deterministic: no wall-clock, randomness, or environment reads"). Nothing
   below the CLI ever learns where the data came from -- the loaders take a
   path. *)
let data_dir () =
  let has_data d = Sys.file_exists (Filename.concat d "sanctoral.sexp") in
  let prefix = Filename.dirname (Filename.dirname Sys.executable_name) in
  let installed = List.fold_left Filename.concat prefix [ "share"; "colitur"; "ef" ] in
  let build_tree = Filename.concat prefix (Filename.concat "data" "ef") in
  match Sys.getenv_opt "COLITUR_DATA_DIR" with
  | Some d when String.trim d <> "" ->
      if has_data d then d
      else begin
        Printf.eprintf
          "colitur: COLITUR_DATA_DIR is set to %s, which contains no sanctoral.sexp\n\
           colitur: refusing to fall back to another data directory -- unset it, or point it at one\n"
          d;
        exit 2
      end
  | _ -> if has_data installed then installed else build_tree

(* [lang_dir] mirrors [data_dir]'s own probe order exactly -- installed
   prefix first, then the build tree -- because a language file must resolve
   the same way calendar data does, or an installed binary could find one
   and not the other (exactly the defect a prior fix round found: lang/ had
   no install rule at all, and the installed binary silently fell back to
   raw slugs with no error). Accepted only if la.ini is actually readable
   there, matching [data_dir]'s own "a candidate counts only if the data is
   really there" discipline. *)
let lang_dir () =
  let prefix = Filename.dirname (Filename.dirname Sys.executable_name) in
  let installed = List.fold_left Filename.concat prefix [ "share"; "colitur"; "lang" ] in
  if Sys.file_exists (Filename.concat installed "la.ini") then installed
  else Filename.concat prefix "lang"

(* Loads the universal sanctoral layer and applies the one hand-authored
   overlay over it (data/ef/adjustments.sexp -- see that file's own header):
   [Overlay.apply]'s diagnostics are never silently dropped (Overlay.mli),
   so any that come back -- expected to be none in the committed data; see
   the overlay file's own comment on when one WOULD fire -- are printed to
   stderr, loudly, without aborting the run. *)
(* [user_overlays] are applied AFTER the shipped adjustments, in the order
   given, never instead of them. That ordering is the whole point: the shipped
   overlay carries RG 110's own 30 June companion, the Major Litanies, St
   Barbara and Rogation Wednesday, and a user file that REPLACED it would
   silently drop all four while looking like it had merely added a local
   feast. {!Overlay.merge}'s last-writer-wins is what lets a local calendar
   still override a universal entry deliberately, by naming its slug.

   Diagnostics stay loud but non-fatal, and that matters more for a user file
   than for the shipped one: a directive naming a slug that does not exist (a
   typo in a diocesan calendar) prints to stderr and the run continues, rather
   than the entry silently doing nothing. A file that fails to LOAD is fatal,
   exactly as the shipped overlay is -- a malformed calendar is not something
   to carry on past. *)
let load_ef_layer ?(user_overlays = []) () =
  let dir = data_dir () in
  let sanctoral_path = Filename.concat dir "sanctoral.sexp" in
  let adjustments_path = Filename.concat dir "adjustments.sexp" in
  (* An overlay handed to --overlay must be the S-expression form. The INI
     form is real but is a SOURCE format: `colitur convert` turns it into one.
     Feeding the INI here otherwise fails deep inside the sexp reader with
     "more than one S-expression in file", which names neither the cause nor
     the cure. Detect it and say both. *)
  let looks_like_ini path =
    match open_in path with
    | exception _ -> false
    | ic ->
        (* Skip the comment header and stop at the first real line. The cap
           only bounds how much of a binary file gets read; it is NOT a guess
           at how long a header may be. The first version capped at 40 and
           poland.ini's own header is 43 lines, so the detection silently
           never fired on the very file it was written for. *)
        let rec scan n =
          if n > 2000 then false
          else
            match input_line ic with
            | exception End_of_file -> false
            | line ->
                let l = String.trim line in
                if l = "" || l.[0] = ';' || l.[0] = '#' then scan (n + 1)
                else String.length l > 1 && l.[0] = '[' && l.[String.length l - 1] = ']'
        in
        let r = scan 0 in
        close_in_noerr ic;
        r
  in
  let load_overlay path =
    match Colitur_kernel.Overlay.load Rite_ef.Vocab_ef.rank_of_sexp path with
    | Error _ when looks_like_ini path ->
        Error
          (Printf.sprintf
             "%s looks like an INI overlay, not an S-expression one.\n\
              colitur: convert it first:  colitur convert %s > overlay.sexp"
             path path)
    | Error e -> Error (Printf.sprintf "failed to load %s: %s" path e)
    | Ok o -> Ok o
  in
  let rec load_all acc = function
    | [] -> Ok (List.rev acc)
    | p :: rest -> ( match load_overlay p with Error e -> Error e | Ok o -> load_all (o :: acc) rest)
  in
  match Colitur_kernel.Layer.load Rite_ef.Vocab_ef.rank_of_sexp sanctoral_path with
  | Error e -> Error (Printf.sprintf "failed to load %s: %s" sanctoral_path e)
  | Ok layer -> (
      match load_all [] (adjustments_path :: user_overlays) with
      | Error e -> Error e
      | Ok overlays ->
          (* Diagnostics come back to the caller rather than being printed
             here: `day`/`readings` want them on stderr beside a year of
             output, while `check` wants them on stdout, attributed to the
             overlay that produced them, and counted. Printing at the source
             made the second impossible. *)
          Ok (Colitur_kernel.Overlay.merge layer overlays))

(* Sibling to [load_ef_layer] above, same reasoning: [Rite_ef.context] now
   takes [~lectionary] rather than loading data/ef/lectionary.sexp itself
   (fix round 1, coordinator review -- a prior version had [Rite_ef]'s own
   [context] load the file as a side effect of being linked, which killed
   `colitur easter <year>` -- no lectionary data touched at all -- the
   moment that file was missing from a bare `dune build`'s own default
   target). Routed through the same [result] failure path as
   [load_ef_layer], so a missing/malformed file is reported via
   `colitur: %s` and `exit 2`, never an uncaught exception -- restoring the
   promise [Lectionary.load]'s own .mli makes ("failures come back as
   [Error], never as an exception"), which the reverted version broke by
   re-wrapping it in [failwith] at module init where no caller could catch
   it. *)
let load_ef_lectionary () =
  let path = Filename.concat (data_dir ()) "lectionary.sexp" in
  match Colitur_kernel.Lectionary.load path with
  | Error e -> Error (Printf.sprintf "failed to load %s: %s" path e)
  | Ok lectionary -> Ok lectionary

(* Sibling to [load_ef_lectionary] above, same reasoning and the same
   [result] failure path: data/ef/commons.sexp holds the Commons of the
   1962 Missal plus the per-saint assignments that route a readingless
   class-3 feast to one, and [Rite_ef.context] takes it as [~commons]
   rather than reading it itself. Its own loader validates the file
   (duplicate ids, empty formularies, assignments naming a common that does
   not exist) and reports every failure as [Error]. *)
let load_ef_commons () =
  let path = Filename.concat (data_dir ()) "commons.sexp" in
  match Rite_ef.Lectionary_ef.Commons.load path with
  | Error e -> Error (Printf.sprintf "failed to load %s: %s" path e)
  | Ok commons -> Ok commons

(* Task 5 (2026-08-25-colitur-of-phases-3-5): `--rite of`, the OF (post-1970)
   counterpart of everything above. Mirrors [data_dir]'s own probe order
   (installed prefix, then the build tree) but scoped to "of" and keyed on
   [calendar-2002.sexp] rather than [sanctoral.sexp] -- Task 1's own
   transcription of the General Roman Calendar, the OF base layer.

   Deliberately does NOT honour [COLITUR_DATA_DIR]: that variable's existing
   contract (documented on [data_dir] above) is "an explicit override
   pointing at a single flat directory containing sanctoral.sexp" -- an
   EF-shaped contract this function would either have to silently reinterpret
   (the same directory, now also expected to carry calendar-2002.sexp) or
   split into a second variable, and neither is this task's call to make.
   Left unaddressed rather than guessed at. *)
let of_data_dir () =
  let has_data d = Sys.file_exists (Filename.concat d "calendar-2002.sexp") in
  let prefix = Filename.dirname (Filename.dirname Sys.executable_name) in
  let installed = List.fold_left Filename.concat prefix [ "share"; "colitur"; "of" ] in
  let build_tree = Filename.concat prefix (Filename.concat "data" "of") in
  if has_data installed then installed else build_tree

(* [load_of_layer]'s own [~user_overlays] follows [load_ef_layer]'s exact
   discipline: applied AFTER the shipped base, never instead of it. The OF
   base is [calendar-2002.sexp] (Task 1) plus all 13 decree-chronological
   amendment overlays (Task 2, data/of/amendments/*.sexp) -- never edited
   after the fact, per that file's own header -- so a diocesan/local
   overlay a user supplies via [--overlay] layers on top of THOSE, exactly
   mirroring how an EF user overlay layers on top of adjustments.sexp. *)
let of_amendment_files =
  [ "001-padre-pio.sexp"; "002-juan-diego-cuauhtlatoatzin.sexp"; "003-our-lady-of-guadalupe.sexp";
    "004-john-xxiii-john-paul-ii.sexp"; "005-mary-magdalene-rank.sexp"; "006-mary-mother-of-the-church.sexp";
    "007-paul-vi.sexp"; "008-our-lady-of-loreto.sexp"; "009-faustina-kowalska.sexp";
    "010-narek-avila-hildegard.sexp"; "011-martha-mary-lazarus.sexp"; "012-teresa-of-calcutta.sexp";
    "013-john-henry-newman.sexp" ]

let load_of_layer ?(user_overlays = []) () =
  let dir = of_data_dir () in
  let base_path = Filename.concat dir "calendar-2002.sexp" in
  let amendment_paths =
    List.map (fun name -> Filename.concat dir (Filename.concat "amendments" name)) of_amendment_files
  in
  let load_overlay path =
    match Colitur_kernel.Overlay.load Rite_of.Vocab_of.rank_of_sexp path with
    | Error e -> Error (Printf.sprintf "failed to load %s: %s" path e)
    | Ok o -> Ok o
  in
  let rec load_all acc = function
    | [] -> Ok (List.rev acc)
    | p :: rest -> ( match load_overlay p with Error e -> Error e | Ok o -> load_all (o :: acc) rest)
  in
  match Colitur_kernel.Layer.load Rite_of.Vocab_of.rank_of_sexp base_path with
  | Error e -> Error (Printf.sprintf "failed to load %s: %s" base_path e)
  | Ok layer -> (
      match load_all [] (amendment_paths @ user_overlays) with
      | Error e -> Error e
      | Ok overlays -> Ok (Colitur_kernel.Overlay.merge layer overlays))

(* Sibling to [load_ef_lectionary], same [~lectionary]-is-a-caller-supplied-
   parameter discipline [Rite_of.context]'s own .mli documents: a missing or
   malformed data/of/lectionary.sexp is reported via [Error], never an
   uncaught exception. *)
let load_of_lectionary () =
  let path = Filename.concat (of_data_dir ()) "lectionary.sexp" in
  match Colitur_kernel.Lectionary.load path with
  | Error e -> Error (Printf.sprintf "failed to load %s: %s" path e)
  | Ok lectionary -> Ok lectionary

(* [load_of_data]/[resolved_of_year_days]/[day_report_of]/[readings_report_of]
   mirror [load_ef_data]/[resolved_year_days]/[day_report]/[readings_report]
   exactly, one rite down: no [~commons] (OF's [Lectionary_of.readings] has
   none to thread, see rite_of.mli), and every EF-specific module reference
   swapped for its OF sibling. Duplicated rather than parameterised over the
   rite for the same reason test_amendments_of.ml's own header gives for its
   near-identical EF twin: no [.mli] either file shares, and a shared
   higher-order version would have to abstract over TWO different [Vocab.t]
   instantiations plus TWO different [Rite.t] result types, which
   [day_line]/[readings_line] below cannot be generic over either (they print
   rite-specific vocabulary strings). *)
let load_of_data ?(user_overlays = []) () =
  match
    Result.map
      (fun (layer, diagnostics) ->
        List.iter
          (fun d -> Printf.eprintf "colitur: %s\n" (Colitur_kernel.Overlay.diagnostic_to_string d))
          diagnostics;
        layer)
      (load_of_layer ~user_overlays ())
  with
  | Error msg -> Error msg
  | Ok layer -> ( match load_of_lectionary () with Error msg -> Error msg | Ok lectionary -> Ok (layer, lectionary))

let resolved_of_year_days ~overlays y =
  match load_of_data ~user_overlays:overlays () with
  | Error msg ->
      Printf.eprintf "colitur: %s\n" msg;
      exit 2
  | Ok (layer, lectionary) ->
      let context = Rite_of.context ~lectionary in
      let module Cal = Colitur_kernel.Calendar in
      let by_rata : (int, (Rite_of.Vocab_of.season, Rite_of.Vocab_of.rank) Colitur_kernel.Liturgical_day.t) Hashtbl.t =
        Hashtbl.create 400
      in
      let index days =
        Array.iter
          (fun (d : (Rite_of.Vocab_of.season, Rite_of.Vocab_of.rank) Colitur_kernel.Liturgical_day.t) ->
            Hashtbl.replace by_rata (D.to_rata d.Colitur_kernel.Liturgical_day.date) d)
          days
      in
      index (Cal.year context layer (y - 1));
      index (Cal.year context layer y);
      let jan1 = match D.make ~year:y ~month:1 ~day:1 with Ok t -> t | Error e -> failwith e in
      let dec31 = match D.make ~year:y ~month:12 ~day:31 with Ok t -> t | Error e -> failwith e in
      let d = ref jan1 in
      let acc = ref [] in
      while D.compare !d dec31 <= 0 do
        (match Hashtbl.find_opt by_rata (D.to_rata !d) with
        | Some day -> acc := day :: !acc
        | None -> Printf.eprintf "colitur: internal error: no resolved day for %s\n" (D.to_iso8601 !d));
        d := D.add_days !d 1
      done;
      List.rev !acc

(* [~lang] resolves the observed slug to a display NAME, appended as a new
   LAST field rather than substituted into the slug's own position: a name
   contains spaces (Latin and English both), and inserting it where the slug
   used to sit would break every fixed-position field after it (rank,
   colour, the commemoration tail) for anyone parsing this line by column --
   the same reasoning that keeps `readings` a separate command rather than
   extra columns on `day`. [slug] itself is therefore untouched by [lang] in
   this row, exactly as [Colitur_render.View]'s own [slug] field is.

   The trailing field is present only when the resolved name actually
   DIFFERS from the slug -- not gated on [--raw] as a special case, but as a
   direct consequence of [Lang.raw] being the identity table (lang.mli):
   under [--raw], [name = slug] always, so the field is always absent and
   this row is BYTE-IDENTICAL to what it printed before this feature
   existed, with no `if raw then ...` branch anywhere in this function. The
   same holds for any language file that has genuinely no entry for a given
   slug -- a miss also returns the slug (lang.mli), so an untranslated day
   quietly gets no trailing field rather than a field that redundantly
   repeats the slug it already printed. *)
let day_line ~lang (d : (Rite_ef.Vocab_ef.season, Rite_ef.Vocab_ef.rank) Colitur_kernel.Liturgical_day.t)
    =
  let t = d.Colitur_kernel.Liturgical_day.temporal in
  let cel = d.Colitur_kernel.Liturgical_day.observed in
  let week =
    match t.Colitur_kernel.Temporal.week with Some n -> string_of_int n | None -> "-"
  in
  let commemoration_suffix (c, _) =
    " +" ^ Colitur_kernel.Slug.to_string c.Colitur_kernel.Celebration.slug
  in
  let commemorations =
    String.concat "" (List.map commemoration_suffix d.Colitur_kernel.Liturgical_day.commemorations)
  in
  let slug_s = Colitur_kernel.Slug.to_string cel.Colitur_kernel.Celebration.slug in
  let name = Colitur_naming.Lang.celebration lang slug_s in
  let name_suffix = if name = slug_s then "" else " " ^ name in
  Printf.printf "%s %s %s %s %s %s %s%s%s\n" (D.to_iso8601 d.Colitur_kernel.Liturgical_day.date)
    (D.weekday_to_string t.Colitur_kernel.Temporal.weekday)
    (Rite_ef.Vocab_ef.season_to_string t.Colitur_kernel.Temporal.season)
    week slug_s
    (Rite_ef.Vocab_ef.rank_to_string cel.Colitur_kernel.Celebration.rank)
    (Colitur_kernel.Colour.to_string cel.Colitur_kernel.Celebration.colour)
    commemorations name_suffix

(* The reading citations for a day, as its own row shape rather than extra
   columns on [day_line]'s.

   A SEPARATE COMMAND, not a widening of `colitur day`, and the reason is
   mechanical rather than aesthetic: a citation contains spaces and commas
   ("Ezech 34:11-16", "Ecclus 51:1-8, 12"), while [day_line]'s row is
   space-separated with a variable-length "+slug" commemoration tail.
   Appending citations there would leave the row unsplittable -- no [awk]/
   [cut] field number could recover where the Epistle ends -- which is the
   opposite of the composability the row is shaped for. So `day` keeps its
   format byte-identical (nothing downstream of it changes at all) and the
   citations get a row whose own fields are " | "-delimited, safe for values
   containing spaces.

   This is deliberately a stopgap, and should not be mistaken for the
   project's answer to output formatting: the design calls for one schema
   rendered through a logic-less template engine (CSV/JSON/S-expression),
   which is where this belongs eventually. Two ad-hoc column formats are
   easier to retire later than one overloaded format with parsing rules
   nobody wrote down.

   "-" for an absent part, matching [temporal_report]'s own [field]
   convention for an empty column. On the EF data as it stands no day can
   actually print "-" -- {!Colitur_kernel.Validate}'s "citations"/
   "citations-unresolved" checks assert exactly one First and one Gospel on
   every day of every year 1583..9999 -- but the CLI must not assume a
   guarantee the kernel makes about DATA rather than about types. *)
(* [~lang]: same append-only rule as [day_line] above, using this row's own
   " | " field separator (chosen there precisely because a citation may
   contain spaces or commas) rather than a plain space -- a resolved name
   can equally contain spaces, and " | " is what already keeps this row's
   fields unambiguous. Present only when the resolved name differs from the
   slug, for the identical reason [day_line] gives: under [--raw] this row
   is therefore byte-identical to what it printed before.

   [~sigla] (Task 9) is what [--raw]/[--sigla-style]/[--sigla-book]/
   [--sigla-tradition] actually reach: each stored reference renders
   through {!Colitur_citation.Sigla.format} rather than printing verbatim.
   Under {!Colitur_citation.Sigla.verbatim} (what [--raw] passes) this is
   the identity, so the byte-exact claim above still holds. *)
let readings_line ~lang ~sigla (d : (Rite_ef.Vocab_ef.season, Rite_ef.Vocab_ef.rank) Colitur_kernel.Liturgical_day.t)
    =
  let cel = d.Colitur_kernel.Liturgical_day.observed in
  let part_ref p =
    match
      List.find_opt
        (fun (c : Colitur_kernel.Citation.t) -> c.Colitur_kernel.Citation.part = p)
        d.Colitur_kernel.Liturgical_day.citations
    with
    | Some c -> Colitur_citation.Sigla.format sigla c.Colitur_kernel.Citation.reference
    | None -> "-"
  in
  (* The Second reading (OLM n. 67: a Sunday/solemnity's own three-reading
     shape) is present-or-absent, not present-or-"-": unlike First/Gospel
     ({!Colitur_kernel.Validate}'s "citations" check guarantees exactly one
     of each on every day of every rite), a day may legitimately carry no
     Second reading at all ([Rite.t.citation_shapes] for EF is
     [[First; Gospel]] alone), and EF never carries one. So this is an
     append-only field, the same discipline [name_suffix] below already
     uses -- absent, it contributes the empty string and this row is
     byte-identical to what it printed before the Second reading existed. *)
  let second_suffix =
    match
      List.find_opt
        (fun (c : Colitur_kernel.Citation.t) -> c.Colitur_kernel.Citation.part = Colitur_kernel.Citation.Second)
        d.Colitur_kernel.Liturgical_day.citations
    with
    | Some c -> " | " ^ Colitur_citation.Sigla.format sigla c.Colitur_kernel.Citation.reference
    | None -> ""
  in
  let slug_s = Colitur_kernel.Slug.to_string cel.Colitur_kernel.Celebration.slug in
  let name = Colitur_naming.Lang.celebration lang slug_s in
  let name_suffix = if name = slug_s then "" else " | " ^ name in
  Printf.printf "%s %s | %s%s | %s%s\n"
    (D.to_iso8601 d.Colitur_kernel.Liturgical_day.date)
    slug_s
    (part_ref Colitur_kernel.Citation.First)
    second_suffix
    (part_ref Colitur_kernel.Citation.Gospel)
    name_suffix

(* Task 4 (celebrant-rubrics-phase1): the day's own Mass formulary -- which
   slug's Mass is actually said, and how that was decided
   ({!Colitur_kernel.Mass_formulary.source}: proper/own/preceding-sunday/
   common/votive).

   A SEPARATE command from `day` and `readings`, for the identical mechanical
   reason CLAUDE.md already records for `readings`: a formulary NAME (not
   built yet, but the reason this row is shaped the way it is) contains
   spaces ("Mass of the 9th Sunday after Pentecost"), and `day`'s own row is
   fixed-width space-separated with a variable-length "+slug" tail, so
   appending anything with its own internal whitespace there would leave the
   row unsplittable by field number.

   TAB-separated rather than reusing [readings_line]'s " | " -- deliberately
   a THIRD delimiter, not a second use of the existing one -- because a
   later column on this row (the resolved formulary name, below) can itself
   contain a literal "|" inside punctuation a citation never does, and
   because TAB is what stays unambiguous once a field may carry both spaces
   and arbitrary punctuation.

   Fix 2 (cli-flags-report, 2026-08-27): `rubrics` DOES now take
   --lang/--raw -- reversing this comment's own former claim after
   auditing it against the evidence rather than the flag surface alone.
   [said] (below) is a SLUG, exactly the same kind of machine key
   [day_line]'s own [slug_s] is, and every other row that prints one
   already resolves it to a display name under --lang; there turned out to
   be no principled reason for this row to be the one exception. --raw and
   --sigla-* are NOT symmetric here: --raw genuinely applies (see
   [rubrics_name] below), but --sigla-* still has nothing to act on -- this
   row prints no citation of its own, so [reject_sigla "rubrics"]
   (bin/main.ml's own dispatch) is unchanged. *)
(* [d.formulary] is documented as [Some] on every day of every year for EF,
   asserted by {!Colitur_kernel.Validate}'s own ["formulary"] check -- but
   the type itself permits [None] (a rite with no lectionary), so this
   prints "-" rather than pattern-matching partially and crashing on a
   guarantee that belongs to DATA, not to the type.

   Task 5 (celebrant-rubrics-phase1): a fourth column, whether the Creed is
   said (EF: RG 475-476, {!Rite_ef.Rubrics_ef.creed}) -- "true"/"false"
   ([string_of_bool], not "yes"/"no" or "1"/"0": this row has no other
   boolean column to be consistent with, so OCaml's own literal is the
   least surprising choice for a machine-readable field). Unlike
   [formulary], [d.creed] is a plain [bool] with no [option] to guard: a
   rite that has not implemented the rule answers [false] outright, so
   there is no third "unknown" state this column could ever need to print.

   Whole-branch review fix round: {!Colitur_kernel.Mass_formulary.t.said}
   itself gained an [option] (its own citation has the full account --
   [None] exactly for [Votive], where the shipped data genuinely names no
   slug for the Mass actually said). This column's own OUTPUT does not
   change for that reason: when [said] is [None] it falls back to
   [d.observed]'s own slug -- the SAME value this column always printed
   for a [Votive] day before [said] became honest, and it is a value this
   function already has in scope regardless of [via]. So this is not
   "print a placeholder for the missing case", it is "the value was
   already available from a different field, and still is".

   Task (celebrant-rubrics-phase1, Phase 2): a FIFTH column, whether the
   Gloria in excelsis is said (EF: RG 431-432, {!Rite_ef.Rubrics_ef.gloria})
   -- same [string_of_bool] convention as [creed], same plain [bool] with
   no [option] to guard, same reasoning throughout.

   Task (celebrant-rubrics-phase1, Phase 3): a SIXTH column, which preface
   is said (EF: RG 482-499, {!Rite_ef.Rubrics_ef.preface}) --
   {!Colitur_kernel.Preface.to_string} (e.g. "common", "holy-cross"), or
   "-" when [d.preface] is [None]. UNLIKE [creed]/[gloria], [preface] is a
   genuine [option]: "-" here can mean either of two things ("this rite
   has not implemented the rule" or "this specific day has no Mass to
   preface", {!Colitur_kernel.Rite.t.preface}'s own citation) and this
   column does not distinguish them, the same "-" convention [formulary]'s
   own [None] case already uses two columns to the left, for the identical
   reason. *)
(* No explicit [(season, rank) Liturgical_day.t] annotation, unlike
   [day_line]/[readings_line]: unlike those two, this function never prints
   a rite-specific VOCABULARY string (season/rank name), only fields
   [Rite.t] already makes generic ([formulary]/[creed]/[gloria]/[preface]/
   [observed]/[temporal.office], all of them rite-agnostic per
   liturgical_day.mli) -- so it type-checks fully polymorphic over
   [('s, 'r)] and needs no EF/OF duplicate the way those two do. Reused
   as-is for OF in [rubrics_report] below. *)
(* [rubrics_name] resolves [said]'s slug to a display name, the same
   append-only-if-different discipline [day_line]/[readings_line] already
   use for the OBSERVED celebration's own slug -- but [said] is not always
   the observed celebration ([Mass_formulary.source]'s own citation:
   [Preceding_sunday] names a DIFFERENT day's temporal slug, [Common] names
   a Common's own id), so there is no single [Celebration.t] this function
   can assume [said] belongs to.

   Two [Celebration.t] values are always in scope on any [Liturgical_day.t],
   for either rite: [d.observed] (Proper, the common case) and
   [d.temporal.office] (Own_slug, the day's own temporal office when a
   ferial/weekday resumes it) -- see [Mass_formulary.source]'s own
   constructors and {!Rite_of.Lectionary_of.readings}, which never produces
   [Preceding_sunday]/[Common]/[Votive] at all, so for OF this covers EVERY
   [said] value, not merely the common case. When [said] matches one of
   those two, its own [Celebration.t.names] is consulted FIRST (the same
   preference [day_line_of]'s own [observed_name_of] gives OF's richer,
   verified per-slug names over the generic lang/*.ini table, for the
   identical reason: a collision between an OF slug and an unrelated EF
   entry in that table must not silently print the wrong century's title).
   For EF this is a safe no-op, not a new risk: EF's own [Celebration.t
   .names] is "almost always empty" ([day_line_of]'s own citation), so the
   lookup falls straight through to [Colitur_naming.Lang.celebration] --
   BYTE-IDENTICAL to what [day_line] already does for EF's [slug_s] today.
   When [said] matches NEITHER (EF's [Preceding_sunday]/[Common]/[Votive]
   cases, or a genuine miss), this falls back to the same generic
   lang-table lookup every other row already accepts as its own residual
   imprecision -- nothing here is worse than what [day_line] already
   ships. *)
let rubrics_name ~lang (d : (_, _) Colitur_kernel.Liturgical_day.t) said_slug =
  let module K = Colitur_kernel in
  let cel_opt =
    if K.Slug.to_string d.K.Liturgical_day.observed.K.Celebration.slug = said_slug then
      Some d.K.Liturgical_day.observed
    else if K.Slug.to_string d.K.Liturgical_day.temporal.K.Temporal.office.K.Celebration.slug = said_slug
    then Some d.K.Liturgical_day.temporal.K.Temporal.office
    else None
  in
  let from_data =
    match cel_opt with
    | None -> None
    | Some cel -> (
        match K.Lang.of_string (Colitur_naming.Lang.code lang) with
        | Error _ -> None
        | Ok l -> K.Names.find cel.K.Celebration.names l)
  in
  match from_data with Some n -> n | None -> Colitur_naming.Lang.celebration lang said_slug

let rubrics_line ~lang (d : (_, _) Colitur_kernel.Liturgical_day.t) =
  let said, via =
    match d.Colitur_kernel.Liturgical_day.formulary with
    | Some f ->
        ( Colitur_kernel.Slug.to_string
            (match f.Colitur_kernel.Mass_formulary.said with
            | Some s -> s
            | None -> d.Colitur_kernel.Liturgical_day.observed.Colitur_kernel.Celebration.slug),
          Colitur_kernel.Mass_formulary.source_to_string f.Colitur_kernel.Mass_formulary.via )
    | None -> ("-", "-")
  in
  let preface =
    match d.Colitur_kernel.Liturgical_day.preface with
    | Some p -> Colitur_kernel.Preface.to_string p
    | None -> "-"
  in
  let name = rubrics_name ~lang d said in
  let name_suffix = if name = said || said = "-" then "" else "\t" ^ name in
  Printf.printf "%s\t%s\t%s\t%s\t%s\t%s%s\n" (D.to_iso8601 d.Colitur_kernel.Liturgical_day.date) said via
    (string_of_bool d.Colitur_kernel.Liturgical_day.creed)
    (string_of_bool d.Colitur_kernel.Liturgical_day.gloria)
    preface name_suffix

(* One civil year, Jan 1 - Dec 31, matching [temporal_report]'s own scan --
   NOT one liturgical year: [Colitur_kernel.Calendar.year] resolves a single
   Advent-anchored liturgical year, which straddles two civil years, so a
   civil year's worth of output needs the tail of the liturgical year that
   opened the PREVIOUS civil year (covers roughly 1 Jan - 28 Nov) plus the
   liturgical year that opens within this one (roughly 29 Nov - 31 Dec).
   Both are computed once each -- not once per day via [Calendar.day], which
   would recompute the whole (~365-day) placement pass up to 365 times over
   for the days sharing one liturgical year (calendar.mli's own "pays it
   once" cost model assumes exactly this usage: call [year], not [day] in a
   loop). *)
(* The three data files this subcommand needs, loaded once and reported
   through ONE failure path. Flattened out of the nested [match] this used
   to be when a third loader (the Commons, Task 6) joined the first two:
   each additional caller-supplied table would otherwise add a level of
   indentation and a third verbatim copy of the same two-line error-and-exit
   block. Every loader already returns [(_, string) result] (never raises,
   never reads at module-initialisation time -- see [load_ef_lectionary]),
   so chaining them costs nothing and keeps that promise intact. *)
let load_ef_data ?(user_overlays = []) () =
  match
    Result.map
      (fun (layer, diagnostics) ->
        List.iter
          (fun d -> Printf.eprintf "colitur: %s\n" (Colitur_kernel.Overlay.diagnostic_to_string d))
          diagnostics;
        layer)
      (load_ef_layer ~user_overlays ())
  with
  | Error msg -> Error msg
  | Ok layer -> (
      match load_ef_lectionary () with
      | Error msg -> Error msg
      | Ok lectionary -> (
          match load_ef_commons () with
          | Error msg -> Error msg
          | Ok commons -> Ok (layer, lectionary, commons)))

(* The resolved-year walk, shared by [day_report], [readings_report] and
   [emit_report] (Task 8): they differ only in what happens to each day, and
   the two-liturgical-year indexing below (with its own reasoning about
   civil-vs-liturgical spans) is exactly the part that must not be duplicated
   and drift. [resolved_year_days] owns that walk and returns the resolved
   days, in date order, for one civil year; every caller layers its own
   handling (a line-printer, an accumulator for a whole-year [Template.value])
   on top rather than repeating the indexing. *)
let resolved_year_days ~overlays y =
  match load_ef_data ~user_overlays:overlays () with
  | Error msg ->
      Printf.eprintf "colitur: %s\n" msg;
      exit 2
  | Ok (layer, lectionary, commons) ->
      let context = Rite_ef.context ~lectionary ~commons in
      let module Cal = Colitur_kernel.Calendar in
      let by_rata : (int, (Rite_ef.Vocab_ef.season, Rite_ef.Vocab_ef.rank) Colitur_kernel.Liturgical_day.t) Hashtbl.t =
        Hashtbl.create 400
      in
      let index days =
        Array.iter
          (fun (d : (Rite_ef.Vocab_ef.season, Rite_ef.Vocab_ef.rank) Colitur_kernel.Liturgical_day.t) ->
            Hashtbl.replace by_rata (D.to_rata d.Colitur_kernel.Liturgical_day.date) d)
          days
      in
      index (Cal.year context layer (y - 1));
      index (Cal.year context layer y);
      let jan1 = match D.make ~year:y ~month:1 ~day:1 with Ok t -> t | Error e -> failwith e in
      let dec31 = match D.make ~year:y ~month:12 ~day:31 with Ok t -> t | Error e -> failwith e in
      let d = ref jan1 in
      let acc = ref [] in
      while D.compare !d dec31 <= 0 do
        (match Hashtbl.find_opt by_rata (D.to_rata !d) with
        | Some day -> acc := day :: !acc
        | None ->
            (* Unreachable for any [y] in 1583..9999: the two indexed
               liturgical years jointly cover [year_start (y-1), year_start
               (y+1)), which contains all of civil year [y]
               (calendar.mli). Not a [failwith] -- an out-of-domain [d]
               inside this loop is impossible by construction (jan1/dec31
               are themselves validated in range, and [add_days] only ever
               advances within the same civil year here) -- but a silent
               skip would violate the same "never silently dropped"
               standard the kernel holds itself to, so a gap surfaces
               loudly on stderr rather than as a quietly short year. *)
            Printf.eprintf "colitur: internal error: no resolved day for %s\n" (D.to_iso8601 !d));
        d := D.add_days !d 1
      done;
      List.rev !acc

let resolved_year_report ~line ~overlays y =
  List.iter line (resolved_year_days ~overlays y)


(* ---------------------------------------------------------------------- *)
(* --pretty: the same days, laid out for a person rather than for awk.
 *
 * These mirror the plain formatters above one for one and share their data;
 * they do NOT recompute anything. The plain output stays byte-identical --
 * see bin/pretty.ml's own note on why this format is free to change while
 * every other one is a contract. *)

let pretty_day_generic ~date ~dow ~colour ~rank ~season ~week ~name ~comms =
  let season_col =
    match week with
    | Some w -> Printf.sprintf "%s %s" season w
    | None -> season
  in
  (* The prefix is built, then MEASURED, rather than its width being assumed
     from the column constants. Those constants are a minimum, not a maximum
     -- a season name longer than its column (the Latin "Tempus per annum ante
     Septuagesimam" is 35 against 34) pushes everything after it right, and an
     indent computed from the constants would then sit under the wrong column
     on exactly the rows that have something to indent. *)
  let prefix =
    Printf.sprintf "%s  %s  " (Pretty.pad Pretty.w_date date)
      (Pretty.pad Pretty.w_dow (String.sub dow 0 (min 3 (String.length dow))))
  in
  let mid =
    Printf.sprintf "  %s  %s"
      (Pretty.pad Pretty.w_rank rank)
      (Pretty.pad Pretty.w_season season_col)
  in
  Printf.printf "%s%s%s%s\n" prefix (Pretty.swatch colour) mid name;
  (* Commemorations take their own indented line rather than a suffix: the EF
     admits up to three, and appending them runs the row past any sensible
     terminal width on precisely the days worth reading. The swatch counts as
     one display column however it was rendered. *)
  let indent = Pretty.utf8_len prefix + 1 + Pretty.utf8_len mid in
  List.iter
    (fun c -> Printf.printf "%s%s\n" (String.make indent ' ') (Pretty.dim ("+ " ^ c)))
    comms

let day_line_pretty ~lang (d : (Rite_ef.Vocab_ef.season, Rite_ef.Vocab_ef.rank) Colitur_kernel.Liturgical_day.t) =
  let t = d.Colitur_kernel.Liturgical_day.temporal in
  let cel = d.Colitur_kernel.Liturgical_day.observed in
  let slug_s = Colitur_kernel.Slug.to_string cel.Colitur_kernel.Celebration.slug in
  let name = Colitur_naming.Lang.celebration lang slug_s in
  pretty_day_generic
    ~date:(D.to_iso8601 d.Colitur_kernel.Liturgical_day.date)
    ~dow:(D.weekday_to_string t.Colitur_kernel.Temporal.weekday)
    ~colour:(Colitur_kernel.Colour.to_string cel.Colitur_kernel.Celebration.colour)
    ~rank:(Colitur_naming.Lang.rank lang (Rite_ef.Vocab_ef.rank_to_string cel.Colitur_kernel.Celebration.rank))
    ~season:(Colitur_naming.Lang.season lang (Rite_ef.Vocab_ef.season_to_string t.Colitur_kernel.Temporal.season))
    ~week:(match t.Colitur_kernel.Temporal.week with Some n -> Some (string_of_int n) | None -> None)
    ~name:(if name = slug_s then slug_s else name)
    ~comms:(List.map
              (fun (c, _) ->
                let cs = Colitur_kernel.Slug.to_string c.Colitur_kernel.Celebration.slug in
                let cn = Colitur_naming.Lang.celebration lang cs in
                if cn = cs then cs else cn)
              d.Colitur_kernel.Liturgical_day.commemorations)

let day_report ~lang ~pretty ~overlays y =
  resolved_year_report
    ~line:(if pretty then day_line_pretty ~lang else day_line ~lang)
    ~overlays y
let readings_pretty_row ~date ~dow ~name ~first ~second ~gospel =
  Printf.printf "%s  %s  %s\n"
    (Pretty.pad Pretty.w_date date)
    (Pretty.pad Pretty.w_dow (String.sub dow 0 (min 3 (String.length dow))))
    name;
  let show label v =
    if v <> "" && v <> "-" then
      Printf.printf "%s%s %s\n"
        (String.make (Pretty.w_date + Pretty.w_dow + 5) ' ')
        (Pretty.dim (Pretty.pad 8 label)) v
  in
  (* Labelled and stacked rather than pipe-separated. A citation is what a
     person came here to read, and "Isai 63:16b-17, 19b; 64:2-7" is hard to
     find in a row of three when the separators are bars. The OF's second
     reading simply does not print on the days that have none, which is most
     of them. *)
  show "First" first;
  show "Second" second;
  show "Gospel" gospel

let readings_line_pretty ~lang ~sigla (d : (Rite_ef.Vocab_ef.season, Rite_ef.Vocab_ef.rank) Colitur_kernel.Liturgical_day.t) =
  let cel = d.Colitur_kernel.Liturgical_day.observed in
  let part_ref p =
    match
      List.find_opt (fun (c : Colitur_kernel.Citation.t) ->
        c.Colitur_kernel.Citation.part = p) d.Colitur_kernel.Liturgical_day.citations
    with
    | Some c -> Colitur_citation.Sigla.format sigla c.Colitur_kernel.Citation.reference
    | None -> ""
  in
  let slug_s = Colitur_kernel.Slug.to_string cel.Colitur_kernel.Celebration.slug in
  let n = Colitur_naming.Lang.celebration lang slug_s in
  readings_pretty_row
    ~date:(D.to_iso8601 d.Colitur_kernel.Liturgical_day.date)
    ~dow:(D.weekday_to_string d.Colitur_kernel.Liturgical_day.temporal.Colitur_kernel.Temporal.weekday)
    ~name:(if n = slug_s then slug_s else n)
    ~first:(part_ref Colitur_kernel.Citation.First)
    ~second:(part_ref Colitur_kernel.Citation.Second)
    ~gospel:(part_ref Colitur_kernel.Citation.Gospel)

let readings_report ~lang ~sigla ~pretty ~overlays y =
  resolved_year_report
    ~line:(if pretty then readings_line_pretty ~lang ~sigla else readings_line ~lang ~sigla)
    ~overlays y

(* Fix wave I1 (final-review.md, 2026-08-25-colitur-of-phases-3-5): unlike
   EF's [Celebration.names] (almost always empty -- lang/la.ini is EF's own
   independently-cited Latin name table, keyed on slug, and that is
   deliberate: see day_line's own header), the OF's data/of/calendar-2002
   .sexp carries a verified [names] entry (both [la] and [en]) for every one
   of its 208 sanctoral slugs, transcribed and cited against the 2002
   Missal. [day_line]/[readings_line]'s original OF twins nonetheless
   resolved names through the SAME [lang/*.ini] table EF uses -- 18 of 222
   OF slugs collide with an EF slug there and printed the WRONG (1962)
   title (e.g. "S. Marthae Virg." instead of amendment 011's own "Ss.
   Marthae, Mariae et Lazari"); the other 204 had no entry and degraded to
   a bare slug, so calendar-2002.sexp's own transcription was reachable
   from nothing.

   [observed_name_of] fixes this at the source: prefer the OBSERVED
   CELEBRATION'S OWN [names] (keyed by the requested language code), and
   fall back to the lang/*.ini table only on a miss -- which still covers
   every slug the calendar data has no name for (the temporal-origin ones,
   of-pentecost/of-advent-sunday-4/etc, correctly absent from both tables).
   Under [--raw], [Colitur_naming.Lang.raw]'s own [code] is ["raw"], not a
   valid 2-letter ISO-639-1 code, so {!Colitur_kernel.Lang.of_string}
   rejects it, [from_data] is always [None], and this always falls through
   to the lang-table lookup -- [Lang.raw]'s own identity table -- so [--raw]
   output is byte-identical to before this fix. *)
let observed_name_of ~lang (cel : Rite_of.Vocab_of.rank Colitur_kernel.Celebration.t) slug_s =
  let from_data =
    match Colitur_kernel.Lang.of_string (Colitur_naming.Lang.code lang) with
    | Error _ -> None
    | Ok l -> Colitur_kernel.Names.find cel.Colitur_kernel.Celebration.names l
  in
  match from_data with Some n -> n | None -> Colitur_naming.Lang.celebration lang slug_s

(* Task 5 (2026-08-25-colitur-of-phases-3-5): [day_line]/[readings_line]'s
   OF twins -- same two row shapes, same [~lang]/[~sigla] append-only rules
   (see those functions' own citations just above for the full reasoning,
   not repeated here), [Rite_of.Vocab_of] in place of [Rite_ef.Vocab_ef].
   Names resolve through [observed_name_of] above, not directly through
   [Colitur_naming.Lang.celebration] as EF's twins do -- see that
   function's own header for why the two rites differ here. *)
let day_line_of ~lang (d : (Rite_of.Vocab_of.season, Rite_of.Vocab_of.rank) Colitur_kernel.Liturgical_day.t) =
  let t = d.Colitur_kernel.Liturgical_day.temporal in
  let cel = d.Colitur_kernel.Liturgical_day.observed in
  let week = match t.Colitur_kernel.Temporal.week with Some n -> string_of_int n | None -> "-" in
  let commemoration_suffix (c, _) =
    " +" ^ Colitur_kernel.Slug.to_string c.Colitur_kernel.Celebration.slug
  in
  let commemorations =
    String.concat "" (List.map commemoration_suffix d.Colitur_kernel.Liturgical_day.commemorations)
  in
  let slug_s = Colitur_kernel.Slug.to_string cel.Colitur_kernel.Celebration.slug in
  let name = observed_name_of ~lang cel slug_s in
  let name_suffix = if name = slug_s then "" else " " ^ name in
  Printf.printf "%s %s %s %s %s %s %s%s%s\n" (D.to_iso8601 d.Colitur_kernel.Liturgical_day.date)
    (D.weekday_to_string t.Colitur_kernel.Temporal.weekday)
    (Rite_of.Vocab_of.season_to_string t.Colitur_kernel.Temporal.season)
    week slug_s
    (Rite_of.Vocab_of.rank_to_string cel.Colitur_kernel.Celebration.rank)
    (Colitur_kernel.Colour.to_string cel.Colitur_kernel.Celebration.colour)
    commemorations name_suffix

let readings_line_of ~lang ~sigla
    (d : (Rite_of.Vocab_of.season, Rite_of.Vocab_of.rank) Colitur_kernel.Liturgical_day.t) =
  let cel = d.Colitur_kernel.Liturgical_day.observed in
  let part_ref p =
    match
      List.find_opt
        (fun (c : Colitur_kernel.Citation.t) -> c.Colitur_kernel.Citation.part = p)
        d.Colitur_kernel.Liturgical_day.citations
    with
    | Some c -> Colitur_citation.Sigla.format sigla c.Colitur_kernel.Citation.reference
    | None -> "-"
  in
  (* Second reading: present-or-absent, not present-or-"-" -- see
     [readings_line]'s own comment for the full reasoning (OLM n. 67, a
     Sunday/solemnity's own three-reading shape; [Rite.t.citation_shapes]
     is what actually distinguishes which OF days carry one). *)
  let second_suffix =
    match
      List.find_opt
        (fun (c : Colitur_kernel.Citation.t) -> c.Colitur_kernel.Citation.part = Colitur_kernel.Citation.Second)
        d.Colitur_kernel.Liturgical_day.citations
    with
    | Some c -> " | " ^ Colitur_citation.Sigla.format sigla c.Colitur_kernel.Citation.reference
    | None -> ""
  in
  let slug_s = Colitur_kernel.Slug.to_string cel.Colitur_kernel.Celebration.slug in
  let name = observed_name_of ~lang cel slug_s in
  let name_suffix = if name = slug_s then "" else " | " ^ name in
  Printf.printf "%s %s | %s%s | %s%s\n"
    (D.to_iso8601 d.Colitur_kernel.Liturgical_day.date)
    slug_s
    (part_ref Colitur_kernel.Citation.First)
    second_suffix
    (part_ref Colitur_kernel.Citation.Gospel)
    name_suffix

let resolved_of_year_report ~line ~overlays y = List.iter line (resolved_of_year_days ~overlays y)

let day_line_of_pretty ~lang (d : (Rite_of.Vocab_of.season, Rite_of.Vocab_of.rank) Colitur_kernel.Liturgical_day.t) =
  let t = d.Colitur_kernel.Liturgical_day.temporal in
  let cel = d.Colitur_kernel.Liturgical_day.observed in
  let slug_s = Colitur_kernel.Slug.to_string cel.Colitur_kernel.Celebration.slug in
  (* Same preference [day_line_of] itself uses: the shipped OF data's own
     verified per-slug name first, the generic lang table only as a fallback.
     Reusing [observed_name_of] rather than restating it keeps the two row
     shapes from drifting apart. *)
  let name = observed_name_of ~lang cel slug_s in
  pretty_day_generic
    ~date:(D.to_iso8601 d.Colitur_kernel.Liturgical_day.date)
    ~dow:(D.weekday_to_string t.Colitur_kernel.Temporal.weekday)
    ~colour:(Colitur_kernel.Colour.to_string cel.Colitur_kernel.Celebration.colour)
    ~rank:(Colitur_naming.Lang.rank lang (Rite_of.Vocab_of.rank_to_string cel.Colitur_kernel.Celebration.rank))
    ~season:(Colitur_naming.Lang.season lang (Rite_of.Vocab_of.season_to_string t.Colitur_kernel.Temporal.season))
    ~week:(match t.Colitur_kernel.Temporal.week with Some n -> Some (string_of_int n) | None -> None)
    ~name ~comms:[]

let day_report_of ~lang ~pretty ~overlays y =
  resolved_of_year_report
    ~line:(if pretty then day_line_of_pretty ~lang else day_line_of ~lang)
    ~overlays y
let readings_line_of_pretty ~lang ~sigla (d : (Rite_of.Vocab_of.season, Rite_of.Vocab_of.rank) Colitur_kernel.Liturgical_day.t) =
  let cel = d.Colitur_kernel.Liturgical_day.observed in
  let part_ref p =
    match
      List.find_opt (fun (c : Colitur_kernel.Citation.t) ->
        c.Colitur_kernel.Citation.part = p) d.Colitur_kernel.Liturgical_day.citations
    with
    | Some c -> Colitur_citation.Sigla.format sigla c.Colitur_kernel.Citation.reference
    | None -> ""
  in
  let slug_s = Colitur_kernel.Slug.to_string cel.Colitur_kernel.Celebration.slug in
  readings_pretty_row
    ~date:(D.to_iso8601 d.Colitur_kernel.Liturgical_day.date)
    ~dow:(D.weekday_to_string d.Colitur_kernel.Liturgical_day.temporal.Colitur_kernel.Temporal.weekday)
    ~name:(observed_name_of ~lang cel slug_s)
    ~first:(part_ref Colitur_kernel.Citation.First)
    ~second:(part_ref Colitur_kernel.Citation.Second)
    ~gospel:(part_ref Colitur_kernel.Citation.Gospel)

let readings_report_of ~lang ~sigla ~pretty ~overlays y =
  resolved_of_year_report
    ~line:(if pretty then readings_line_of_pretty ~lang ~sigla else readings_line_of ~lang ~sigla)
    ~overlays y

(* Fix 1 (cli-flags-report, 2026-08-27): `rubrics` widened to `--rite of`.
   [rubrics_line] above needs no OF twin (it type-checks polymorphic over
   [('s, 'r)] already -- see its own header), so dispatching here is only
   ever about which resolver walks the year, never about which printer
   prints it. *)

(* --pretty for `readings` and `rubrics`. Both keep the same one-row-per-day
   shape as `day --pretty`, so the four commands scan alike; only the columns
   after the date differ, because what they are FOR differs. *)

let rubrics_pretty_row ~date ~said ~via ~creed ~gloria ~preface =
  let tick b = if b then "yes" else Pretty.dim "no" in
  Printf.printf "%s  %s  %s  %s  %s  %s\n"
    (Pretty.pad Pretty.w_date date)
    (Pretty.pad 34 said)
    (Pretty.pad 10 via)
    (Pretty.pad 8 ("Creed " ^ tick creed))
    (Pretty.pad 9 ("Gloria " ^ tick gloria))
    preface


let rubrics_line_pretty (d : (_, _) Colitur_kernel.Liturgical_day.t) =
  let said, via =
    match d.Colitur_kernel.Liturgical_day.formulary with
    | Some f ->
        ((match f.Colitur_kernel.Mass_formulary.said with
          | Some sl -> Colitur_kernel.Slug.to_string sl
          | None -> "-"),
         Colitur_kernel.Mass_formulary.source_to_string f.Colitur_kernel.Mass_formulary.via)
    | None -> ("-", "-")
  in
  rubrics_pretty_row
    ~date:(D.to_iso8601 d.Colitur_kernel.Liturgical_day.date)
    ~said ~via
    ~creed:d.Colitur_kernel.Liturgical_day.creed
    ~gloria:d.Colitur_kernel.Liturgical_day.gloria
    ~preface:(match d.Colitur_kernel.Liturgical_day.preface with
              | Some pf -> Colitur_kernel.Preface.to_string pf
              | None -> "-")

let rubrics_report ~rite ~lang ~pretty ~overlays y =
  match rite with
  | `Ef -> resolved_year_report ~line:(if pretty then rubrics_line_pretty else rubrics_line ~lang) ~overlays y
  | `Of -> resolved_of_year_report ~line:(if pretty then rubrics_line_pretty else rubrics_line ~lang) ~overlays y

(* Fix 1 (cli-flags-report, 2026-08-27): shared by [table_report] and
   [publish_report], which each need only the rendered [Template.value] --
   {!Colitur_render.View.of_days} is fully polymorphic over [('s, 'r)]
   (view.mli), so the SAME function builds it for either rite, and nothing
   downstream (a template, an emitter) has to know which one produced it.
   [emit_report] does NOT reuse this: its own "sexp" format needs the raw,
   rite-specific [days] list too (a different [sexp_of_season]/
   [sexp_of_rank] pair per rite), so it dispatches inline instead, right
   next to the [days] binding this helper deliberately does not expose. *)
let view_of_year ~rite ~lang ~sigla ~overlays y =
  match rite with
  | `Ef ->
      let days = resolved_year_days ~overlays y in
      Colitur_render.View.of_days ~lang ~sigla ~vocab:Rite_ef.Vocab_ef.vocab ~rite:"ef" ~year:y days
  | `Of ->
      let days = resolved_of_year_days ~overlays y in
      Colitur_render.View.of_days ~lang ~sigla ~vocab:Rite_of.Vocab_of.vocab ~rite:"of" ~year:y days

(* Task 8: `colitur emit` -- the five template-family emitters built in
   Tasks 5-7, wired to a year RANGE rather than a single year, because a
   published feed (ics) or a data export (csv/json/xml) is usually wanted
   for more than one civil year at a time. Reuses [resolved_year_days]
   rather than re-walking the two-liturgical-year index: see that
   function's own comment.

   CSV is the one format that spans years in a single stream deliberately
   printed as ONE header followed by every year's rows: emitting a fresh
   header per year would make `wc -l` and `awk 'NR>1'` both wrong on a
   multi-year run, and nothing about RFC 4180 requires a header per file
   rather than per stream. json/xml/sexp/ics are printed once per year
   instead -- concatenating whole JSON objects or VCALENDARs into one
   stream is what each of those formats itself expects a multi-document
   feed to look like (SEXP: printed one form per line, matching the
   sexp-per-day shape [Liturgical_day.t] already uses elsewhere in this
   file; XML: one document per year, the schema's own root is a single
   year; ICS: one VCALENDAR per year, valid to concatenate for a
   subscriber that reads multiple files). *)
(* [--dtstamp] is the only user string that reaches [emit]/[publish] output
   unescaped and unvalidated (it becomes an ICS DTSTAMP: property value
   directly, Colitur_render.Emit_ics.year's own [dtstamp] parameter) --
   every OTHER interpolated value in this project's output is either
   escaped (Escape.apply) or engine-computed, never raw user input placed
   straight into a line-oriented format. RFC 5545 section 3.3.5 defines
   DATE-TIME's UTC form as exactly 8 digits, "T", 6 digits, "Z"
   (e.g. "20270101T000000Z"); rejecting anything else is what stops
   "--dtstamp hello" from silently emitting a malformed "DTSTAMP:hello" AND
   what stops a value carrying its own CRLF (e.g. "X\r\nBEGIN:VEVENT\r\n...")
   from being injected verbatim into every VEVENT -- a value shaped exactly
   like the real form cannot contain either character. *)
let dtstamp_well_formed s =
  let is_digit c = c >= '0' && c <= '9' in
  String.length s = 16
  && String.for_all is_digit (String.sub s 0 8)
  && s.[8] = 'T'
  && String.for_all is_digit (String.sub s 9 6)
  && s.[15] = 'Z'

let check_dtstamp = function
  | None -> ()
  | Some s when dtstamp_well_formed s -> ()
  | Some s ->
      Printf.eprintf
        "colitur: --dtstamp %S is not RFC 5545 UTC form (want 8 digits, 'T', 6 digits, 'Z', e.g. \
         20270101T000000Z)\n"
        s;
      exit 2

(* Fix 1 (cli-flags-report, 2026-08-27): `emit` widened to `--rite of`.
   [view_of_year] above cannot be reused here: "sexp" prints the raw
   [days] list through a rite-specific [sexp_of_season]/[sexp_of_rank]
   pair, so each rite needs its own [days] binding in scope, not only its
   own [Template.value] -- dispatched inline instead, once per year (the
   resolved data does not carry over between years, unlike [rite] itself,
   so this sits inside the loop, not outside it). *)
let emit_report ~rite ~lang ~sigla ~format ~overlays ~dtstamp ~from_y ~to_y =
  check_dtstamp dtstamp;
  if from_y > to_y then begin
    Printf.eprintf "colitur: --from %d is after --to %d\n" from_y to_y;
    exit 2
  end;
  for y = from_y to to_y do
    let v, print_sexp =
      match rite with
      | `Ef ->
          let days = resolved_year_days ~overlays y in
          ( Colitur_render.View.of_days ~lang ~sigla ~vocab:Rite_ef.Vocab_ef.vocab ~rite:"ef" ~year:y
              days,
            fun () ->
              List.iter
                (fun d ->
                  print_string
                    (Sexplib.Sexp.to_string_hum
                       (Colitur_kernel.Liturgical_day.sexp_of_t Rite_ef.Vocab_ef.sexp_of_season
                          Rite_ef.Vocab_ef.sexp_of_rank d));
                  print_newline ())
                days )
      | `Of ->
          let days = resolved_of_year_days ~overlays y in
          ( Colitur_render.View.of_days ~lang ~sigla ~vocab:Rite_of.Vocab_of.vocab ~rite:"of" ~year:y
              days,
            fun () ->
              List.iter
                (fun d ->
                  print_string
                    (Sexplib.Sexp.to_string_hum
                       (Colitur_kernel.Liturgical_day.sexp_of_t Rite_of.Vocab_of.sexp_of_season
                          Rite_of.Vocab_of.sexp_of_rank d));
                  print_newline ())
                days )
    in
    match format with
    | "csv" ->
        (* One header for the whole run, not one per year -- safe across a
           multi-year [--rite of] run too: {!Colitur_render.Emit_csv.year}
           reads its own column set from [v]'s "rite" field (see that
           module's own comment), and [rite] cannot change mid-run, so
           every year's header is identical within one invocation. *)
        let body = Colitur_render.Emit_csv.year v in
        if y = from_y then print_string body
        else
          print_string
            (match String.index_opt body '\n' with
             | Some i -> String.sub body (i + 1) (String.length body - i - 1)
             | None -> body)
    | "json" -> print_string (Colitur_render.Emit_json.year v)
    | "xml" -> print_string (Colitur_render.Emit_xml.year v)
    | "ics" -> print_string (Colitur_render.Emit_ics.year ?dtstamp v)
    | "sexp" -> print_sexp ()
    | other ->
        Printf.eprintf "colitur: unknown format %S (want csv, json, sexp, xml or ics)\n" other;
        exit 2
  done

(* Task 9: `colitur table` and `colitur render` -- compute a year and render it
   through a user-supplied template, in ONE process.

   The design's own sketch was `compute | render` as a Unix pipe, with `render`
   reading a serialised view back from stdin. That is deliberately NOT built:
   honouring the pipe would need a JSON *parser*, purely to re-read the view
   this same process just serialised -- a second hand-rolled component, and a
   second place for the published contract to drift, for no benefit over
   calling [View.of_days] directly. So `table --year Y --template F` computes
   and renders in one process (the command that actually gets used), and
   `render --template F --year Y` is the identical operation under the name
   the design used, kept so that documented vocabulary still works. There is
   no stdin-fed `render`; `colitur emit --format json | jq` still composes for
   real pipe use, because JSON there is the OUTPUT, never something colitur
   itself has to parse back in.

   Fix 1 (cli-flags-report, 2026-08-27): both now take `--rite`, dispatched
   through [view_of_year]. Pointing an EF template at an OF year (or vice
   versa) is not refused and does not crash: {!Colitur_render.Template
   .render}'s own contract is that a missing key renders as the empty
   string (template.mli), so a template written before `--rite of` existed
   -- one that never references [{{second}}], say -- simply never shows
   the OF Second reading it does not ask for; it does not error, and no
   OTHER field goes missing, because [View.of_days] emits the identical KEY
   set for either rite (only the resolved VALUES differ, e.g. `ordinary`
   vs whatever EF's own season names are). A template is user input and
   this project's own rule is that user input must never crash the
   program -- the missing-key silence is exactly what keeps that promise
   here too, not a special case added for this task. *)

(* The open is guarded separately from the read: a missing file fails at
   [open_in_bin] with a plain, path-only message (matching the wording this
   project already uses for every other "no such file" case), while a file
   that opens but cannot be READ -- a directory, a device node, anything
   whose length or content changes between [open] and [read] -- fails inside
   the [Fun.protect]'d body instead, carrying the raised exception's own text
   (mirrors {!Colitur_kernel.Layer.load}/{!Colitur_kernel.Overlay.load}'s own
   catch-all shape, lib/kernel/layer.ml and lib/kernel/overlay.ml). Either
   way the channel is closed on EVERY path -- success, exception, or an
   early return -- because [close_in_noerr] runs in [~finally], which
   [Fun.protect] guarantees runs even when the protected function raises; a
   bare [close_in] after [really_input_string] only ever ran on the success
   path, leaking the descriptor on every failure. The whole read is inside
   the [try], not only [open_in_bin], because [in_channel_length] and
   [really_input_string] can themselves raise [Sys_error] (a directory opens
   fine but is not readable as bytes) -- a template is user input, and this
   project's own rule is that user input must never crash the program. *)
let read_file path =
  match open_in_bin path with
  | exception Sys_error _ -> Error ("cannot read template " ^ path)
  | ic -> (
      try
        Fun.protect
          ~finally:(fun () -> close_in_noerr ic)
          (fun () ->
            let n = in_channel_length ic in
            let s = really_input_string ic n in
            Ok s)
      with exn -> Error (Printf.sprintf "cannot read template %s: %s" path (Printexc.to_string exn)))

(* The config file supplies DEFAULTS for --lang, --overlay, --template and
   --format when the corresponding flag is absent -- Colitur_naming.Config
   owns precedence (flag > config > default). Location follows the XDG base
   directory convention: $XDG_CONFIG_HOME/colitur/config.ini, or
   ~/.config/colitur/config.ini when that variable is unset or blank. An
   unresolvable HOME (neither variable set) means no config path at all --
   [load_config] below treats that exactly like a missing file, not an
   error, since colitur without any config must keep working. *)
let config_path () =
  match Sys.getenv_opt "XDG_CONFIG_HOME" with
  | Some d when String.trim d <> "" -> Filename.concat d "colitur/config.ini"
  | _ -> (
      match Sys.getenv_opt "HOME" with
      | Some h -> Filename.concat h ".config/colitur/config.ini"
      | None -> "")

(* A config file is OPTIONAL: none at [config_path ()] behaves exactly as
   colitur always has (Colitur_naming.Config.empty). A file that EXISTS but
   fails to read or parse is fatal -- a config the user wrote and colitur
   cannot honour is not something to silently carry on past. An unknown key
   or section is reported but never fatal (Config.mli's own contract): a
   config written for a newer colitur must still work on an older one, but a
   silently-ignored typo is how a setting the user believes is active quietly
   does nothing. Two separate warnings, not one, so a misspelled SECTION
   (e.g. [deafults]) reads differently from a misspelled KEY inside a
   recognised one -- Config.mli documents exactly this distinction. *)
let load_config () =
  let p = config_path () in
  if p = "" || not (Sys.file_exists p) then Colitur_naming.Config.empty
  else
    match read_file p with
    | Error _ ->
        Printf.eprintf "colitur: cannot read config file %s\n" p;
        exit 2
    | Ok text -> (
        match Colitur_naming.Config.of_string text with
        | Error msg ->
            Printf.eprintf "colitur: %s: %s\n" p msg;
            exit 2
        | Ok c ->
            List.iter
              (fun k -> Printf.eprintf "colitur: %s: unknown setting %S (ignored)\n" p k)
              (Colitur_naming.Config.unknown_keys c);
            List.iter
              (fun s -> Printf.eprintf "colitur: %s: unknown section [%s] (ignored)\n" p s)
              (Colitur_naming.Config.unknown_sections c);
            c)

(* An unknown language is an ERROR naming what is available, never a silent
   fallback to Latin: a booklet quietly printed in the wrong language is
   worse than one that refuses to print. [raw] takes priority
   unconditionally and short-circuits everything else -- [--raw] IS
   [Lang.raw], the identity table, handed to the caller directly, rather
   than a second "is this raw" case threaded through every call site
   downstream (View.of_days, day_line, readings_line all just take a
   [Lang.t] and do not know or care whether it came from [--raw] or a real
   file). *)
let load_lang ~raw ~flag ~config =
  if raw then Colitur_naming.Lang.raw
  else
    let code, _src = Colitur_naming.Config.resolve ~flag ~config ~default:"la" in
    let path =
      if String.contains code '/' || Filename.check_suffix code ".ini" then code
      else Filename.concat (lang_dir ()) (code ^ ".ini")
    in
    match read_file path with
    | Error _ ->
        Printf.eprintf "colitur: no language %S (looked in %s); try: colitur lang --list\n" code
          (lang_dir ());
        exit 2
    | Ok text -> (
        match Colitur_naming.Lang.of_string text with
        | Error msg ->
            Printf.eprintf "colitur: %s: %s\n" path msg;
            exit 2
        | Ok t -> (
            (* Chain to the declared fallback, so a partial translation shows
               its fallback language rather than bare slugs. A fallback that
               itself fails to load or parse does not take [t] down with it
               -- [t] is already a good table; losing only the fallback field
               is better than losing the whole language over a defect in a
               file [t] merely NAMES. *)
            match Colitur_naming.Lang.fallback_code t with
            | None -> t
            | Some fb -> (
                match read_file (Filename.concat (lang_dir ()) (fb ^ ".ini")) with
                | Error _ -> t
                | Ok ftext -> (
                    match Colitur_naming.Lang.of_string ftext with
                    | Error _ -> t
                    | Ok base -> Colitur_naming.Lang.with_fallback t base))))

(* lang/traditions.ini answers a different question from la.ini/en.ini's own
   [\[bible\]] section: which book a reference DENOTES, not what it is
   CALLED. Naming varies by language (a [\[bible\]] section per language
   file); denoting does not -- "modern numbering" is the same decision in
   Latin, Polish and English -- so it gets its own file, read once here
   rather than duplicated per language.

   Reuses {!lang_dir} rather than adding a second probe: a tradition file
   must resolve the same way a language file does, or an installed binary
   could find one and not the other. Note carefully what that reuse implies
   -- [lang_dir]'s own installed-vs-source-tree choice is gated on [la.ini]
   existing, so it can legitimately return a directory that HAS [la.ini] but
   NOT [traditions.ini] (an older install upgraded in place, from before
   this file shipped). That case, like an unknown [name] naming no section
   in the file, degrades to {!Colitur_citation.Book.vulgate} with a WARNING
   on stderr -- never fatal. This deliberately does NOT mirror [load_lang]'s
   own PRIMARY-file behaviour (a missing/unparsing la.ini is fatal, [exit 2])
   -- it mirrors [load_lang]'s own FALLBACK-chain behaviour just above,
   which already degrades silently rather than taking a good language table
   down over a defect in a file it merely NAMES. Asking for a renumbering is
   optional the way asking for a language is not: a run should not be lost
   over a typo in [--sigla-tradition] (wired in Task 8) the way it is lost
   over a typo in [--lang].

   [name = "vulgate"] takes no shortcut around the file: [\[vulgate\]] is
   shipped as a deliberately empty section (see traditions.ini's own
   comment), and an empty field list is exactly {!Colitur_citation.Book.vulgate}
   ([[]]) via the same {!Colitur_citation.Book.tradition_of_fields} path
   every other tradition uses -- one code path, not a special case for the
   default.

   Called from [config_show] below (Task 8's own [--sigla-tradition]
   plumbing), which discards the returned [tradition] and keeps only the
   validation side effect -- `config --show` reports the RESOLVED STRING,
   exactly like every other row, not a loaded object. Also called from
   [load_sigla] below (Task 9), which DOES thread the loaded [tradition]
   through to actually renumber a reference at both places one reaches
   output, [View.citation_ref] and [part_ref]. *)
let load_tradition name =
  let path = Filename.concat (lang_dir ()) "traditions.ini" in
  let vulgate () = Colitur_citation.Book.vulgate in
  match read_file path with
  | Error _ ->
      Printf.eprintf "colitur: no %s; tradition %S falls back to the Vulgate\n" path name;
      vulgate ()
  | Ok text -> (
      match Colitur_kernel.Overlay_ini.parse_sections text with
      | Error e ->
          Printf.eprintf "colitur: %s: %s; tradition %S falls back to the Vulgate\n" path e name;
          vulgate ()
      | Ok sections -> (
          match List.find_opt (fun (s : Colitur_kernel.Overlay_ini.section) -> s.name = name) sections with
          | None ->
              Printf.eprintf "colitur: %s: no tradition %S; falling back to the Vulgate\n" path name;
              vulgate ()
          | Some sec ->
              List.iter
                (fun k ->
                  Printf.eprintf "colitur: %s: [%s]: unknown book %S (ignored)\n" path name k)
                (Colitur_citation.Book.unknown_fields sec.fields);
              Colitur_citation.Book.tradition_of_fields sec.fields))

(* A book id's display NAME, for {!Colitur_citation.Sigla.make}'s own
   [names] parameter. {!Colitur_naming.Lang.bible} is a TOTAL lookup that
   returns THE KEY on a miss (["luke.abbr"]), because that is [Lang]'s own
   miss contract, kept uniformly across every lookup it offers -- but a
   caller that rendered a miss verbatim would print "luke.abbr 5:12-14"
   straight into a citation. Degrade instead to
   {!Colitur_citation.Book.default_spelling}, the data's own spelling for
   the id -- exactly what colitur printed before this feature existed.
   This path is invisible once [la.ini]/[en.ini] gain a real [\[bible\]]
   section (Task 10); [test_cli.t] pins it against a language file that
   deliberately has none, so the fallback stays under test after that. *)
let names_of lang id form =
  let key =
    Colitur_citation.Book.to_string id
    ^ (match form with `Full -> ".full" | `Abbr -> ".abbr")
  in
  let v = Colitur_naming.Lang.bible lang key in
  if v = key then Colitur_citation.Book.default_spelling id else v

(* Builds the [Sigla.t] every citation-rendering command applies to what it
   emits -- the single place [--raw]/[--sigla-style]/[--sigla-book]/
   [--sigla-tradition] actually take effect (Task 9), a sibling to
   [load_lang] above and reusing it directly for [sigla_style]'s own file
   lookup (config.mli: "a language CODE, looked up the same way [lang] is,
   or a path").

   [raw] short-circuits exactly as [load_lang] does: [Sigla.verbatim] is
   handed back directly, NEVER a styled [Sigla.t] built over [Lang.raw] --
   the latter would still parse every citation and reformat its
   punctuation, which is precisely what [--raw] exists to avoid (byte-exact
   diffing against lectio, and independence from the parser: a parser bug
   must not corrupt the very output used to diagnose it). Every other
   [--sigla-*] flag is silently unconsulted under [--raw] too, the same way
   [--lang] itself is once [--raw] is given.

   [sigla_style] DEFAULTS to [lang_t]'s own resolved code (config.mli's own
   comment on [sigla_style]: a booklet that asked for a different [--lang]
   gets its citations in that language's convention too, not a silent
   reversion to Latin punctuation) -- when the resolved style code IS
   [lang_t]'s own code, [lang_t] is reused directly rather than reading its
   file a second time. Only the style file's OWN [\[sigla\]] section is
   read here ({!Colitur_naming.Lang.sigla_fields} /
   {!Colitur_citation.Render.style_of_fields}); book NAMES always resolve
   through [lang_t] via [names_of] above, never through the style file --
   naming and citation style are deliberately independent axes (a booklet
   may want Polish names but Latin-convention citations, config.mli again).

   [sigla_book] validation mirrors [config_show]'s own check exactly (a
   closed [full]/[abbr] set, [Render.with_book] takes a variant, not a
   string) -- unrecognised is a hard usage error, the same discipline an
   unrecognised [--lang] gets. [sigla_tradition] resolves through
   [load_tradition] above, which is BY DESIGN never fatal: asking for a
   renumbering is optional, unlike asking for a language. *)
let load_sigla ~raw ~lang_t ~sigla_style_flag ~sigla_book_flag ~sigla_tradition_flag ~config =
  if raw then Colitur_citation.Sigla.verbatim
  else
    let lang_code = Colitur_naming.Lang.code lang_t in
    let style_code, _ =
      Colitur_naming.Config.resolve ~flag:sigla_style_flag
        ~config:(Colitur_naming.Config.sigla_style config) ~default:lang_code
    in
    let style_lang =
      if style_code = lang_code then lang_t
      else load_lang ~raw:false ~flag:(Some style_code) ~config:None
    in
    let style =
      Colitur_citation.Render.style_of_fields (Colitur_naming.Lang.sigla_fields style_lang)
    in
    let sigla_book_value, _ =
      Colitur_naming.Config.resolve ~flag:sigla_book_flag
        ~config:(Colitur_naming.Config.sigla_book config)
        (* The STYLE's own [book] key is the default, so a style file can
           set it and a flag/config still overrides. A hardcoded "abbr"
           here made the documented [sigla] book key unreachable. *)
        ~default:(Colitur_citation.Render.book_string style)
    in
    let book_form =
      match sigla_book_value with
      | "full" -> `Full
      | "abbr" -> `Abbr
      | _ ->
          Printf.eprintf "colitur: unknown --sigla-book %S (want \"full\" or \"abbr\")\n" sigla_book_value;
          exit 2
    in
    let style = Colitur_citation.Render.with_book book_form style in
    let sigla_tradition_value, _ =
      Colitur_naming.Config.resolve ~flag:sigla_tradition_flag
        ~config:(Colitur_naming.Config.sigla_tradition config) ~default:"vulgate"
    in
    let tradition = load_tradition sigla_tradition_value in
    Colitur_citation.Sigla.make ~style ~tradition ~names:(names_of lang_t)

let extension path =
  match String.rindex_opt path '.' with
  | Some i -> String.sub path i (String.length path - i)
  | None -> ""

(* An unknown extension with no [--flavour] is an ERROR, never a silent
   fallback to [Escape.None_]: guessing the flavour wrong produces malformed
   output (unescaped LaTeX/HTML metacharacters) that looks fine until it does
   not -- the same "never silently substitute" discipline [data_dir]'s own
   [COLITUR_DATA_DIR] handling documents above.

   Both error messages below list the flavours by walking [Escape.all]
   rather than a hand-typed literal, on purpose: a hand-typed list is
   exactly the kind of call site the design claims does not exist outside
   escape.ml (spec section 5) -- adding Typst as a seventh flavour found
   this one had drifted from that claim (it silently still said "the six
   flavours" until then), so this is now future-proof against the same
   drift the next flavour would otherwise reintroduce. *)
let flavour_names_comma () =
  match List.map Colitur_render.Escape.to_string Colitur_render.Escape.all with
  | [] -> ""
  | [ x ] -> x
  | xs -> (
      match List.rev xs with
      | last :: rest -> String.concat ", " (List.rev rest) ^ " or " ^ last
      | [] -> "")

let flavour_names_bar () =
  String.concat "|" (List.map Colitur_render.Escape.to_string Colitur_render.Escape.all)

let table_report ~rite ~lang ~sigla ~template ~flavour_opt ~overlays y =
  let flavour =
    match flavour_opt with
    | Some name -> (
        match Colitur_render.Escape.of_string name with
        | Some f -> f
        | None ->
            Printf.eprintf "colitur: unknown flavour %S (want %s)\n" name (flavour_names_comma ());
            exit 2)
    | None -> (
        match Colitur_render.Escape.of_extension (extension template) with
        | Some f -> f
        | None ->
            Printf.eprintf "colitur: cannot infer a flavour from %S; pass --flavour %s\n"
              (extension template) (flavour_names_bar ());
            exit 2)
  in
  match read_file template with
  | Error msg ->
      Printf.eprintf "colitur: %s\n" msg;
      exit 2
  | Ok src -> (
      let v = view_of_year ~rite ~lang ~sigla ~overlays y in
      match Colitur_render.Template.render_string ~flavour src v with
      | Error e ->
          (* The template is user input; a parse failure is reported with the
             parser's OWN reason and exits 2, never an uncaught exception. *)
          Printf.eprintf "colitur: template %s: %s\n" template e;
          exit 2
      | Ok out -> print_string out)

(* Task 12: `colitur publish` -- writes the static tree that IS this
   project's API: a set of files any web server or git repo can serve as-is,
   computed once, with nothing running at request time.

   Two properties matter more than anything else here:

   DETERMINISTIC -- publishing the same year range twice must produce a
   byte-identical tree. That is what makes publishing into a git repo safe:
   `git status` shows only genuine change, and a human reviews a real diff
   before pushing. Nothing below reads a wall clock; [dtstamp] is threaded
   through as a plain parameter all the way to
   {!Colitur_render.Emit_ics.year}, exactly as `emit --format ics` already
   requires (see that command's own comment above).

   NON-DESTRUCTIVE -- publish writes only files it owns, names every one of
   them in a manifest ([.colitur-manifest], one relative path per line,
   itself never subject to pruning), and [--prune] removes only entries
   THAT MANIFEST lists which this run did not rewrite. A file the caller put
   in the output directory themselves is never in the manifest, so it is
   never touched, with or without [--prune] -- asserted in both directions
   in test/cli.t. *)

let rec mkdir_p path =
  if path <> "" && path <> "/" && not (Sys.file_exists path) then begin
    mkdir_p (Filename.dirname path);
    try Unix.mkdir path 0o755 with Unix.Unix_error (Unix.EEXIST, _, _) -> ()
  end

let write_file path contents =
  mkdir_p (Filename.dirname path);
  let oc = open_out_bin path in
  output_string oc contents;
  close_out oc

let manifest_name = ".colitur-manifest"

(* [read_file] rather than a second hand-rolled reader -- see its own
   comment above for why the whole read, not only the open, is guarded. A
   missing manifest (the very first publish into a fresh directory) is not
   an error here: it just means there is nothing yet to prune against. *)
let read_manifest out =
  match read_file (Filename.concat out manifest_name) with
  | Error _ -> []
  | Ok contents -> String.split_on_char '\n' contents |> List.filter (fun l -> l <> "")

(* Fix round 1 (coordinator review), CRITICAL: a manifest entry is
   UNTRUSTED input the moment [--prune] reads it back. The manifest is a
   plain-text file that lives INSIDE the very tree this feature exists to
   have committed into a git repo -- an ordinary bad merge or a hand-edit is
   enough to put an arbitrary path in it, no attacker required. Without a
   check, an entry like "../outside/CANARY.txt" resolves, via
   [Filename.concat out entry], to a path OUTSIDE [out], and the prune loop
   below would [Sys.remove] it -- deleting a file [publish] never wrote,
   breaking the "never deletes a file it does not own" contract outright.

   Two independent checks, deliberately, because either alone is easy to
   regress later without anyone noticing in review:

   1. STRUCTURAL ([manifest_entry_is_safe]) -- reject an entry that is
      absolute, or that has a ".." path component anywhere. Split on '/'
      and compare COMPONENTS, never a bare substring test: substring-
      matching ".." would wrongly reject a legitimate name like
      "foo..bar", which contains the two characters but has no ".."
      component of its own.
   2. CONTAINMENT ([resolves_under]) -- even an entry that passes check 1
      is not trusted until the path it actually resolves to, symlinks
      included, is verified to sit under [out]. [Unix.realpath] resolves
      symlinks as well as "..", so this also catches an entry that a
      symlink planted inside [out] could use to defeat check 1 alone. A
      plain string-prefix compare is not enough by itself either:
      "/tmp/pub1" is a byte-prefix of "/tmp/pub1-evil", a directory that is
      not nested inside it at all, so [is_under] insists the character
      right after the prefix is the path separator (or that the paths are
      identical). *)
let manifest_entry_is_safe entry =
  entry <> ""
  && entry.[0] <> '/'
  && not (List.mem ".." (String.split_on_char '/' entry))

let is_under ~root path =
  let root =
    if String.length root > 1 && root.[String.length root - 1] = '/' then
      String.sub root 0 (String.length root - 1)
    else root
  in
  String.equal path root
  || (String.length path > String.length root
     && String.sub path 0 (String.length root) = root
     && path.[String.length root] = '/')

(* [Unix.realpath] requires the path to exist, which is fine here: every
   caller below checks [Sys.file_exists]/[Sys.readdir] first. Any failure
   (missing path, dangling symlink, permission error) is treated as "not
   contained" -- refuse to act rather than guess. *)
let resolves_under out p =
  match Unix.realpath out with
  | exception (Unix.Unix_error _ | Sys_error _) -> false
  | out_real -> (
      match Unix.realpath p with
      | exception (Unix.Unix_error _ | Sys_error _) -> false
      | p_real -> is_under ~root:out_real p_real)

(* [--prune] deletes the FILES a stale manifest entry names, but that alone
   can leave their parent directories (ef/<year>/<mm>/, then ef/<year>/)
   empty behind them -- and an empty directory still makes `test -d
   out/ef/<year>` true, which is exactly the check a caller uses to confirm
   an old year is gone. Walk upward from each deleted file's own directory,
   removing it while it is empty, stopping at (never including) [out]
   itself: [out] is the caller's own directory, never ours to remove, even
   when it is empty. The same containment discipline as the file deletions
   above applies here too ([resolves_under]), not only structurally (this
   function is only ever reached via a [p] the file-deletion path already
   validated, but re-checking each directory step is the belt to that
   entry's braces -- see the two-layer reasoning above). *)
let rec prune_empty_dirs ~out dir =
  if
    dir <> out
    && String.length dir > String.length out
    && Sys.file_exists dir
    && resolves_under out dir
  then
    match Sys.readdir dir with
    | [||] ->
        (try Unix.rmdir dir with Unix.Unix_error _ -> ());
        prune_empty_dirs ~out (Filename.dirname dir)
    | _ -> ()
    | exception Sys_error _ -> ()

(* schema/day-v1.json is resolved the same prefix-relative way [data_dir]
   above resolves data/ef/*.sexp -- NOT from the process's own cwd, which
   would break an installed binary invoked from an arbitrary directory. Two
   candidates, installed then build-tree, the same shape as [data_dir]; a
   candidate counts only if the file is actually there. No COLITUR_DATA_DIR
   override here: that variable's whole contract is about the directory
   holding sanctoral.sexp, and schema/ is not nested inside it.

   The installed candidate assumes schema/ lands at
   <prefix>/share/colitur/schema/day-v1.json, mirroring data/dune's own ef/
   layout. Adding that install rule is explicitly Task 13's job, not this
   one -- this function only has to be ready to find the file once the rule
   exists, which is why it is PROBED rather than assumed, exactly like
   [data_dir]'s own installed candidate. *)
let schema_path () =
  let prefix = Filename.dirname (Filename.dirname Sys.executable_name) in
  let installed =
    List.fold_left Filename.concat prefix [ "share"; "colitur"; "schema"; "day-v1.json" ]
  in
  let build_tree = List.fold_left Filename.concat prefix [ "schema"; "day-v1.json" ] in
  if Sys.file_exists installed then Some installed else if Sys.file_exists build_tree then Some build_tree else None

(* An ordinary OCaml string, NOT a template: it describes the TREE, not the
   calendar, so it has no business in the template vocabulary. *)
(* Fix 1 (cli-flags-report, 2026-08-27): [rite_id] ("ef" or "of") replaces
   the literal "ef" this page used to hardcode throughout -- both the link
   paths (matching [publish_report]'s own [rite_id ^ "/" ...] tree below)
   and the descriptive sentence, which named the 1962 Missal unconditionally
   even though this page is now generated for either rite's own publish
   run. For [rite_id = "ef"] every byte below is unchanged from before this
   parameter existed -- the EF byte-identity constraint this task is held
   to. *)
let index_html ~rite_id ~from_y ~to_y =
  let missal_sentence =
    if rite_id = "ef" then "Liturgical calendar of the 1962 Missale Romanum."
    else "Liturgical calendar of the post-1970 (Ordinary Form) Roman Missal, base calendar the 2002 \
          Missale Romanum (editio typica tertia)."
  in
  let b = Buffer.create 4096 in
  Buffer.add_string b
    (Printf.sprintf
       "<!doctype html>\n<html lang=\"en\"><head><meta charset=\"utf-8\">\n\
        <title>colitur</title>\n\
        <style>body{font-family:sans-serif;max-width:40em;margin:2em auto;line-height:1.5}\n\
        code{background:#f4f4f4;padding:.1em .3em}</style></head><body>\n\
        <h1>colitur</h1>\n\
        <p>%s Citations only \xe2\x80\x94 never scripture text.</p>\n"
       missal_sentence);
  Buffer.add_string b "<h2>Subscribe</h2>\n<ul>\n";
  for y = from_y to to_y do
    Buffer.add_string b
      (Printf.sprintf "<li><a href=\"%s/%d.ics\">%s/%d.ics</a></li>\n" rite_id y rite_id y)
  done;
  Buffer.add_string b "</ul>\n<h2>Data</h2>\n<ul>\n";
  for y = from_y to to_y do
    Buffer.add_string b
      (Printf.sprintf
         "<li>%d: <a href=\"%s/%d.json\">json</a> <a href=\"%s/%d.csv\">csv</a> \
          <a href=\"%s/%d.xml\">xml</a> \xe2\x80\x94 per-day at <code>%s/%d/MM/DD.json</code></li>\n"
         y rite_id y rite_id y rite_id y rite_id y)
  done;
  Buffer.add_string b
    "</ul>\n<p>Contract: <a href=\"schema/day-v1.json\">schema/day-v1.json</a></p>\n\
     </body></html>\n";
  Buffer.contents b

(* Fix 1 (cli-flags-report, 2026-08-27): `publish` widened to `--rite of`.
   [rite_id] names the output subtree ("ef/" or "of/", mirroring
   [index_html]'s own parameter of the same name) -- every occurrence of
   the literal "ef" the write loop below used to hardcode is replaced by
   it, so an EF publish run (the default) writes the identical tree it
   always did, and an OF run writes the same shape one directory over,
   never colliding with it. A single [--out] directory can therefore hold
   BOTH rites' trees side by side across two separate invocations (one
   `--rite ef`, one `--rite of`) -- but NOT safely with [--prune] on
   either: the manifest and index.html this function writes are for the
   WHOLE tree, not per-rite, so a `--rite of` run's own [written] list
   never mentions the other rite's files, and [--prune] would delete them
   as stale. This is a genuine, disclosed limitation (see this task's own
   report), not a silent one: publish a single rite per [--out] directory,
   or omit [--prune] when deliberately layering both. *)
let publish_report ~rite ~lang ~sigla ~from_y ~to_y ~out ~overlays ~dtstamp ~prune =
  let rite_id = match rite with `Ef -> "ef" | `Of -> "of" in
  check_dtstamp dtstamp;
  if from_y > to_y then begin
    Printf.eprintf "colitur: --from %d is after --to %d\n" from_y to_y;
    exit 2
  end;
  (* Resolved and read BEFORE any file is written, so a missing/unreadable
     schema fails fast, before the output directory has anything half-
     written in it. [read_file]'s own error text says "cannot read
     template ..." (it was built for Task 9's template reads) -- accurate
     about the mechanism, wrong about the noun, so the message here is
     rebuilt rather than printed verbatim. *)
  let schema =
    match schema_path () with
    | None ->
        Printf.eprintf
          "colitur: cannot find schema/day-v1.json (looked in the installed and build-tree locations)\n";
        exit 2
    | Some p -> (
        match read_file p with
        | Error _ ->
            Printf.eprintf "colitur: cannot read schema %s\n" p;
            exit 2
        | Ok s -> s)
  in
  let written = ref [] in
  let emit rel contents =
    write_file (Filename.concat out rel) contents;
    written := rel :: !written
  in
  (* [write_year] is generic over [('s, 'r)] -- a plain let-bound function
     value, so it generalises fully (the same reason [resolved_year_report]
     above generalises over its own [~line]) -- and is instantiated once
     per rite branch below, at THAT branch's own concrete [Liturgical_day.t]
     type. [days] cannot be hoisted out of the branch the way [v] is
     elsewhere in this file: [resolved_year_days]/[resolved_of_year_days]
     return two DIFFERENT, incompatible monomorphic types (EF's own
     [Vocab_ef.season/rank] vs OF's), so a single [let days = match rite
     with ...] binding shared by both branches would not type-check --
     [mk_view] and every write using [days] must stay inside the SAME
     branch that produced it, per rite. *)
  let write_year ~ys days mk_view =
    let v = mk_view days in
    emit (rite_id ^ "/" ^ ys ^ ".json") (Colitur_render.Emit_json.year v);
    emit (rite_id ^ "/" ^ ys ^ ".csv") (Colitur_render.Emit_csv.year v);
    emit (rite_id ^ "/" ^ ys ^ ".xml") (Colitur_render.Emit_xml.year v);
    emit (rite_id ^ "/" ^ ys ^ ".ics") (Colitur_render.Emit_ics.year ?dtstamp v);
    (* One file per day: the static equivalent of a per-day endpoint.
       [View.of_days] with a one-day list yields 12 months, 11 empty, one
       populated -- exactly the shape a single day's own page needs. *)
    List.iter
      (fun d ->
        let iso = D.to_iso8601 d.Colitur_kernel.Liturgical_day.date in
        let mm = String.sub iso 5 2 and dd = String.sub iso 8 2 in
        let one = mk_view [ d ] in
        emit (Printf.sprintf "%s/%s/%s/%s.json" rite_id ys mm dd) (Colitur_render.Emit_json.year one))
      days
  in
  for y = from_y to to_y do
    let ys = string_of_int y in
    match rite with
    | `Ef ->
        let days = resolved_year_days ~overlays y in
        write_year ~ys days (fun days ->
            Colitur_render.View.of_days ~lang ~sigla ~vocab:Rite_ef.Vocab_ef.vocab ~rite:rite_id ~year:y
              days)
    | `Of ->
        let days = resolved_of_year_days ~overlays y in
        write_year ~ys days (fun days ->
            Colitur_render.View.of_days ~lang ~sigla ~vocab:Rite_of.Vocab_of.vocab ~rite:rite_id ~year:y
              days)
  done;
  emit "schema/day-v1.json" schema;
  emit "index.html" (index_html ~rite_id ~from_y ~to_y);
  let now = List.sort compare !written in
  (* Every stale entry is validated TWICE before anything is removed --
     see [manifest_entry_is_safe]/[resolves_under]'s own comment above for
     why both layers exist. A rejected entry is skipped and warned about on
     stderr, never fatal: a corrupt or hand-mangled manifest must not make
     `publish` itself unusable -- it completes, having refused to act on
     the bad line. *)
  if prune then
    List.iter
      (fun old ->
        if not (List.mem old now) then
          if not (manifest_entry_is_safe old) then
            Printf.eprintf
              "colitur: refusing to prune manifest entry %S (absolute path or .. component)
" old
          else begin
            let p = Filename.concat out old in
            if Sys.file_exists p then
              if resolves_under out p then begin
                Sys.remove p;
                prune_empty_dirs ~out (Filename.dirname p)
              end
              else
                Printf.eprintf "colitur: refusing to prune %s (resolves outside %s)
" p out
          end)
      (read_manifest out);
  write_file (Filename.concat out manifest_name) (String.concat "\n" now ^ "\n");
  Printf.printf "colitur: wrote %d files to %s\n" (List.length now) out

(* Help and usage are deliberately DIFFERENT things, and the difference is the
   Unix convention rather than a preference: asking for help is a request that
   SUCCEEDED, so [--help] prints to stdout and exits 0 (it can be piped into a
   pager or grepped); being invoked wrongly is an error, so [usage] prints a
   one-liner to stderr and exits 2, keeping stdout clean for whatever the
   caller was really trying to capture. *)
(* Kept in lockstep with dune-project's own [(version ...)] by `make release`,
   which bumps BOTH and refuses to proceed if either edit did not take. Two
   places rather than one because dune's watermarking (`dune subst`) only
   substitutes in a release tarball, not in a plain `dune build` from a
   checkout, so a binary built the ordinary way would report a placeholder.
   A constant edited by the release target is what lectio does too, for the
   same reason. Deliberately NOT embedded in [help_text]: the cram test pins
   help's first line, and a version in it would make every release edit a
   test expectation for no gain. *)
let version = "1.1.0"

let help_text =
  {|colitur -- deterministic liturgical calendar engine (Roman rite, 1962)

usage:
  colitur easter <year>      Easter, and the movable feasts anchored to it
  colitur temporal <year> [--rite ef|of]
                              the temporal cycle, one line per day
  colitur day <year>         the resolved day identity, one line per day
  colitur readings <year>    the Mass reading citations, one line per day
  colitur rubrics <year>     the Mass formulary said, one line per day
  colitur day|readings|rubrics [<year>] [--year Y] [--rite ef|of]
              [--overlay FILE ...] [--lang CODE|FILE] [--raw]
              <year> may be given positionally or as --year (both, if they
              agree); rubrics's own --lang/--raw govern its trailing
              formulary-name column, --sigla-* stay refused there (see
              "naming" below)
  colitur emit --format csv|json|sexp|xml|ics --from Y --to Y [--rite ef|of]
              [--overlay FILE ...] [--dtstamp S] [--lang CODE|FILE] [--raw]
              render a resolved year range through one of five emitters
  colitur table [<year>] [--year Y] --template FILE [--rite ef|of]
              [--flavour X] [--overlay FILE ...] [--lang CODE|FILE] [--raw]
  colitur render --template FILE [<year>] [--year Y] [--rite ef|of]
              [--flavour X] [--overlay FILE ...] [--lang CODE|FILE] [--raw]
              compute year Y and render it through FILE, a logic-less
              Mustache-family template; table and render are the same
              operation, two names (see "rendering" below)
  colitur publish --from Y --to Y --out DIR [--rite ef|of]
              [--overlay FILE ...] [--prune] [--dtstamp S]
              [--lang CODE|FILE] [--raw]
              write the static tree: per-year csv/json/xml/ics, one JSON
              file per day, the schema and a generated index (see
              "publish" below)
  colitur lang --list        which language files this build can find
  colitur lang --dump CODE   a language's full key set, in INI form, on stdout
  colitur lang --check FILE  what a language file is missing, and any typo'd key
  colitur config --show      every setting, its value and where it came from
  colitur new-overlay        print a starter overlay file to stdout
  colitur convert FILE.ini   flat INI overlay -> S-expression, on stdout
  colitur check FILE ...     load an overlay, say what it does, exit 2 if not
  colitur -h, --help         this help
  colitur -V, --version      print the version and exit

<year> is a civil year, 1583..9999 inclusive. Each report covers 1 January to
31 December of that year, not a liturgical year. `emit`/`publish` take a
RANGE instead (--from Y --to Y, inclusive) and do not also accept a single
--year or positional year -- deliberate: they may compute many years in one
run, and a third, single-year spelling on top of the range form would add
parsing surface for no real workflow gain.

output formats:
  day       date weekday season week slug rank colour [+commemoration ...] [name]
            2026-04-05 sunday paschaltide 1 ef-easter-sunday class-1 white
  readings  date slug | Epistle | Gospel [| name]
            2026-12-25 ef-nativity | Heb 1:1-12 | John 1:1-14
  rubrics   date, formulary slug, source, creed, gloria, preface [name] -- TAB-separated
            2026-01-01[TAB]ef-circumcision[TAB]own[TAB]true[TAB]true[TAB]nativity[TAB]In Octava Nativitatis Domini

  A citation contains spaces, so readings uses " | " between its fields while
  day stays space-separated; that is why they are separate commands rather
  than extra columns. The same reasoning is why the resolved display NAME,
  present by default (see "naming" below), is appended as the LAST field
  rather than substituted for the slug shown above: a name may itself
  contain spaces, and inserting it earlier in the row would break every
  fixed-position field that follows it. It is present only when it differs
  from the slug already shown -- under --raw, or any language with no entry
  for that particular day, the trailing field is simply absent, which is
  what makes --raw byte-identical to this program's pre-naming output.

  rubrics prints which Mass is actually said and how that was decided
  (source: proper/own/preceding-sunday/common/votive) -- not always the
  day's own: a weekday with no proper resumes the preceding Sunday's, a
  saint with no proper says his assigned Common -- followed by whether the
  Creed is said (RG 475-476), whether the Gloria in excelsis is said
  (RG 431-432, deferring to the Breviary's own Te Deum rule, nn. 237-238,
  for RG 431(a)), and which preface is said (RG 482-499) -- Creed/Gloria
  both "true"/"false", OCaml's own literal, not "yes"/"no" or "1"/"0";
  preface one of nativity/epiphany/lent/holy-cross/easter/ascension/
  sacred-heart/christ-the-king/holy-spirit/trinity/bvm/st-joseph/apostles/
  common/requiem, or "-" when this engine resolves no Mass at all that day
  (Good Friday). TAB-separated rather than space or " | ": the resolved
  formulary NAME (below) can carry both spaces and punctuation a citation
  never does, which rules out either alternative already in use above.
  --overlay is accepted (the observed celebration it changes decides the
  formulary, the Creed, the Gloria and the preface); --sigla-* are refused
  -- this row prints no citation for them to affect.

  --lang/--raw ARE accepted (unlike --sigla-*): `said` (the formulary slug)
  is a machine key exactly like `day`'s own slug, and this row resolves it
  to a display name under the identical append-only rule day/readings use
  -- present as a trailing 8th field only when it differs from the slug
  already printed, so --raw (or a language with no entry for that day) is
  byte-identical to the seven-field row shown above.

  emit      one schema (season, week, slug, rank, colour, subject, names,
            citations, commemorations), rendered five ways: csv (RFC 4180,
            one header for the whole run), json, sexp, xml (schema/colitur-
            v1.xsd) and ics (RFC 5545). --from/--to give a civil-year range,
            inclusive. --dtstamp fixes the ics DTSTAMP so two runs over the
            same data are byte-identical -- the engine reads no clock.

rite:
  --rite ef|of selects which rite module a command computes against;
            default ef (so every invocation written before this flag
            existed is unaffected). `of` is the 1970 Missale Romanum
            (editio typica tertia, 2002). Accepted on `day`, `readings`,
            `rubrics`, `temporal`, `emit`, `table`, `render` and `publish`;
            refused, not silently ignored, on `check`/`convert` (operate
            on an overlay FILE, not a computed year), `new-overlay`
            (prints a static starter, no calendar computation), and
            `lang`/`config` (answer naming/config questions orthogonal to
            any rite). `easter` is refused too, but PROVEN rite-invariant
            rather than merely unbuilt for `of`: EF and OF reckon Easter
            on the identical Gregorian computus, so no second value could
            ever change the six dates it prints.

            `emit --format csv --rite of` and `publish --rite of` widen
            their CSV output with a 17th column, "second", between
            "first" and "gospel" -- present, and usually empty, because a
            Sunday or solemnity genuinely carries a Second reading (OLM
            1981 Praenotanda n. 66.1) and a feria/feast/memorial does not
            (n. 69.1); EF's own 16-column CSV header is unaffected, byte
            for byte, because EF's `citations` never contains one. json/
            xml/sexp/ics need no such widening -- each already had a place
            for a variable-length reading list.

            A single `--out` directory can hold both rites' own `publish`
            trees side by side ("ef/", "of/"), but not safely combined
            with --prune on either: publish's own manifest and index.html
            describe the WHOLE tree, not one rite's slice of it, so a
            later run for the other rite would not know the first run's
            files exist and --prune would delete them as stale. Publish a
            single rite per --out, or omit --prune when deliberately
            layering both.

overlays:
  --overlay FILE (repeatable, ordered; -o) applies a user calendar ON TOP of
            the shipped universal one, never instead of it, so local feasts
            add to it rather than replacing it. Later files win over earlier
            ones, and over the universal calendar, when they name the same
            slug. Accepted on `day`, `readings`, `rubrics`, `emit`, `table`,
            `render` and `publish` -- `easter` and `temporal` read no
            sanctoral data, so the flag is refused there rather than
            silently ignored.

            An overlay is applied, NOT validated: colitur's test layers assert
            things about the shipped calendar and cannot vouch for a file you
            supply. A directive naming a slug that does not exist warns on
            stderr and the run continues; a file that fails to load is fatal.

            To write one:

              colitur new-overlay > my-parish.sexp   # a commented starter
              $EDITOR my-parish.sexp
              colitur check my-parish.sexp           # parses? every directive hit?
              colitur day 2026 --overlay my-parish.sexp

            `check` reports what each directive targets and exits 2 if a file
            will not load or a directive matched nothing, so it fits a
            Makefile or a pre-commit hook. It does not check a calendar
            against the rubrics -- nothing here can.

            A flatter INI form exists for simple calendars, converted with
            `colitur convert`, which verifies its own output before emitting
            it. See colitur-overlay(5) for both forms.

            In an added celebration, `citations` and `layer` may be omitted:
            they default to empty and to the overlay's own id. Dates may be
            (Fixed (month M) (day D)), (Easter_offset N) signed, or
            (Nth_weekday (month M) (nth N) (weekday W)) with N negative to
            count from the end of the month.

year:
  `day`, `readings`, `rubrics`, `table` and `render` each take a single
            civil year, sayable two ways -- positionally (`colitur day
            2026`) or as --year (`colitur day --year 2026`) -- additively:
            neither form was removed when the other was added, so every
            invocation that worked before still works unchanged. Naming
            both is fine as long as they agree (`colitur day 2026 --year
            2026`); naming both with DIFFERENT years is a hard usage error
            rather than one silently winning.

            `emit`/`publish` deliberately do NOT gain a --year: they take
            --from Y --to Y instead (see the usage block above), and stay
            that way even for a single-year run (`--from 2026 --to 2026`)
            -- a third spelling meaning exactly the same thing as the two
            above would add parsing surface, and a range command's own
            natural single-year form is already `--from Y --to Y`, not a
            new flag.

naming:
  --lang CODE|FILE applies to `day`, `readings`, `rubrics`, `emit`,
            `table`, `render` and `publish`. A CODE (e.g. `la`, `en`) is
            looked up as
            <lang-dir>/CODE.ini; a value containing '/' or ending ".ini" is
            read as a literal path instead. Default `la`, overridable by a
            config file (see below). An unknown language is a hard ERROR
            naming what is available (try `colitur lang --list`), never a
            silent fallback to Latin -- a booklet quietly printed in the
            wrong language is worse than one that refuses to print. A
            language file may declare `fallback = CODE` in its [meta]
            section, so a partial translation shows its fallback language
            for the keys it does not itself carry, rather than bare slugs.

  --raw     restores every command's pre-naming output: `name` (and every
            other localised field `emit`'s schema carries) equals the bare
            machine slug, exactly as if no language had ever been resolved.
            This is not a special case threaded through the naming code --
            it is `colitur lang`'s own identity table, under which every
            lookup echoes its key back unchanged.

  --sigla-style CODE|FILE, --sigla-book full|abbr, --sigla-tradition NAME
            settings for how a Mass reading CITATION is written -- WHICH
            punctuation/abbreviation style, WHICH book form, and WHICH
            numbering tradition. Each has a config-key counterpart
            (`sigla_style`/`sigla_book`/`sigla_tradition`) resolved with
            the identical flag > config > default precedence as --lang, and
            each is reported by `colitur config --show` with its source.
            Defaults: `sigla_style` the resolved language code (so a
            booklet's citations follow its own --lang unless told
            otherwise), `sigla_book` `abbr`, `sigla_tradition` `vulgate`.
            An unrecognised `--sigla-book` is a hard ERROR (want `full` or
            `abbr`), the same discipline as an unknown `--lang`; an
            unrecognised `--sigla-tradition` is not -- it degrades to the
            Vulgate with a stderr warning, because asking for a renumbering
            is optional the way asking for a language is not. `--raw`
            bypasses all of it and emits each citation exactly as stored,
            byte for byte, so it stays usable for diffing and does not
            depend on the citation parser being correct.

  colitur lang --list         which language files this build can find, and
                               each one's own declared fallback, if any.
  colitur lang --dump CODE    the named language's full key set, in INI
                               form, on stdout -- a starting point for a new
                               translation, or a way to diff two versions of
                               one.
  colitur lang --check FILE   what a language file is MISSING (a real slug
                               with no entry) and, separately, any entry
                               naming a slug that does not exist at all (a
                               typo, silently dead otherwise) -- exits 1 if
                               anything is unknown, so it fits a Makefile or
                               a pre-commit hook.
  colitur config --show       every effective setting -- lang, overlay,
                               template, format, sigla_style, sigla_book,
                               sigla_tradition -- its resolved value, and
                               where it came from: `flag`, `config` or
                               `default`. See colitur-config(5) for the
                               config file's location and full precedence.

rendering:
  --template FILE (required on `table`/`render`) is a logic-less Mustache-
            family template: {{placeholder}}, {{#section}}...{{/section}},
            {{^inverted}}...{{/inverted}}, {{!comment}} -- nothing else. It is
            DATA, never a program: no partials, no lambdas, no expression
            evaluation, no filesystem or process access, and no "raw" or
            triple-brace form that could opt out of escaping. The value it
            renders against is the same schema `emit` uses (season, week,
            slug, rank, colour, subject, names, citations, commemorations),
            reshaped into a booklet (`days`) and a month grid (`weeks`, with
            padding cells for the leading/trailing blanks); see
            colitur-templates(5) for the full field list, the syntax, and
            the one remaining scope hazard (`num` -- both a month and a week
            carry it, and only the innermost one is ever meant). `name` is a
            plain resolved string, not a lang-keyed object, so it carries no
            equivalent hazard of its own.

  --flavour X selects how interpolated VALUES are escaped (never the
            template's own literal markup, which is the author's). One of:

              latex   typst   groff   html   xml   ics   none

            Inferred from --template's extension when --flavour is omitted:

              .tex              -> latex
              .typ              -> typst
              .ms .mom .me      -> groff
              .html .htm        -> html
              .xml              -> xml
              .ics              -> ics
              .md .adoc .txt    -> none (no metacharacters are escaped;
                                   Markdown/AsciiDoc/plain text have no fixed
                                   metacharacter set, so escaping them here
                                   would produce worse output than leaving
                                   them alone)

            An extension colitur does not recognise is a hard ERROR naming
            the seven flavours above, never a silent fallback to `none`:
            guessing wrong produces output that looks fine until the
            metacharacters it silently failed to escape show up.

  `table` and `render` are the SAME operation under two names. The design
            this project followed originally sketched `compute | render` as a
            Unix pipe, with `render` reading a serialised view back from
            stdin. That is deliberately not built: honouring the pipe would
            need a JSON *parser*, purely so this program could re-read a view
            it had just serialised itself -- a second hand-rolled component,
            and a second place for the published contract to drift, for no
            benefit over calling the view builder directly in the same
            process. There is therefore no stdin-fed `render`; `colitur emit
            --format json | jq` still composes for real pipe use, because
            that JSON is the OUTPUT, never something colitur itself parses
            back in.

publish:
  --out DIR (required) writes the static tree that IS this program's API:
            any web server or git repo can serve it as-is, and nothing runs
            at request time.

              <rite>/<year>.{json,csv,xml,ics}   one civil year, all days
              <rite>/<year>/<mm>/<dd>.json       one file per day
              schema/day-v1.json                 the published JSON contract
              index.html                         a generated index page
              .colitur-manifest                  every path this run wrote

            <rite> is "ef" or "of", selected by --rite exactly as on every
            other command (default ef) -- see "rite" above for what a
            single --out directory holding both rites' own trees needs.

            Deterministic: publishing the same --from/--to range twice
            produces a byte-identical tree (--dtstamp behaves exactly as on
            `emit`). That is what makes publishing into a git repo safe --
            `git status` shows only real change, and you review an actual
            diff before pushing.

            Non-destructive: publish writes only files it owns, and records
            every one in .colitur-manifest. A file you put in the output
            directory yourself is never in that manifest, so it is never
            touched, whether or not --prune is given. --prune additionally
            removes manifest entries from a PREVIOUS run that this run did
            not rewrite (e.g. an earlier year's per-day files, when you
            publish a different range into the same directory) -- never
            anything the manifest does not name.

environment:
  COLITUR_DATA_DIR
            Read the calendar data from this directory instead of the
            installed (<prefix>/share/colitur/ef) or build-tree location.
            If it is set and holds no sanctoral.sexp, colitur exits 2 rather
            than silently falling back to a different copy of the data.

exit status:
  0  success
  2  bad usage, year out of range, or the calendar data could not be read

Reading references only (e.g. "Jn 3:16"); never scripture text.
See colitur(1) for the full description and the sources it computes against,
colitur-overlay(5) for the overlay file format in full,
colitur-templates(5) for the template format in full -- the syntax, the
remaining scope hazard, the seven flavours' escaping, and the full view-model
field reference -- and colitur-config(5) for the config file's location and
precedence in full.|}

let print_help () =
  print_endline help_text;
  exit 0

let usage () =
  prerr_endline
    "colitur: usage: colitur easter <year> | colitur temporal <year> | colitur day <year> | colitur \
     readings <year> | colitur rubrics <year> | colitur emit --format FMT --from Y --to Y | colitur \
     table --year Y --template FILE | colitur render --template FILE --year Y | colitur publish \
     --from Y --to Y --out DIR | colitur lang --list|--dump CODE|--check FILE | colitur config --show \
     | colitur check FILE | colitur new-overlay  (try: colitur --help)";
  exit 2

let with_year ys f =
  match int_of_string_opt ys with
  | Some y when y >= 1583 && y <= 9999 -> f y
  | Some y ->
      Printf.eprintf "colitur: year %d out of range 1583..9999\n" y;
      exit 2
  | None -> usage ()

(* Task 5 (2026-08-25-colitur-of-phases-3-5): resolves [--rite] to a closed
   choice -- [None] (the flag was never given) and [Some "ef"] both mean
   "ef", so that existing invocations with no [--rite] at all are
   byte-identical to before this flag existed (spec's own requirement,
   verified in test/cli.t). Anything other than "ef"/"of" is a usage error,
   not a silent fallback to "ef" -- the same "an unrecognised value is
   refused, not guessed at" discipline every other closed-choice flag in
   this file follows (`--sigla-book full|abbr`, `lang --dump CODE`). Shared
   by every command [reject_rite_for] lets the flag reach -- `day`/
   `readings` originally, widened (Fix 1, cli-flags-report) to `rubrics`,
   `emit`, `table`/`render` and `publish`. *)
let resolve_rite = function
  | None | Some "ef" -> `Ef
  | Some "of" -> `Of
  | Some other ->
      Printf.eprintf "colitur: unknown --rite %S (expected \"ef\" or \"of\")\n" other;
      exit 2

(* Fix 3 (cli-flags-report, 2026-08-27): every single-year command
   (`day`/`readings`/`rubrics`/`table`/`render`) now accepts EITHER a
   positional year or [--year], additively -- neither form is removed, so
   every invocation that worked before this task keeps working unchanged.
   [emit]/[publish] deliberately do NOT gain this: they are RANGE commands
   ([--from]/[--to]), and the range form is the right one for a command
   that may compute many years in one run -- see this task's own report
   for why [--from Y --to Y] was considered and rejected as a third
   spelling here too. `easter`/`temporal` are also left alone: their own
   flag surface is deliberately closed end to end (every optional flag
   refused, not merely [--year]), and this task's brief names only the
   five data-computing commands above, not those two.

   Disagreement between the two forms (`day 2026 --year 2027`) is refused
   outright rather than one silently winning -- the same "never silently
   pick" discipline [--overlay] and every other flag in this file already
   follow. Agreement (`day 2026 --year 2026`) is accepted; it is redundant
   but not a contradiction. *)
let resolve_single_year cmd ~positional ~flag =
  match (positional, flag) with
  | Some p, None -> p
  | None, Some f -> f
  | Some p, Some f when p = f -> p
  | Some p, Some f ->
      Printf.eprintf "colitur: %s: positional year %s and --year %s disagree\n" cmd p f;
      exit 2
  | None, None ->
      Printf.eprintf "colitur: %s requires a year (positional or --year)\n" cmd;
      exit 2

(* Flags are stripped first, then the remaining words are matched as
   command + year. The alternative -- extending the exact-array patterns
   below -- does not survive a REPEATABLE flag: [--overlay a --overlay b] is a
   different array shape from [--overlay a], and every additional flag would
   multiply the patterns again. Hand-rolled because the dependency list is
   frozen and this is fifteen lines.

   [--overlay] accumulates in the order given, and that order is load-bearing
   ({!Overlay.merge} is last-writer-wins), so the list is reversed exactly
   once at the end rather than callers guessing.

   [--format]/[--from]/[--to]/[--dtstamp] (Task 8, `emit`) are each single-
   valued, unlike [--overlay], so they are plain [string option] fields
   rather than accumulating lists. *)
(* [year]/[template]/[flavour] (Task 9, `table`/`render`) are each single-
   valued, the same shape as [format]/[from_y]/[to_y]/[dtstamp] above --
   `table`/`render` take one year and one template file, never a range or a
   repeatable list. *)
(* [out] (Task 12, `publish`) is single-valued like [format]/[year]/etc.
   [prune] is a plain boolean flag -- every other field up to here takes a
   value, but [--prune] does not, so it cannot reuse the `"--flag" :: v ::
   rest` shape the value-taking flags share below. *)
(* [lang]/[raw] (Task 6): [lang] is single-valued like [format]/[template]/
   etc (a language CODE or a file path); [raw] is a second plain boolean,
   the same shape as [prune]. [dump]/[check]/[list]/[show] (Task 7,
   `colitur lang`/`colitur config`) follow the identical two shapes --
   [dump]/[check] each take one value, [list]/[show] are bare. *)
(* [sigla_style]/[sigla_book]/[sigla_tradition] (Task 8) are three more
   single-valued optional settings, the same shape as [lang] -- each has a
   config-key counterpart in [Colitur_naming.Config] and is resolved through
   the identical [Config.resolve] precedence (flag > config > default). *)
(* [rite] (Task 5, 2026-08-25-colitur-of-phases-3-5): single-valued like
   [lang], and deliberately a bare [string option] with no config-key
   counterpart -- unlike [lang]/[template]/[format], nothing in
   [Colitur_naming.Config] resolves a default rite, and this task does not
   add one (out of scope: the brief asks for `--rite of` on `day`/
   `readings` only). [None] means "ef", not "unset and therefore an
   error" -- existing invocations with no [--rite] at all must stay
   byte-identical, so the default has to be the CURRENT behaviour, not a
   forced choice. *)
type parsed_args = {
  overlays : string list;
  rite : string option;
  format : string option;
  from_y : string option;
  to_y : string option;
  dtstamp : string option;
  year : string option;
  template : string option;
  flavour : string option;
  out : string option;
  prune : bool;
  lang : string option;
  raw : bool;
  pretty : bool;
  dump : string option;
  check : string option;
  list : bool;
  show : bool;
  sigla_style : string option;
  sigla_book : string option;
  sigla_tradition : string option;
  positional : string list;
}

let parse_args argv =
  let rec go acc = function
    | [] -> Ok { acc with overlays = List.rev acc.overlays; positional = List.rev acc.positional }
    | ("--overlay" | "-o") :: path :: rest -> go { acc with overlays = path :: acc.overlays } rest
    | [ ("--overlay" | "-o") ] -> Error "--overlay needs a file path"
    | "--rite" :: v :: rest -> go { acc with rite = Some v } rest
    | [ "--rite" ] -> Error "--rite needs a value (ef or of)"
    | "--format" :: v :: rest -> go { acc with format = Some v } rest
    | [ "--format" ] -> Error "--format needs a value"
    | "--from" :: v :: rest -> go { acc with from_y = Some v } rest
    | [ "--from" ] -> Error "--from needs a value"
    | "--to" :: v :: rest -> go { acc with to_y = Some v } rest
    | [ "--to" ] -> Error "--to needs a value"
    | "--dtstamp" :: v :: rest -> go { acc with dtstamp = Some v } rest
    | [ "--dtstamp" ] -> Error "--dtstamp needs a value"
    | "--year" :: v :: rest -> go { acc with year = Some v } rest
    | [ "--year" ] -> Error "--year needs a value"
    | "--template" :: v :: rest -> go { acc with template = Some v } rest
    | [ "--template" ] -> Error "--template needs a value"
    | "--flavour" :: v :: rest -> go { acc with flavour = Some v } rest
    | [ "--flavour" ] -> Error "--flavour needs a value"
    | "--out" :: v :: rest -> go { acc with out = Some v } rest
    | [ "--out" ] -> Error "--out needs a directory path"
    | "--prune" :: rest -> go { acc with prune = true } rest
    | "--lang" :: v :: rest -> go { acc with lang = Some v } rest
    | [ "--lang" ] -> Error "--lang needs a language code or file path"
    | "--raw" :: rest -> go { acc with raw = true } rest
    | "--pretty" :: rest -> go { acc with pretty = true } rest
    | "--dump" :: v :: rest -> go { acc with dump = Some v } rest
    | [ "--dump" ] -> Error "--dump needs a language code"
    | "--check" :: v :: rest -> go { acc with check = Some v } rest
    | [ "--check" ] -> Error "--check needs a file path"
    | "--list" :: rest -> go { acc with list = true } rest
    | "--show" :: rest -> go { acc with show = true } rest
    | "--sigla-style" :: v :: rest -> go { acc with sigla_style = Some v } rest
    | [ "--sigla-style" ] -> Error "--sigla-style needs a language code or file path"
    | "--sigla-book" :: v :: rest -> go { acc with sigla_book = Some v } rest
    | [ "--sigla-book" ] -> Error "--sigla-book needs a value (full or abbr)"
    | "--sigla-tradition" :: v :: rest -> go { acc with sigla_tradition = Some v } rest
    | [ "--sigla-tradition" ] -> Error "--sigla-tradition needs a section name from lang/traditions.ini"
    (* The recognised bare flags pass through as positional words for the
       dispatch below to match; anything else beginning with '-' is rejected
       rather than silently treated as a command or a year. *)
    | arg :: _
      when String.length arg > 1
           && arg.[0] = '-'
           && not (List.mem arg [ "-h"; "--help"; "-V"; "--version" ]) ->
        Error (Printf.sprintf "unknown option %s" arg)
    | arg :: rest -> go { acc with positional = arg :: acc.positional } rest
  in
  go
    { overlays = []; rite = None; format = None; from_y = None; to_y = None; dtstamp = None; year = None;
      template = None; flavour = None; out = None; prune = false; lang = None; raw = false; pretty = false;
      dump = None; check = None; list = false; show = false; sigla_style = None; sigla_book = None;
      sigla_tradition = None; positional = [] }
    argv

(* Sibling to [reject_overlays_for]: `emit`'s own four flags have no meaning
   on any other command (they take a single [<year>] positional, not a
   [--from]/[--to] range), so accepting and silently dropping them would be
   the same failure mode `--overlay` already refuses on `easter`/`temporal`. *)
let reject_emit_flags_for cmd ~format ~from_y ~to_y ~dtstamp =
  if format <> None || from_y <> None || to_y <> None || dtstamp <> None then begin
    Printf.eprintf
      "colitur: --format/--from/--to/--dtstamp have no effect on `%s`; refusing rather than ignoring them\n"
      cmd;
    exit 2
  end

(* [easter] reads no calendar data at all, and [temporal] deliberately runs the
   temporal cycle BEFORE any sanctoral layer exists, so an overlay could not
   affect either. Accepting the flag there and silently ignoring it is the
   failure mode this project refuses everywhere else -- it is an error. *)
let reject_overlays_for cmd overlays =
  if overlays <> [] then begin
    Printf.eprintf "colitur: --overlay has no effect on `%s` (it reads no sanctoral data); refusing rather than ignoring it\n" cmd;
    exit 2
  end

(* Sibling to [reject_overlays_for]. Fix 1 (cli-flags-report, 2026-08-27)
   widened `--rite` from `day`/`readings` alone to also cover `rubrics`,
   `emit`, `table`/`render`, `publish` AND (coordinator-review fix round,
   same date) `temporal` -- every command whose OUTPUT actually depends on
   which rite computed it (this is plumbing, not new library work:
   {!Colitur_render.View.of_days}/{!Colitur_kernel.Record.of_temporal}
   were already fully polymorphic over [('s, 'r)], and both rite modules
   already existed). What is left refusing the flag does so because the
   flag would GENUINELY have no effect, not because of a stale scope note
   -- checked per command, not assumed as a group, after `temporal` was
   found wrongly grouped with `easter` here on a first pass (both refused,
   but for DIFFERENT reasons, one of which turned out not to hold):

   - `easter` computes only Easter and its own movable-feast anchors
     ({!Colitur_kernel.Computus.gregorian_easter} and friends) -- genuinely
     rite-invariant, not merely unbuilt for OF: both EF and OF reckon
     Easter on the identical Gregorian computus ({!Rite_of.Rite_of
     .context}'s own [easter] field cites this directly), so `--rite of`
     would recompute the exact same six dates, byte for byte. This is the
     one case in this whole file where "no effect" is actually PROVEN, not
     merely asserted.
   - `check`/`convert` operate on an OVERLAY FILE, not a computed year, and
     an overlay's own rank type is fixed by which rite loaded it, not by a
     flag on the command inspecting it.
   - `new-overlay` prints a static starter template with no calendar
     computation in it whatsoever.
   - `lang`/`config` answer questions about NAMING/CONFIG resolution,
     orthogonal to which rite a later `day`/`table` invocation might name.

   `temporal` is NOT on this list any more: it calls
   [Rite_ef.Temporal_ef.temporal] directly, the whole rite-specific
   temporal cycle (season, week numbering, every slug), so `--rite of`
   changes essentially every line (OF has five seasons, no Septuagesima,
   and an "of-" slug prefix throughout) -- refusing it under a "no effect"
   message was FALSE, not merely stale, confirmed directly: `colitur
   temporal 2026 | grep septuagesima` finds Septuagesima-tide rows that
   cannot exist under the OF's own Normae at all. --overlay stays refused
   on `temporal` regardless -- a SEPARATE, still-valid claim
   ([reject_overlays_for]'s own citation: the temporal cycle is computed
   before any sanctoral layer exists, in EITHER rite), which is what this
   comment's first pass actually meant to say about `temporal` and
   over-generalised to `--rite` by mistake. *)
let reject_rite_for cmd rite =
  if rite <> None then begin
    Printf.eprintf "colitur: --rite has no effect on `%s`; refusing rather than ignoring it\n" cmd;
    exit 2
  end

(* Sibling to [reject_emit_flags_for]/[reject_overlays_for]: `table`/`render`'s
   own three flags (Task 9) have no meaning on any other command, so accepting
   and silently dropping them would be the same failure mode this project
   already refuses everywhere else.

   Fix 3 (cli-flags-report, 2026-08-27) split [--year] out of this bundle:
   `day`/`readings`/`rubrics` now accept it (see [reject_template_flavour_for]
   below), so this three-flag rejector is no longer accurate for them.
   Every OTHER caller of this function (`--help`/`--version`/`easter`/
   `temporal`/`check`/`convert`/`new-overlay`/`lang`/`config`/`emit`/
   `publish`) still refuses [--year] exactly as before -- `emit`/`publish`
   in particular are RANGE commands ([--from]/[--to]), and deliberately do
   not gain a second, single-year spelling (see this task's own report for
   why). *)
let reject_table_flags_for cmd ~year ~template ~flavour =
  if year <> None || template <> None || flavour <> None then begin
    Printf.eprintf
      "colitur: --year/--template/--flavour have no effect on `%s`; refusing rather than ignoring them\n"
      cmd;
    exit 2
  end

(* Sibling to [reject_table_flags_for], narrower: `day`/`readings`/`rubrics`
   (Fix 3, cli-flags-report) now accept [--year] as an alternative to their
   own positional year, so only [--template]/[--flavour] -- meaningful
   solely on `table`/`render` -- are refused on them. *)
let reject_template_flavour_for cmd ~template ~flavour =
  if template <> None || flavour <> None then begin
    Printf.eprintf "colitur: --template/--flavour have no effect on `%s`; refusing rather than ignoring them\n"
      cmd;
    exit 2
  end

(* Sibling to [reject_emit_flags_for]/[reject_table_flags_for]: `--format`
   has no meaning on `publish` (it always writes all four whole-year
   formats plus the per-day JSON tree, never a single chosen one), so
   accepting and silently dropping it would be the same failure mode this
   project already refuses everywhere else. Narrower than
   [reject_emit_flags_for] on purpose -- `publish` legitimately takes
   --from/--to/--dtstamp, so that blanket check cannot be reused here. *)
let reject_format_for cmd format =
  if format <> None then begin
    Printf.eprintf "colitur: --format has no effect on `%s`; refusing rather than ignoring it\n" cmd;
    exit 2
  end

(* Sibling to the three rejectors above: `--out`/`--prune` (Task 12) have no
   meaning on any command except `publish`. *)
let reject_publish_flags_for cmd ~out ~prune =
  if out <> None || prune then begin
    Printf.eprintf "colitur: --out/--prune have no effect on `%s`; refusing rather than ignoring them\n" cmd;
    exit 2
  end

(* Sibling to the four rejectors above: `--lang`/`--raw` (Task 6) have
   meaning only on the commands that resolve display names --
   `day`/`readings`/`emit`/`table`/`render`/`publish` -- and not on
   `easter`/`temporal` (read no sanctoral data, exactly like `--overlay`),
   `check`/`convert`/`new-overlay` (operate on overlay files, not a
   rendered calendar), or `lang`/`config` themselves (which take their OWN
   flags, `--dump`/`--check`/`--list`/`--show`, disjoint from these). *)
(* Sibling to [reject_lang_for] and the rest: --pretty is terminal
   presentation for the four commands that print one row per day. `emit`,
   `table`/`render` and `publish` already choose their own shape through
   --format and --template, so prettifying them would compete with the
   template engine rather than complement it; `easter` prints six key/value
   lines, not a day grid. Accepting the flag there and quietly doing nothing
   is the failure mode this program refuses everywhere else. *)
let reject_pretty_for cmd ~pretty =
  if pretty then begin
    Printf.eprintf
      "colitur: --pretty has no effect on `%s`; refusing rather than ignoring it\n" cmd;
    exit 2
  end

let reject_lang_for cmd ~lang ~raw =
  if lang <> None || raw then begin
    Printf.eprintf "colitur: --lang/--raw have no effect on `%s`; refusing rather than ignoring them\n" cmd;
    exit 2
  end

(* Sibling again: `--dump`/`--check`/`--list`/`--show` (Task 7) belong only
   to `colitur lang` and `colitur config` respectively. *)
let reject_lang_subcommand_flags_for cmd ~dump ~check ~list ~show =
  if dump <> None || check <> None || list || show then begin
    Printf.eprintf
      "colitur: --dump/--check/--list/--show have no effect on `%s`; refusing rather than ignoring them\n"
      cmd;
    exit 2
  end

(* Sibling again: `--sigla-style`/`--sigla-book`/`--sigla-tradition` (Task 8
   plumbing, Task 9 wiring) actually render a citation on every command
   that emits one -- `readings`, `table`/`render`, `emit`, `publish`, each
   of which builds its own [Sigla.t] via [load_sigla] rather than calling
   this rejector. Every OTHER command -- `day` included, which prints no
   `first`/`gospel` field of its own -- still refuses the three flags
   rather than silently accepting and ignoring them, the same discipline
   every rejector above keeps; `config --show` is the one place that
   previews their resolution without rendering anything. *)
let reject_sigla_for cmd ~sigla_style ~sigla_book ~sigla_tradition =
  if sigla_style <> None || sigla_book <> None || sigla_tradition <> None then begin
    Printf.eprintf
      "colitur: --sigla-style/--sigla-book/--sigla-tradition have no effect on `%s`; refusing rather \
       than ignoring them\n"
      cmd;
    exit 2
  end

(* `colitur check FILE...` -- load a user overlay, apply it to the real
   shipped calendar, and say what it did, without printing a year of output.

   The gap this closes: an overlay is APPLIED, NOT VALIDATED (the man page says
   so, and it remains true -- the five test layers assert things about the
   SHIPPED calendar and cannot vouch for a user's file). Before this, the only
   way to find out whether your file did what you meant was to generate a whole
   year and grep for your own slug, and the only way to learn that a directive
   matched nothing was to notice a warning scroll past among 365 lines.

   This does not validate a calendar against the rubrics -- it cannot, and
   claiming otherwise would be the overclaim this project avoids elsewhere. It
   answers three narrower questions: does the file parse, does every directive
   find its target, and what does the merged result contain. *)
let check_report paths =
  let ok = ref true in
  List.iter
    (fun path ->
      match Colitur_kernel.Overlay.load Rite_ef.Vocab_ef.rank_of_sexp path with
      | Error e ->
          Printf.printf "%s: FAILED TO LOAD\n  %s\n" path e;
          ok := false
      | Ok o ->
          let n_add, n_sup, n_rep, n_edit =
            List.fold_left
              (fun (a, s, r, e) -> function
                | Colitur_kernel.Overlay.Add _ -> (a + 1, s, r, e)
                | Colitur_kernel.Overlay.Suppress _ -> (a, s + 1, r, e)
                | Colitur_kernel.Overlay.Replace _ -> (a, s, r + 1, e)
                | Colitur_kernel.Overlay.Edit _ -> (a, s, r, e + 1))
              (0, 0, 0, 0) o.Colitur_kernel.Overlay.directives
          in
          Printf.printf "%s: ok -- overlay %s, %d directive(s): %d add, %d suppress, %d replace, %d edit\n"
            path o.Colitur_kernel.Overlay.id
            (List.length o.Colitur_kernel.Overlay.directives) n_add n_sup n_rep n_edit;
          (* Apply it to the REAL shipped calendar, so "matched nothing" is
             judged against the data the user will actually run against, not
             against an empty layer where every Suppress would trivially fail. *)
          (match load_ef_layer ~user_overlays:[ path ] () with
           | Error e ->
               Printf.printf "  applying to the shipped calendar failed: %s\n" e;
               ok := false
           | Ok (_, diagnostics) ->
               let mine =
                 List.filter
                   (fun (d : Colitur_kernel.Overlay.diagnostic) ->
                     String.equal d.Colitur_kernel.Overlay.overlay o.Colitur_kernel.Overlay.id)
                   diagnostics
               in
               if mine = [] then print_endline "  every directive found its target"
               else begin
                 ok := false;
                 List.iter
                   (fun d ->
                     Printf.printf "  MATCHED NOTHING: %s\n"
                       (Colitur_kernel.Overlay.diagnostic_to_string d))
                   mine
               end);
          List.iter
            (function
              | Colitur_kernel.Overlay.Add e ->
                  Printf.printf "  add      %s\n"
                    (Colitur_kernel.Slug.to_string
                       e.Colitur_kernel.Layer.cel.Colitur_kernel.Celebration.slug)
              | Colitur_kernel.Overlay.Suppress s ->
                  Printf.printf "  suppress %s\n" (Colitur_kernel.Slug.to_string s)
              | Colitur_kernel.Overlay.Replace (s, _) ->
                  Printf.printf "  replace  %s\n" (Colitur_kernel.Slug.to_string s)
              | Colitur_kernel.Overlay.Edit (s, _) ->
                  Printf.printf "  edit     %s\n" (Colitur_kernel.Slug.to_string s))
            o.Colitur_kernel.Overlay.directives)
    paths;
  exit (if !ok then 0 else 2)

(* `colitur convert FILE.ini` -- the flat INI form to the S-expression one,
   on stdout for redirection.

   A separate step rather than teaching --overlay to sniff the extension, and
   deliberately so: the user gets to SEE what their INI became. When a date
   form was mistyped or an edit silently dropped, "what did the engine
   actually get" is the question, and an invisible transpile cannot answer it.

   {!Overlay_ini.convert} verifies its own output before returning it -- see
   that function's own comment. Nothing is written if the round trip fails. *)
let convert_report path =
  match
    (try Ok (In_channel.with_open_text path In_channel.input_all)
     with Sys_error e -> Error e)
  with
  | Error e ->
      Printf.eprintf "colitur: %s\n" e;
      exit 2
  | Ok text -> (
      match
        Colitur_kernel.Overlay_ini.convert ~rank_of_string:Rite_ef.Vocab_ef.rank_of_string
          ~rank_to_sexp:Rite_ef.Vocab_ef.sexp_of_rank ~rank_of_sexp:Rite_ef.Vocab_ef.rank_of_sexp text
      with
      | Error e ->
          Printf.eprintf "colitur: %s: %s\n" path e;
          exit 2
      | Ok sexp ->
          print_string sexp;
          exit 0)

(* `colitur lang --list` -- what language files this build can find, from
   [lang_dir ()], the same probe [load_lang] itself uses. Each is opened and
   parsed (not merely listed by filename) so a malformed file is flagged
   here rather than only failing later when someone actually tries to use
   it.

   [traditions.ini] lives in the same directory but is not a language file
   -- it answers which book a reference DENOTES, not what it is CALLED (see
   [load_tradition] above) -- and does not even parse as one ([Lang.of_string]
   requires its own [\[meta\]] section, which traditions.ini has no reason to
   carry). Without this exclusion it would list here as "(unreadable: ...)",
   which is not a defect in the file, only a mismatch between what this scan
   assumes every [.ini] in the directory is and what is actually shipped
   there now. *)
let lang_list () =
  let dir = lang_dir () in
  match Sys.readdir dir with
  | exception Sys_error _ ->
      Printf.eprintf "colitur: no language directory at %s\n" dir;
      exit 2
  | files ->
      Array.sort compare files;
      Array.iter
        (fun f ->
          if Filename.check_suffix f ".ini" && f <> "traditions.ini" then begin
            let code = Filename.remove_extension f in
            match read_file (Filename.concat dir f) with
            | Ok t -> (
                match Colitur_naming.Lang.of_string t with
                | Ok l ->
                    Printf.printf "%-6s %s\n" code
                      (match Colitur_naming.Lang.fallback_code l with
                       | Some fb -> "(falls back to " ^ fb ^ ")"
                       | None -> "")
                | Error e -> Printf.printf "%-6s (unreadable: %s)\n" code e)
            | Error e -> Printf.printf "%-6s (unreadable: %s)\n" code e
          end)
        files

(* Every slug the engine can actually emit -- the observed office AND every
   commemoration/transfer, exactly the four-field walk
   test/test_lang_coverage.ml's own [slugs_of_day] performs -- over the same
   2020-2045 window that test measures against. This is [colitur lang
   --check]'s own reference set: a language file is judged against what the
   engine can really produce, not against an arbitrarily chosen sample. *)
let all_known_slugs () =
  match load_ef_data () with
  | Error msg ->
      Printf.eprintf "colitur: %s\n" msg;
      exit 2
  | Ok (layer, lectionary, commons) ->
      let context = Rite_ef.context ~lectionary ~commons in
      let slug (c : _ Colitur_kernel.Celebration.t) =
        Colitur_kernel.Slug.to_string c.Colitur_kernel.Celebration.slug
      in
      let slugs_of_day
          (d : (Rite_ef.Vocab_ef.season, Rite_ef.Vocab_ef.rank) Colitur_kernel.Liturgical_day.t) =
        slug d.Colitur_kernel.Liturgical_day.observed
        :: List.map (fun (c, _priv) -> slug c) d.Colitur_kernel.Liturgical_day.commemorations
        @ (match d.Colitur_kernel.Liturgical_day.transferred_in with
           | None -> []
           | Some c -> [ slug c ])
        @ List.map (fun (c, _date) -> slug c) d.Colitur_kernel.Liturgical_day.transferred_out
      in
      let seen = Hashtbl.create 1024 in
      for y = 2020 to 2045 do
        Array.iter
          (fun d -> List.iter (fun s -> Hashtbl.replace seen s ()) (slugs_of_day d))
          (Colitur_kernel.Calendar.year context layer y)
      done;
      Hashtbl.fold (fun k () acc -> k :: acc) seen [] |> List.sort compare

(* `colitur lang --dump CODE` -- the named language's full key set, in INI
   form, on stdout for redirection. [Lang.keys] already returns every
   (section-qualified key, value) pair SORTED as one flat list (lang.mli):
   because every key sharing a section also shares that section's own
   string prefix, and no two section names are a prefix of one another, the
   sort keeps every section's own keys contiguous -- so a single pass
   emitting a fresh `[section]` header each time the prefix changes
   reconstructs proper INI blocks, in a FIXED (alphabetical) order, with no
   second grouping step. Two dumps of the same table are therefore
   byte-identical, which is what makes `--dump` diffable across two
   versions of a translation. *)
let lang_dump code =
  let path = Filename.concat (lang_dir ()) (code ^ ".ini") in
  match read_file path with
  | Error _ ->
      Printf.eprintf "colitur: no language %S (looked in %s); try: colitur lang --list\n" code
        (lang_dir ());
      exit 2
  | Ok text -> (
      match Colitur_naming.Lang.of_string text with
      | Error msg ->
          Printf.eprintf "colitur: %s: %s\n" path msg;
          exit 2
      | Ok t ->
          Printf.printf "[meta]\nlang = %s\n" (Colitur_naming.Lang.code t);
          (match Colitur_naming.Lang.fallback_code t with
           | Some fb -> Printf.printf "fallback = %s\n" fb
           | None -> ());
          let cur = ref "" in
          List.iter
            (fun (qk, v) ->
              match String.index_opt qk '.' with
              | None -> ()
              | Some i ->
                  let section = String.sub qk 0 i in
                  let key = String.sub qk (i + 1) (String.length qk - i - 1) in
                  if section <> !cur then begin
                    print_newline ();
                    Printf.printf "[%s]\n" section;
                    cur := section
                  end;
                  Printf.printf "%s = %s\n" key v)
            (Colitur_naming.Lang.keys t))

(* `colitur lang --check FILE` -- the difference between "you may write a
   language file" and "you can": without this, a translator has to
   reverse-engineer the key set from source. Reports what is MISSING
   (a real slug the file has no entry for) AND what is UNKNOWN (a
   [celebration] key matching no real slug at all -- a typo, or a slug from
   a version of colitur this file was not written against) -- a key
   matching nothing is silently dead, and its author would otherwise never
   learn why their translation does not appear. Exits 2 only on UNKNOWN: a
   partial file (some slugs missing) is exactly the shippable, in-progress
   state [Lang.with_fallback] exists for, but a typo naming nothing is
   always worth flagging as a failure, the same "never silently dead"
   standard [Config.unknown_keys] holds a config file to. *)
let lang_check path =
  match read_file path with
  | Error msg ->
      Printf.eprintf "colitur: %s\n" msg;
      exit 2
  | Ok text -> (
      match Colitur_naming.Lang.of_string text with
      | Error msg ->
          Printf.eprintf "colitur: %s: %s\n" path msg;
          exit 2
      | Ok t ->
          let known = all_known_slugs () in
          let have =
            List.filter_map
              (fun (k, _) ->
                match String.index_opt k '.' with
                | Some i when String.sub k 0 i = "celebration" ->
                    Some (String.sub k (i + 1) (String.length k - i - 1))
                | _ -> None)
              (Colitur_naming.Lang.keys t)
          in
          let missing = List.filter (fun s -> not (List.mem s have)) known in
          let unknown = List.filter (fun s -> not (List.mem s known)) have in
          (* Book names are checked the same way, and separately. Without
             this the reference set gained a [bible] half that nothing ever
             consulted: a file with [bible] entirely absent reported a clean
             bill of health while every citation silently fell back to the
             data's own Latin spelling. A miss is the TOTAL-lookup contract's
             own signature -- [Lang.bible] returns the KEY when there is no
             entry -- so equality with the key IS the test. *)
          let missing_books =
            List.concat_map
              (fun id ->
                let n = Colitur_citation.Book.to_string id in
                List.filter_map
                  (fun form ->
                    let key = n ^ "." ^ form in
                    if Colitur_naming.Lang.bible t key = key then Some key
                    else None)
                  [ "full"; "abbr" ])
              Colitur_citation.Book.all
          in
          List.iter (fun s -> Printf.printf "missing: %s\n" s) (List.sort compare missing);
          List.iter (fun s -> Printf.printf "missing book: %s\n" s)
            (List.sort compare missing_books);
          List.iter (fun s -> Printf.printf "unknown slug: %s\n" s) (List.sort compare unknown);
          let books_total = 2 * List.length Colitur_citation.Book.all in
          Printf.printf "%s: %d of %d celebrations named, %d missing, %d unknown\n" path
            (List.length known - List.length missing)
            (List.length known) (List.length missing) (List.length unknown);
          Printf.printf "%s: %d of %d book names, %d missing\n" path
            (books_total - List.length missing_books) books_total
            (List.length missing_books);
          if unknown <> [] then exit 1)

(* `colitur config --show` -- each effective setting, its resolved value,
   and where it came from (`flag`/`config`/`default`), via
   [Config.resolve]. There is deliberately no separate "provenance"
   function: [resolve] already returns the source alongside the value
   (config.mli), and a second entry point recomputing it independently
   would let the two disagree. [lang]/[template]/[format] are scalars, each
   resolved the same way `colitur day`/`table`/`emit` would resolve them
   given these SAME command-line flags (so `config --show --lang fr` shows
   exactly what a real `--lang fr` run would use); [overlay] is a list, so
   it has no single "value" to resolve -- shown as one line per effective
   entry instead, with its own source.

   [sigla_style]/[sigla_book]/[sigla_tradition] (Task 8) join the same
   scalar rows, resolved through the identical [Config.resolve]. Two are
   NOT arbitrary strings, though, so "report" also means "validate", the
   same way an unknown [--lang] is an error rather than a silent Latin
   fallback:
   - [sigla_book] is a closed two-value setting ([full]/[abbr]) --
     [Colitur_citation.Render.with_book] takes a variant, not a string, so
     an unrecognised value could never mean anything downstream. Checked
     HERE too, not only inside [load_sigla]'s own real renderer (Task 9) --
     this preview must reject exactly what a real render would.
   - [sigla_tradition] names a section of [lang/traditions.ini]; resolving
     it for real (via [load_tradition], the same reader [load_sigla] below
     uses) rather than only printing the string means a typo is caught
     right here too -- though, unlike [sigla_book], [load_tradition] is
     BY DESIGN never fatal (see its own comment: asking for a renumbering
     is optional, unlike asking for a language), so an unknown tradition
     degrades to a stderr warning and the Vulgate, exactly as it does on a
     real render, not a [config --show] failure.
   [sigla_style] gets no such check: like [lang] itself, it is an open
   language code or path, not a closed set, and [config --show] does not
   validate [lang] either (that only happens when a command actually loads
   it via [load_lang]). *)
let config_show ~lang_flag ~template_flag ~format_flag ~flavour_flag ~overlays_flag ~sigla_style_flag
    ~sigla_book_flag ~sigla_tradition_flag config =
  (* VALIDATE BEFORE PRINTING ANYTHING. A usage error used to surface
     halfway down the table, so `config --show --sigla-book bogus` exited 2
     having already written five rows to stdout -- a caller redirecting
     stdout to a file got a truncated, plausible-looking report alongside a
     non-zero status. Nothing is emitted now until every value is known good. *)
  let sigla_book_check, _ =
    Colitur_naming.Config.resolve ~flag:sigla_book_flag
      ~config:(Colitur_naming.Config.sigla_book config) ~default:"abbr"
  in
  if sigla_book_check <> "full" && sigla_book_check <> "abbr" then begin
    Printf.eprintf "colitur: unknown --sigla-book %S (want \"full\" or \"abbr\")\n"
      sigla_book_check;
    exit 2
  end;
  let cpath = config_path () in
  Printf.printf "config file: %s (%s)\n" cpath
    (if cpath <> "" && Sys.file_exists cpath then "exists" else "not found");
  let scalar name flag cfgval default =
    let v, src = Colitur_naming.Config.resolve ~flag ~config:cfgval ~default in
    Printf.printf "%-16s %-24s (%s)\n" name v src;
    v
  in
  let lang_value = scalar "lang" lang_flag (Colitur_naming.Config.lang config) "la" in
  let _ = scalar "template" template_flag (Colitur_naming.Config.template config) "(none)" in
  let _ = scalar "format" format_flag (Colitur_naming.Config.format config) "(none)" in
  (* "(infer)" rather than "(none)": an unset flavour is not an absence, it
     means the flavour comes from the template's own extension. *)
  let _ = scalar "flavour" flavour_flag (Colitur_naming.Config.flavour config) "(infer)" in
  (* Default is the resolved LANGUAGE, not a literal "la": a booklet that
     asked for --lang fr and named no --sigla-style of its own gets French
     citations too, not a silent switch back to Latin punctuation. *)
  let _ = scalar "sigla_style" sigla_style_flag (Colitur_naming.Config.sigla_style config) lang_value in
  let sigla_book_value, sigla_book_src =
    Colitur_naming.Config.resolve ~flag:sigla_book_flag ~config:(Colitur_naming.Config.sigla_book config)
      ~default:"abbr"
  in
  if sigla_book_value <> "full" && sigla_book_value <> "abbr" then begin
    Printf.eprintf "colitur: unknown --sigla-book %S (want \"full\" or \"abbr\")\n" sigla_book_value;
    exit 2
  end;
  Printf.printf "%-16s %-24s (%s)\n" "sigla_book" sigla_book_value sigla_book_src;
  let sigla_tradition_value, sigla_tradition_src =
    Colitur_naming.Config.resolve ~flag:sigla_tradition_flag
      ~config:(Colitur_naming.Config.sigla_tradition config) ~default:"vulgate"
  in
  let _ = load_tradition sigla_tradition_value in
  Printf.printf "%-16s %-24s (%s)\n" "sigla_tradition" sigla_tradition_value sigla_tradition_src;
  (match overlays_flag with
   | _ :: _ as l -> List.iter (fun o -> Printf.printf "%-16s %-24s (%s)\n" "overlay" o "flag") l
   | [] -> (
       match Colitur_naming.Config.overlays config with
       | [] -> Printf.printf "%-16s %-24s (%s)\n" "overlay" "(none)" "default"
       | l -> List.iter (fun o -> Printf.printf "%-16s %-24s (%s)\n" "overlay" o "config") l))

(* `colitur new-overlay` -- a starter file on stdout, for redirection.
   Deliberately printed rather than written: the user picks the path, and a
   command that creates files where it likes is a worse citizen. Every value is
   a placeholder that WILL show up in output if left unedited, so a
   half-finished overlay is visible rather than silently inert. *)
let new_overlay_template =
  {template|; A colitur overlay: a local calendar applied ON TOP of the universal 1962
; one, never instead of it. Save this, edit it, then:
;
;   colitur check   my-parish.sexp        -- does it parse, does it apply
;   colitur day 2026 --overlay my-parish.sexp
;
; Directives are Add, Suppress, Replace and Edit, applied in the order written.
; Last writer wins, so a later file may override an earlier one -- or a
; universal entry -- by naming its slug.
((id my-parish)
  (directives
    ; A fixed-date local feast, with its own Mass readings.
    ;
    ; NOTE WHERE `citations` AND `layer` GO: inside `cel`, beside `rank` and
    ; `colour` -- NOT beside `date`. Both may be omitted, defaulting to no
    ; readings and to this overlay's own id. This example shows them in
    ; place because the nesting is the single easiest thing to get wrong,
    ; and getting it wrong is what `unknown field(s): citations` means.
    ((Add
       ((date (Fixed (month 5) (day 20)))
         (cel
           ((slug my-local-patron)
             (names ((la "Sancti Patroni Nostri") (en "Our Local Patron")))
             ; rank:   Class1 | Class2 | Class3 | Class4
             ; status: Feast | Commemoration_only
             ; colour: White | Red | Violet | Green | Black | Rose
             ; subject: Lord | Bvm | Saint | Temporal
             (rank Class3) (status Feast) (colour White) (subject Saint)
             ; part: First | Gospel. The reference is a citation, never
             ; scripture text -- colitur ships no Bible.
             (citations
               (((part First) (reference "Wis 7:7-14"))
                 ((part Gospel) (reference "Matt 5:13-19"))))
             (layer my-parish)))))
     ; A MOVABLE feast: the first Sunday of October. `nth` may be negative to
     ; count from the end of the month (-1 is the last).
     (Add
       ((date (Nth_weekday (month 10) (nth 1) (weekday Sun)))
         (cel
           ((slug my-dedication)
             (names ((en "Dedication of Our Church")))
             ; A church's own dedication anniversary is I class IN THAT CHURCH
             ; (RG 91 entry 4). At III class it would lose to the Sunday it
             ; lands on every year.
             (rank Class1) (status Feast) (colour White) (subject Saint)))))
     ; A feast reckoned from Easter: Easter_offset counts days, signed.
     ; (Easter itself is 0; Ash Wednesday is -46; Corpus Christi is +60.)
     ; (Add
     ;   ((date (Easter_offset 60))
     ;     (cel ((slug my-easter-relative) (names ((en "Example")))
     ;           (rank Class3) (status Feast) (colour White) (subject Saint)))))
     ;
     ; Remove a universal entry your calendar does not keep:
     ; (Suppress some-universal-slug)
     ;
     ; Keep the entry but change one field:
     ; (Edit some-universal-slug ((Set_colour Red)))
     )))
|template}

let () =
  match parse_args (List.tl (Array.to_list Sys.argv)) with
  | Error msg ->
      Printf.eprintf "colitur: %s\n" msg;
      usage ()
  | Ok { overlays; rite; format; from_y; to_y; dtstamp; year; template; flavour; out; prune; lang;
         raw; pretty; dump; check; list; show; sigla_style; sigla_book; sigla_tradition;
         positional } -> (
      let reject_emit = reject_emit_flags_for ~format ~from_y ~to_y ~dtstamp in
      let reject_rite cmd = reject_rite_for cmd rite in
      let reject_table = reject_table_flags_for ~year ~template ~flavour in
      let reject_template_flavour cmd = reject_template_flavour_for cmd ~template ~flavour in
      let reject_publish = reject_publish_flags_for ~out ~prune in
      let reject_lang = reject_lang_for ~lang ~raw in
      let reject_pretty = reject_pretty_for ~pretty in
      let reject_lang_sub = reject_lang_subcommand_flags_for ~dump ~check ~list ~show in
      let reject_sigla = reject_sigla_for ~sigla_style ~sigla_book ~sigla_tradition in
      (* Loaded once, unconditionally: a config file the user wrote and
         colitur cannot honour (missing HOME aside, [load_config] treats
         that as "no config" rather than an error) is worth surfacing on
         EVERY invocation, `--help` included, not only the commands that
         happen to consult it -- the same "never silently ignored"
         discipline [COLITUR_DATA_DIR] already gets. *)
      let config = load_config () in
      (* Resolved only inside the branches that actually consume it, as a
         thunk rather than eagerly here: [load_lang] can [exit 2] (an
         unknown language, a malformed file), and a command that never asked
         for naming at all (`easter`, `check`, ...) must not be able to fail
         on account of a language it never uses -- those commands reject
         [--lang]/[--raw] outright instead, via [reject_lang] above. *)
      let resolved_lang () = load_lang ~raw ~flag:lang ~config:(Colitur_naming.Config.lang config) in
      (* Fix 2 (cli-flags-report, 2026-08-27; corrected against the EF
         byte-identity constraint, same date): `rubrics` gained
         --lang/--raw, but MUST NOT change `colitur rubrics <year>`'s own
         no-flag output -- that exact invocation is one of the five this
         task's own brief holds to byte-identical output against a
         pre-branch build, and `rubrics` never resolved a language at all
         before this feature existed, so ANY non-identity default would
         break it. [resolved_lang]'s own default ("la", [load_lang]'s
         third-priority fallback, shared by every OTHER naming-bearing
         command) is therefore NOT reused here: [rubrics_lang] resolves
         through the ordinary flag/config chain only when [--lang] or
         [--raw] was ACTUALLY given on this invocation; with neither, it
         is [Lang.raw] outright, regardless of any `lang = ...` a config
         file sets for every other command. This is a deliberate,
         documented exception to "flag > config > default" -- config-level
         naming is a standing preference for commands that HAD naming
         before rubrics did; a user who never asked `rubrics` for a name at
         all keeps getting exactly what they always got. *)
      let rubrics_lang () =
        if raw || lang <> None then load_lang ~raw ~flag:lang ~config:(Colitur_naming.Config.lang config)
        else Colitur_naming.Lang.raw
      in
      (* Config supplies a DEFAULT overlay list only when NO --overlay was
         given at all -- not merged with a partial CLI list -- so the
         precedence stays exactly flag > config > default, the same
         direction every other setting resolves in, rather than a list
         merge whose ordering nothing documents. *)
      let effective_overlays =
        if overlays = [] then Colitur_naming.Config.overlays config else overlays
      in
      match positional with
      | [ ("-h" | "--help" | "help") ] ->
          reject_overlays_for "--help" overlays;
          reject_rite "--help";
          reject_emit "--help";
          reject_table "--help";
          reject_publish "--help";
          reject_lang "--help";
          reject_lang_sub "--help";
          reject_sigla "--help";
          print_help ()
      | [ ("-V" | "--version" | "version") ] ->
          reject_overlays_for "--version" overlays;
          reject_rite "--version";
          reject_emit "--version";
          reject_table "--version";
          reject_publish "--version";
          reject_lang "--version";
          reject_lang_sub "--version";
          reject_sigla "--version";
          print_endline version;
          exit 0
      | [ "easter"; ys ] ->
          reject_overlays_for "easter" overlays;
          reject_rite "easter";
          reject_emit "easter";
          reject_table "easter";
          reject_publish "easter";
          reject_lang "easter";
          reject_lang_sub "easter";
          reject_pretty "easter";
          reject_sigla "easter";
          with_year ys easter_report
      | [ "temporal"; ys ] ->
          reject_overlays_for "temporal" overlays;
          reject_emit "temporal";
          reject_table "temporal";
          reject_publish "temporal";
          reject_lang "temporal";
          reject_lang_sub "temporal";
          reject_sigla "temporal";
          with_year ys (temporal_report ~rite:(resolve_rite rite) ~pretty)
      | "check" :: (_ :: _ as files) ->
          reject_overlays_for "check" overlays;
          reject_rite "check";
          reject_emit "check";
          reject_table "check";
          reject_publish "check";
          reject_lang "check";
          reject_lang_sub "check";
          reject_pretty "check";
          reject_sigla "check";
          check_report files
      | [ "convert"; path ] ->
          reject_overlays_for "convert" overlays;
          reject_rite "convert";
          reject_emit "convert";
          reject_table "convert";
          reject_publish "convert";
          reject_lang "convert";
          reject_lang_sub "convert";
          reject_pretty "convert";
          reject_sigla "convert";
          convert_report path
      | [ "new-overlay" ] ->
          reject_overlays_for "new-overlay" overlays;
          reject_rite "new-overlay";
          reject_emit "new-overlay";
          reject_table "new-overlay";
          reject_publish "new-overlay";
          reject_lang "new-overlay";
          reject_lang_sub "new-overlay";
          reject_pretty "new-overlay";
          reject_sigla "new-overlay";
          print_string new_overlay_template;
          exit 0
      | [ "lang" ] -> (
          reject_overlays_for "lang" overlays;
          reject_rite "lang";
          reject_emit "lang";
          reject_table "lang";
          reject_publish "lang";
          reject_lang "lang";
          reject_sigla "lang";
          if show then begin
            Printf.eprintf "colitur: --show has no effect on `lang`; refusing rather than ignoring it\n";
            exit 2
          end;
          match (list, dump, check) with
          | true, None, None -> lang_list ()
          | false, Some code, None -> lang_dump code
          | false, None, Some path -> lang_check path
          | false, None, None ->
              Printf.eprintf "colitur: lang requires one of --list, --dump CODE or --check FILE\n";
              exit 2
          | _ ->
              Printf.eprintf "colitur: lang takes only one of --list, --dump CODE or --check FILE\n";
              exit 2)
      | [ "config" ] ->
          (* Unlike every other subcommand's own rejector, `config --show`
             deliberately ACCEPTS --lang/--template/--format/--overlay: they
             are the very settings it previews the resolution of (so
             `config --show --lang fr` reports exactly what a real `--lang
             fr` run on any other command would resolve to), so none of
             [reject_lang]/[reject_overlays_for]/the format half of
             [reject_emit] apply here. Everything with no meaning for a
             config preview is still refused, not silently ignored. *)
          reject_table "config";
          reject_publish "config";
          reject_rite "config";
          if from_y <> None || to_y <> None || dtstamp <> None then begin
            Printf.eprintf
              "colitur: --from/--to/--dtstamp have no effect on `config`; refusing rather than ignoring them\n";
            exit 2
          end;
          if raw then begin
            Printf.eprintf "colitur: --raw has no effect on `config`; refusing rather than ignoring it\n";
            exit 2
          end;
          if dump <> None || check <> None || list then begin
            Printf.eprintf
              "colitur: --dump/--check/--list have no effect on `config`; refusing rather than ignoring them\n";
            exit 2
          end;
          if not show then begin
            Printf.eprintf "colitur: config requires --show\n";
            exit 2
          end;
          config_show ~lang_flag:lang ~template_flag:template ~format_flag:format
            ~flavour_flag:flavour ~overlays_flag:overlays
            ~sigla_style_flag:sigla_style ~sigla_book_flag:sigla_book ~sigla_tradition_flag:sigla_tradition
            config
      (* Fix 3 (cli-flags-report, 2026-08-27): `day`/`readings`/`rubrics`
         each match "cmd :: rest" with [rest] a positional year (as
         before) or empty (a bare command word, [--year] carrying the
         year instead) -- [List.length rest <= 1] keeps a genuine extra
         argument (`colitur day 2026 extra`) falling through to [usage ()]
         exactly as it always has. [resolve_single_year] then reconciles
         that against [--year], accepting either, agreeing, and refusing
         disagreement -- see its own citation above. *)
      | "day" :: rest when List.length rest <= 1 ->
          reject_emit "day";
          reject_template_flavour "day";
          reject_publish "day";
          reject_lang_sub "day";
          reject_sigla "day";
          let ys =
            resolve_single_year "day"
              ~positional:(match rest with [ ys ] -> Some ys | _ -> None)
              ~flag:year
          in
          (match resolve_rite rite with
          | `Ef -> with_year ys (day_report ~lang:(resolved_lang ()) ~pretty ~overlays:effective_overlays)
          | `Of -> with_year ys (day_report_of ~lang:(resolved_lang ()) ~pretty ~overlays:effective_overlays))
      | "readings" :: rest when List.length rest <= 1 ->
          reject_emit "readings";
          reject_template_flavour "readings";
          reject_publish "readings";
          reject_lang_sub "readings";
          let ys =
            resolve_single_year "readings"
              ~positional:(match rest with [ ys ] -> Some ys | _ -> None)
              ~flag:year
          in
          let lang_t = resolved_lang () in
          let sigla =
            load_sigla ~raw ~lang_t ~sigla_style_flag:sigla_style ~sigla_book_flag:sigla_book
              ~sigla_tradition_flag:sigla_tradition ~config
          in
          (match resolve_rite rite with
          | `Ef -> with_year ys (readings_report ~lang:lang_t ~sigla ~pretty ~overlays:effective_overlays)
          | `Of -> with_year ys (readings_report_of ~lang:lang_t ~sigla ~pretty ~overlays:effective_overlays))
      | "rubrics" :: rest when List.length rest <= 1 ->
          (* --overlay accepted, same reasoning as `readings`: an overlay can
             change which celebration is observed, hence which Mass formulary
             is said. Fix 2 (cli-flags-report, 2026-08-27): --lang/--raw are
             now ALSO accepted -- [said] (rubrics_line's own formulary-slug
             column) is a machine key exactly like [day_line]'s own [slug_s],
             and there turned out to be no principled reason for this row
             alone to refuse translating it (see [rubrics_name]'s own
             citation). --sigla-* stay refused: this row still prints no
             citation for them to act on. Naming resolves through
             [rubrics_lang], NOT the shared [resolved_lang] every other
             naming-bearing command uses -- see that function's own
             citation for why (the EF byte-identity constraint on this
             exact no-flag invocation). *)
          reject_emit "rubrics";
          reject_template_flavour "rubrics";
          reject_publish "rubrics";
          (* --lang/--raw refused, and PRINCIPLED rather than an oversight.
             This row is a date, a slug, a source keyword, two booleans and a
             preface key -- not one field is display text, so there is nothing
             to translate and nothing to strip. An earlier pass added a name
             column so --lang WOULD have something to act on; that changed the
             default output from six tab-separated fields to seven, breaking
             every existing consumer and the byte-identical-EF rule with it.
             Documenting the asymmetry is the cheaper correct answer.
             Contrast `day`/`readings`, which carry a name and take both. *)
          reject_lang "rubrics";
          reject_lang_sub "rubrics";
          reject_sigla "rubrics";
          let ys =
            resolve_single_year "rubrics"
              ~positional:(match rest with [ ys ] -> Some ys | _ -> None)
              ~flag:year
          in
          with_year ys (rubrics_report ~rite:(resolve_rite rite) ~lang:(rubrics_lang ()) ~pretty ~overlays:effective_overlays)
      | [ "emit" ] -> (
          reject_table "emit";
          reject_publish "emit";
          reject_lang_sub "emit";
          reject_pretty "emit";
          match (match format with Some f -> Some f | None -> Colitur_naming.Config.format config) with
          | None ->
              Printf.eprintf "colitur: emit requires --format csv|json|sexp|xml|ics\n";
              exit 2
          | Some format -> (
              match (from_y, to_y) with
              | None, _ | _, None ->
                  Printf.eprintf "colitur: emit requires --from YEAR and --to YEAR\n";
                  exit 2
              | Some from_ys, Some to_ys ->
                  let lang_t = resolved_lang () in
                  let sigla =
                    load_sigla ~raw ~lang_t ~sigla_style_flag:sigla_style ~sigla_book_flag:sigla_book
                      ~sigla_tradition_flag:sigla_tradition ~config
                  in
                  let rite = resolve_rite rite in
                  with_year from_ys (fun from_y ->
                      with_year to_ys (fun to_y ->
                          emit_report ~rite ~lang:lang_t ~sigla ~format ~overlays:effective_overlays
                            ~dtstamp ~from_y ~to_y))))
      (* Fix 3, same shape as `day`/`readings`/`rubrics` above: a bare
         [cmd] (year from [--year], as before `table`/`render` accepted
         any year at all) or [cmd; ys] (year positional, NEW). *)
      | (("table" | "render") as cmd) :: rest when List.length rest <= 1 -> (
          reject_emit cmd;
          reject_publish cmd;
          reject_lang_sub cmd;
            reject_pretty cmd;
          let positional_year = match rest with [ ys ] -> Some ys | _ -> None in
          match (match template with Some t -> Some t | None -> Colitur_naming.Config.template config) with
          | None ->
              Printf.eprintf "colitur: %s requires a year (positional or --year) and --template FILE\n" cmd;
              exit 2
          | Some template -> (
              let ys = resolve_single_year cmd ~positional:positional_year ~flag:year in
              let lang_t = resolved_lang () in
              let sigla =
                load_sigla ~raw ~lang_t ~sigla_style_flag:sigla_style ~sigla_book_flag:sigla_book
                  ~sigla_tradition_flag:sigla_tradition ~config
              in
              let rite = resolve_rite rite in
              with_year ys (fun y ->
                  table_report ~rite ~lang:lang_t ~sigla ~template
                    (* flag > config > infer from the template's own
                       extension. None here still means "infer", which is
                       the usual case, so this is an option-or rather than
                       a Config.resolve with a default. *)
                    ~flavour_opt:
                      (match flavour with
                      | Some _ -> flavour
                      | None -> Colitur_naming.Config.flavour config)
                    ~overlays:effective_overlays y)))
      | [ "publish" ] -> (
          reject_table "publish";
          reject_format_for "publish" format;
          reject_lang_sub "publish";
          reject_pretty "publish";
          match out with
          | None ->
              Printf.eprintf "colitur: publish requires --out DIR\n";
              exit 2
          | Some out -> (
              match (from_y, to_y) with
              | None, _ | _, None ->
                  Printf.eprintf "colitur: publish requires --from YEAR and --to YEAR\n";
                  exit 2
              | Some from_ys, Some to_ys ->
                  let lang_t = resolved_lang () in
                  let sigla =
                    load_sigla ~raw ~lang_t ~sigla_style_flag:sigla_style ~sigla_book_flag:sigla_book
                      ~sigla_tradition_flag:sigla_tradition ~config
                  in
                  let rite = resolve_rite rite in
                  with_year from_ys (fun from_y ->
                      with_year to_ys (fun to_y ->
                          (* [publish_report] writes many files across a whole
                             year range ([mkdir_p]/[write_file], both above) --
                             an unwritable [--out] parent (EACCES) or an [--out]
                             that names an existing plain file (ENOTDIR) raises
                             from deep inside that loop, same defect class as
                             the template read this project already guards
                             (commit 6bd741b): "--out" is user input too, and
                             the WHOLE call is guarded here rather than each
                             [write_file] site individually, for the same
                             reason that fix guarded the whole read and not
                             only the open. [Unix.mkdir] raises
                             [Unix.Unix_error] directly; [open_out_bin]
                             (stdlib, not the Unix module) wraps the same
                             underlying errno in [Sys_error] instead -- both
                             are real on this path, so both are caught. *)
                          try
                            publish_report ~rite ~lang:lang_t ~sigla ~from_y ~to_y ~out
                              ~overlays:effective_overlays ~dtstamp ~prune
                          with
                          | Unix.Unix_error (e, fn, arg) ->
                              Printf.eprintf "colitur: %s: %s: %s\n" fn arg (Unix.error_message e);
                              exit 2
                          | Sys_error e ->
                              Printf.eprintf "colitur: %s\n" e;
                              exit 2))))
      | _ -> usage ())