aboutsummaryrefslogtreecommitdiff
path: root/bin/main.ml
blob: 4f1fbf242880cf464deff33054998c45ce8461e1 (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
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))

let temporal_report 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 d = ref jan1 in
  while D.compare !d dec31 <= 0 do
    let t = Rite_ef.Temporal_ef.temporal !d in
    let r =
      Colitur_kernel.Record.of_temporal ~rite:Rite_ef.Temporal_ef.id
        Rite_ef.Vocab_ef.vocab !d t
    in
    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

(* 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
  let load_overlay path =
    match Colitur_kernel.Overlay.load Rite_ef.Vocab_ef.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_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

let day_line (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
  Printf.printf "%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
    (Colitur_kernel.Slug.to_string cel.Colitur_kernel.Celebration.slug)
    (Rite_ef.Vocab_ef.rank_to_string cel.Colitur_kernel.Celebration.rank)
    (Colitur_kernel.Colour.to_string cel.Colitur_kernel.Celebration.colour)
    commemorations

(* 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. *)
let readings_line (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 -> c.Colitur_kernel.Citation.reference
    | None -> "-"
  in
  Printf.printf "%s %s | %s | %s\n"
    (D.to_iso8601 d.Colitur_kernel.Liturgical_day.date)
    (Colitur_kernel.Slug.to_string cel.Colitur_kernel.Celebration.slug)
    (part_ref Colitur_kernel.Citation.First)
    (part_ref Colitur_kernel.Citation.Gospel)

(* 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)

let day_report ~overlays y = resolved_year_report ~line:day_line ~overlays y
let readings_report ~overlays y = resolved_year_report ~line:readings_line ~overlays y

(* 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). *)
let emit_report ~format ~overlays ~dtstamp ~from_y ~to_y =
  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 days = resolved_year_days ~overlays y in
    let v =
      Colitur_render.View.of_days ~vocab:Rite_ef.Vocab_ef.vocab ~rite:"ef" ~year:y days
    in
    match format with
    | "csv" ->
        (* One header for the whole run, not one per year. *)
        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" ->
        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
    | 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. *)

(* 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)))

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. *)
let table_report ~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 latex, groff, html, xml, ics or none)\n"
              name;
            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 latex|groff|html|xml|ics|none\n"
              (extension template);
            exit 2)
  in
  match read_file template with
  | Error msg ->
      Printf.eprintf "colitur: %s\n" msg;
      exit 2
  | Ok src -> (
      let days = resolved_year_days ~overlays y in
      let v = Colitur_render.View.of_days ~vocab:Rite_ef.Vocab_ef.vocab ~rite:"ef" ~year:y days 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 <> "")

(* [--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. *)
let rec prune_empty_dirs ~out dir =
  if dir <> out && String.length dir > String.length out && Sys.file_exists 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. *)
let index_html ~from_y ~to_y =
  let b = Buffer.create 4096 in
  Buffer.add_string b
    "<!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>Liturgical calendar of the 1962 Missale Romanum. Citations only \xe2\x80\x94 never scripture text.</p>\n";
  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=\"ef/%d.ics\">ef/%d.ics</a></li>\n" y 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=\"ef/%d.json\">json</a> <a href=\"ef/%d.csv\">csv</a> \
          <a href=\"ef/%d.xml\">xml</a> \xe2\x80\x94 per-day at <code>ef/%d/MM/DD.json</code></li>\n"
         y y y y 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

let publish_report ~from_y ~to_y ~out ~overlays ~dtstamp ~prune =
  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
  for y = from_y to to_y do
    let days = resolved_year_days ~overlays y in
    let v = Colitur_render.View.of_days ~vocab:Rite_ef.Vocab_ef.vocab ~rite:"ef" ~year:y days in
    let ys = string_of_int y in
    emit ("ef/" ^ ys ^ ".json") (Colitur_render.Emit_json.year v);
    emit ("ef/" ^ ys ^ ".csv") (Colitur_render.Emit_csv.year v);
    emit ("ef/" ^ ys ^ ".xml") (Colitur_render.Emit_xml.year v);
    emit ("ef/" ^ 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 = Colitur_render.View.of_days ~vocab:Rite_ef.Vocab_ef.vocab ~rite:"ef" ~year:y [ d ] in
        emit (Printf.sprintf "ef/%s/%s/%s.json" ys mm dd) (Colitur_render.Emit_json.year one))
      days
  done;
  emit "schema/day-v1.json" schema;
  emit "index.html" (index_html ~from_y ~to_y);
  let now = List.sort compare !written in
  if prune then
    List.iter
      (fun old ->
        if not (List.mem old now) then begin
          let p = Filename.concat out old in
          if Sys.file_exists p then begin
            Sys.remove p;
            prune_empty_dirs ~out (Filename.dirname p)
          end
        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 = "0.7.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>    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 day|readings <year> --overlay FILE [--overlay FILE ...]
  colitur emit --format csv|json|sexp|xml|ics --from Y --to Y
              [--overlay FILE ...] [--dtstamp S]
              render a resolved year range through one of five emitters
  colitur table --year Y --template FILE [--flavour X] [--overlay FILE ...]
  colitur render --template FILE --year Y [--flavour X] [--overlay FILE ...]
              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 [--overlay FILE ...] [--prune]
              [--dtstamp S]
              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 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.

output formats:
  day       date weekday season week slug rank colour [+commemoration ...]
            2026-04-05 sunday paschaltide 1 ef-easter-sunday class-1 white
  readings  date slug | Epistle | Gospel
            2026-12-25 ef-nativity | Heb 1:1-12 | John 1:1-14

  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.

  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.

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`, `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.

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
            scope-shadowing hazard (an inner key silently loses to an outer
            key of the same name -- a bare {{name.la}} inside a day resolves
            to the enclosing MONTH's name, not the day's own).

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

              latex   groff   html   xml   ics   none

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

              .tex              -> latex
              .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 six 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.

              ef/<year>.{json,csv,xml,ics}   one civil year, all days
              ef/<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

            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, and
colitur-templates(5) for the template format in full -- the syntax, the
scope-shadowing hazard, the six flavours' escaping, and the full view-model
field reference.|}

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 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 ()

(* 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 the one plain boolean flag in this whole record -- every other
   field here takes a value, but [--prune] does not, so it cannot reuse the
   `"--flag" :: v :: rest` shape the value-taking flags share below. *)
type parsed_args = {
  overlays : string list;
  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;
  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"
    | "--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
    (* 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 = []; format = None; from_y = None; to_y = None; dtstamp = None; year = None;
      template = None; flavour = None; out = None; prune = false; 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_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. *)
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_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

(* `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 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. `citations` and `layer` may be omitted: they
    ; default to empty and to this overlay's own id.
    ((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)))))
     ; 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; format; from_y; to_y; dtstamp; year; template; flavour; out; prune; positional } -> (
      let reject_emit = reject_emit_flags_for ~format ~from_y ~to_y ~dtstamp in
      let reject_table = reject_table_flags_for ~year ~template ~flavour in
      let reject_publish = reject_publish_flags_for ~out ~prune in
      match positional with
      | [ ("-h" | "--help" | "help") ] ->
          reject_overlays_for "--help" overlays;
          reject_emit "--help";
          reject_table "--help";
          reject_publish "--help";
          print_help ()
      | [ ("-V" | "--version" | "version") ] ->
          reject_overlays_for "--version" overlays;
          reject_emit "--version";
          reject_table "--version";
          reject_publish "--version";
          print_endline version;
          exit 0
      | [ "easter"; ys ] ->
          reject_overlays_for "easter" overlays;
          reject_emit "easter";
          reject_table "easter";
          reject_publish "easter";
          with_year ys easter_report
      | [ "temporal"; ys ] ->
          reject_overlays_for "temporal" overlays;
          reject_emit "temporal";
          reject_table "temporal";
          reject_publish "temporal";
          with_year ys temporal_report
      | "check" :: (_ :: _ as files) ->
          reject_overlays_for "check" overlays;
          reject_emit "check";
          reject_table "check";
          reject_publish "check";
          check_report files
      | [ "convert"; path ] ->
          reject_overlays_for "convert" overlays;
          reject_emit "convert";
          reject_table "convert";
          reject_publish "convert";
          convert_report path
      | [ "new-overlay" ] ->
          reject_overlays_for "new-overlay" overlays;
          reject_emit "new-overlay";
          reject_table "new-overlay";
          reject_publish "new-overlay";
          print_string new_overlay_template;
          exit 0
      | [ "day"; ys ] ->
          reject_emit "day";
          reject_table "day";
          reject_publish "day";
          with_year ys (day_report ~overlays)
      | [ "readings"; ys ] ->
          reject_emit "readings";
          reject_table "readings";
          reject_publish "readings";
          with_year ys (readings_report ~overlays)
      | [ "emit" ] -> (
          reject_table "emit";
          reject_publish "emit";
          match format 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 ->
                  with_year from_ys (fun from_y ->
                      with_year to_ys (fun to_y -> emit_report ~format ~overlays ~dtstamp ~from_y ~to_y))))
      | [ ("table" | "render") as cmd ] -> (
          reject_emit cmd;
          reject_publish cmd;
          match template with
          | None ->
              Printf.eprintf "colitur: %s requires --year YEAR and --template FILE\n" cmd;
              exit 2
          | Some template -> (
              match year with
              | None ->
                  Printf.eprintf "colitur: %s requires --year YEAR and --template FILE\n" cmd;
                  exit 2
              | Some ys -> with_year ys (fun y -> table_report ~template ~flavour_opt:flavour ~overlays y)
              ))
      | [ "publish" ] -> (
          reject_table "publish";
          reject_format_for "publish" format;
          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 ->
                  with_year from_ys (fun from_y ->
                      with_year to_ys (fun to_y -> publish_report ~from_y ~to_y ~out ~overlays ~dtstamp ~prune))))
      | _ -> usage ())