tix-tracker 0.12.0

A terminal issue tracker: markdown + YAML frontmatter issues with a kanban TUI and CLI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
//! Supported recurrence rules: the typed model, its validation, and the
//! deterministic next-date arithmetic (mission `recurring-issues-01M3C7G7`,
//! WP01; contract `kitty-specs/recurring-issues-01M3C7G7/contracts/recurrence-rule.md`).
//!
//! # The five families
//!
//! [`RuleKind`] names exactly the families the mission approves: `daily`,
//! `weekly`, `monthly`, `interval`, and `cron-like`. A [`RecurrenceRule`] is a
//! flat, serializable record of that family plus its optional cadence fields —
//! the shape `data-model.md` §2 defines — so a rule round-trips through issue
//! frontmatter without a second schema and without becoming code.
//!
//! # Everything is injected
//!
//! [`RecurrenceRule::next_occurrence`] takes a [`RuleContext`]: the local
//! calendar date and (optionally) the local timezone the caller resolved. Domain
//! code never calls `now()` and never consults the system clock, so a test that
//! pins the context is testing the arithmetic, not the machine it runs on
//! (research R2, C-004).
//!
//! # Refusals are the product
//!
//! [`RecurrenceRule::validate`] collects **every** finding as a
//! [`RuleDiagnostic`] rather than failing on the first, and each diagnostic names
//! the offending field, its value, and one actionable sentence. The three cases
//! the mission escalates are all diagnostics rather than guesses:
//!
//! * **Month-end and leap-day arithmetic** is defined, not guessed: a monthly
//!   rule re-anchors on the target month's last day, and the rule is documented
//!   here (see [`RecurrenceRule::next_occurrence`]). A *stored* anchor that is
//!   not a real calendar date (`2025-02-29`, `2026-02-30`) is refused with
//!   [`RuleDiagnosticKind::InvalidAnchor`].
//! * **Daylight-saving ambiguity** can only come from a named IANA zone, which
//!   needs a tzdb this crate does not depend on. [`Timezone::Named`] is carried
//!   but refused with [`RuleDiagnosticKind::UnsupportedTimezone`], and a context
//!   offset that contradicts the rule's is refused with
//!   [`RuleDiagnosticKind::TimezoneMismatch`].
//! * **A general cron expression** needs a parser this mission has not approved
//!   (`docs/recurrence-dependency-review.md`). The parser seam
//!   ([`CronParser`]) ships with a bounded implementation over a closed macro
//!   vocabulary; anything else is refused with
//!   [`RuleDiagnosticKind::MalformedCronExpression`].
//!
//! # Canonical date keys
//!
//! Arithmetic produces a [`DateKey`], whose string form is `YYYY-MM-DD`. The
//! ordering is the point: sorting keys as strings sorts date
//! keys chronologically, so a caller needs no second comparator (C-002/C-006).
#![allow(clippy::module_name_repetitions)]

use std::collections::BTreeMap;
use std::fmt;

use serde::{Deserialize, Deserializer, Serialize, Serializer};
use time::{Date, Month, UtcOffset};

use crate::error::{TixError, render_diagnostics};

/// The largest interval any family accepts.
///
/// The field is bounded so arithmetic stays cheap and the stored value cannot
/// imply a schedule no user could mean. A hundred years of weekly steps is well
/// inside it; anything larger is far more likely to be a typo than an intent.
pub const MAX_INTERVAL: u32 = 1000;

/// The longest cron-like expression accepted, in bytes.
///
/// The bounded fallback vocabulary needs six characters; the cap exists so an
/// expression field can never carry an unbounded payload (T001's "reject
/// executable payloads").
pub const MAX_EXPRESSION_LEN: usize = 128;

/// The characters that mark an `expression` as code rather than a schedule.
///
/// A cron-like expression is a schedule, not a command line. Rather than hand the
/// text to a parser and hope it refuses, the obvious shell/comment metacharacters
/// are refused first, with a diagnostic that says which rule was broken.
const EXECUTABLE_MARKERS: &[char] = &[';', '`', '$', '|', '&', '\n', '\r', '\0'];

// ---------------------------------------------------------------------------
// T001 — supported rule kinds and typed representation
// ---------------------------------------------------------------------------

/// Which recurrence family a rule names (`data-model.md` §2).
///
/// The serde spelling is the contract's (`daily`, `weekly`, `monthly`,
/// `interval`, `cron-like`) because these strings are persisted in issue
/// frontmatter and read by `tix lint`, the CLI, and MCP.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum RuleKind {
    /// Every `interval` days (default 1) from the anchor.
    Daily,
    /// Every `interval` weeks (default 1) from the anchor, on its weekday.
    Weekly,
    /// Every `interval` months (default 1) from the anchor, on its day-of-month.
    Monthly,
    /// Every `interval` units from the anchor; the unit is `days`, `weeks`, or
    /// `months`, and both `interval` and `unit` are required.
    Interval,
    /// A cron-like expression, interpreted through [`CronParser`].
    CronLike,
}

impl RuleKind {
    /// The contract's spelling, used verbatim in diagnostics and payloads.
    pub const fn as_str(self) -> &'static str {
        match self {
            RuleKind::Daily => "daily",
            RuleKind::Weekly => "weekly",
            RuleKind::Monthly => "monthly",
            RuleKind::Interval => "interval",
            RuleKind::CronLike => "cron-like",
        }
    }

    /// Whether the family takes a `unit` field.
    const fn allows_unit(self) -> bool {
        matches!(self, RuleKind::Interval)
    }

    /// Whether the family takes an `expression` field.
    const fn allows_expression(self) -> bool {
        matches!(self, RuleKind::CronLike)
    }
}

/// The unit an [`RuleKind::Interval`] rule steps in.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum IntervalUnit {
    /// Step in whole days.
    Days,
    /// Step in whole weeks (seven days).
    Weeks,
    /// Step in calendar months, re-anchoring on the month's last day.
    Months,
}

impl IntervalUnit {
    /// The contract's spelling.
    pub const fn as_str(self) -> &'static str {
        match self {
            IntervalUnit::Days => "days",
            IntervalUnit::Weeks => "weeks",
            IntervalUnit::Months => "months",
        }
    }
}

/// The timezone policy a rule is expressed in (`data-model.md` §2).
///
/// Parsing never fails: text that is not a fixed offset is *classified* so that
/// validation can name it. That is deliberate — a deserializer that returned a
/// bare `unknown timezone` error would tell a user what `serde` thought, not
/// which field was wrong or why.
///
/// `UTC` and `Z` are accepted as conveniences and canonicalize to `+00:00`.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum Timezone {
    /// A fixed UTC offset, e.g. `+01:00`. Supported.
    Fixed(UtcOffset),
    /// A named IANA zone, e.g. `Europe/Berlin`. Refused by validation: a
    /// daylight-saving transition makes a local date ambiguous, and resolving it
    /// needs a tzdb this crate does not depend on.
    Named(String),
    /// Text that looks like an offset attempt (`+1:00`) but is not `±HH:MM`.
    Invalid(String),
}

impl Timezone {
    /// Classify a stored timezone string. Total; validation is what refuses.
    pub fn parse(raw: &str) -> Self {
        let value = raw.trim();
        if value.eq_ignore_ascii_case("utc") || value.eq_ignore_ascii_case("z") {
            return Timezone::Fixed(UtcOffset::UTC);
        }
        if let Some(offset) = parse_offset(value) {
            return Timezone::Fixed(offset);
        }
        if value.starts_with('+') || value.starts_with('-') {
            return Timezone::Invalid(raw.to_string());
        }
        Timezone::Named(raw.to_string())
    }

    /// Whether validation accepts this policy.
    pub const fn is_supported(&self) -> bool {
        matches!(self, Timezone::Fixed(_))
    }
}

impl fmt::Display for Timezone {
    /// Canonical `±HH:MM` (or `±HH:MM:SS` when seconds are present) for a fixed
    /// offset; the original text for anything else, so a diagnostic quotes what
    /// the user wrote.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Timezone::Fixed(offset) => {
                let (hours, minutes, seconds) = offset.as_hms();
                let sign = if hours < 0 || minutes < 0 || seconds < 0 {
                    '-'
                } else {
                    '+'
                };
                if seconds == 0 {
                    write!(
                        f,
                        "{sign}{:02}:{:02}",
                        hours.unsigned_abs(),
                        minutes.unsigned_abs()
                    )
                } else {
                    write!(
                        f,
                        "{sign}{:02}:{:02}:{:02}",
                        hours.unsigned_abs(),
                        minutes.unsigned_abs(),
                        seconds.unsigned_abs()
                    )
                }
            }
            Timezone::Named(raw) | Timezone::Invalid(raw) => f.write_str(raw),
        }
    }
}

impl Serialize for Timezone {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(&self.to_string())
    }
}

impl<'de> Deserialize<'de> for Timezone {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        Ok(Timezone::parse(&String::deserialize(deserializer)?))
    }
}

/// Parse `±HH:MM` or `±HH:MM:SS`; `None` for anything else.
///
/// The offset grammar is nine characters at most and entirely bounded, so it is
/// parsed here rather than by a `time` feature this crate has not enabled
/// (`time` is depended on with default features only — see `Cargo.toml`).
fn parse_offset(value: &str) -> Option<UtcOffset> {
    let bytes = value.as_bytes();
    let sign = match bytes.first()? {
        b'+' => 1_i8,
        b'-' => -1_i8,
        _ => return None,
    };
    let rest = &bytes[1..];
    if rest.len() != 5 && rest.len() != 8 {
        return None;
    }
    if rest[2] != b':' {
        return None;
    }
    if rest.len() == 8 && rest[5] != b':' {
        return None;
    }
    let digits: Vec<u8> = rest.iter().copied().filter(|c| *c != b':').collect();
    if !digits.iter().all(u8::is_ascii_digit) {
        return None;
    }
    let number =
        |pair: usize| -> i8 { (digits[pair] - b'0') as i8 * 10 + (digits[pair + 1] - b'0') as i8 };
    let hours = sign * number(0);
    let minutes = sign * number(2);
    let seconds = if digits.len() == 6 {
        sign * number(4)
    } else {
        0
    };
    // Bound the components **here** rather than leaning on `UtcOffset::from_hms`'s
    // internal ranges: a fixed offset lies within `±23:59:59`, and `+24:00` is not
    // a timezone. `from_hms` accepts the hour `24`, so the check is not redundant.
    if hours.unsigned_abs() > 23 || minutes.unsigned_abs() > 59 || seconds.unsigned_abs() > 59 {
        return None;
    }
    UtcOffset::from_hms(hours, minutes, seconds).ok()
}

/// A supported schedule definition (`data-model.md` §2).
///
/// Field literals are public so a surface can build a rule directly; the
/// `with_*` builders exist for the common "start from a kind and add fields"
/// case. Nothing here is executable: `expression` is text a [`CronParser`]
/// interprets, and `extensions` is inert metadata.
///
/// # Unknown metadata (T005)
///
/// A key this build does not interpret lands in [`RecurrenceRule::extensions`]
/// and is written back on the next serialization. A newer `tix` that adds a
/// cadence field writes it into the same record, and this build preserves it
/// rather than silently dropping it on the next edit.
///
/// # Why `PartialEq` and not `Eq`
///
/// `extensions` holds `serde_yaml::Value`, which carries floats and therefore
/// has no `Eq`. Whole-struct equality is the priority; the missing `Eq` is the
/// documented consequence.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RecurrenceRule {
    /// The supported family this rule names.
    pub kind: RuleKind,
    /// The cadence, where the family uses one.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub interval: Option<u32>,
    /// The stable schedule origin, as a canonical `YYYY-MM-DD` date.
    ///
    /// Required for every family: an origin is what makes a schedule
    /// deterministic, and inventing one from the inject context would be exactly
    /// the silent guess C-009 escalates.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub anchor: Option<String>,
    /// The explicit timezone policy, or `None` for a timezone-independent
    /// calendar rule.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub timezone: Option<Timezone>,
    /// The cron-like expression; only meaningful for [`RuleKind::CronLike`].
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub expression: Option<String>,
    /// The [`RuleKind::Interval`] unit.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub unit: Option<IntervalUnit>,
    /// Metadata this build does not interpret, preserved verbatim.
    #[serde(flatten)]
    pub extensions: BTreeMap<String, serde_yaml::Value>,
}

impl RecurrenceRule {
    /// A bare rule of `kind`, with no cadence fields and no extensions.
    pub fn new(kind: RuleKind) -> Self {
        Self {
            kind,
            interval: None,
            anchor: None,
            timezone: None,
            expression: None,
            unit: None,
            extensions: BTreeMap::new(),
        }
    }

    /// Set the cadence.
    pub fn with_interval(mut self, interval: u32) -> Self {
        self.interval = Some(interval);
        self
    }

    /// Set the anchor, as a `YYYY-MM-DD` string.
    pub fn with_anchor(mut self, anchor: impl Into<String>) -> Self {
        self.anchor = Some(anchor.into());
        self
    }

    /// Set the timezone policy.
    pub fn with_timezone(mut self, timezone: Timezone) -> Self {
        self.timezone = Some(timezone);
        self
    }

    /// Set the cron-like expression.
    pub fn with_expression(mut self, expression: impl Into<String>) -> Self {
        self.expression = Some(expression.into());
        self
    }

    /// Set the interval unit.
    pub fn with_unit(mut self, unit: IntervalUnit) -> Self {
        self.unit = Some(unit);
        self
    }
}

// ---------------------------------------------------------------------------
// T002 / T005 — validation and field-aware diagnostics
// ---------------------------------------------------------------------------

/// The diagnostic kinds rule validation produces, spelled in `snake_case`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RuleDiagnosticKind {
    /// No anchor was given for a family that requires one.
    MissingAnchor,
    /// The anchor text is not a real calendar date.
    InvalidAnchor,
    /// The interval is outside `1..=MAX_INTERVAL`.
    InvalidInterval,
    /// An `interval` family rule has no interval.
    MissingInterval,
    /// An `interval` family rule has no unit.
    MissingUnit,
    /// A `unit` was given on a family that has none.
    UnexpectedUnit,
    /// An `expression` was given on a family that has none.
    UnexpectedExpression,
    /// A `cron-like` rule has no expression.
    MissingExpression,
    /// The expression exceeds [`MAX_EXPRESSION_LEN`].
    ExpressionTooLong,
    /// The expression carries code-like characters, not a schedule.
    ExecutablePayload,
    /// The expression is not in the supported cron-like vocabulary.
    MalformedCronExpression,
    /// The timezone text is not a fixed offset.
    InvalidTimezone,
    /// The timezone is a named zone whose DST behaviour cannot be resolved.
    UnsupportedTimezone,
    /// The rule's offset and the injected context's offset disagree.
    TimezoneMismatch,
    /// The computed occurrence falls outside the supported calendar range.
    CalendarRange,
}

impl RuleDiagnosticKind {
    /// The contract's spelling, used verbatim in lint and MCP payloads.
    pub const fn as_str(self) -> &'static str {
        match self {
            RuleDiagnosticKind::MissingAnchor => "missing_anchor",
            RuleDiagnosticKind::InvalidAnchor => "invalid_anchor",
            RuleDiagnosticKind::InvalidInterval => "invalid_interval",
            RuleDiagnosticKind::MissingInterval => "missing_interval",
            RuleDiagnosticKind::MissingUnit => "missing_unit",
            RuleDiagnosticKind::UnexpectedUnit => "unexpected_unit",
            RuleDiagnosticKind::UnexpectedExpression => "unexpected_expression",
            RuleDiagnosticKind::MissingExpression => "missing_expression",
            RuleDiagnosticKind::ExpressionTooLong => "expression_too_long",
            RuleDiagnosticKind::ExecutablePayload => "executable_payload",
            RuleDiagnosticKind::MalformedCronExpression => "malformed_cron_expression",
            RuleDiagnosticKind::InvalidTimezone => "invalid_timezone",
            RuleDiagnosticKind::UnsupportedTimezone => "unsupported_timezone",
            RuleDiagnosticKind::TimezoneMismatch => "timezone_mismatch",
            RuleDiagnosticKind::CalendarRange => "calendar_range",
        }
    }
}

/// One field-aware rule diagnostic.
///
/// `value` is the offending value as text, and is **empty** when the field was
/// absent entirely; `message` is the single actionable sentence a surface
/// prints. The message already leads with the field name, so the shared
/// renderer's kind prefix completes the line.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RuleDiagnostic {
    /// Which rule was broken.
    pub kind: RuleDiagnosticKind,
    /// The offending field (`interval`, `anchor`, `timezone`, `unit`,
    /// `expression`).
    pub field: &'static str,
    /// The offending value, or empty when the field was absent.
    pub value: String,
    /// The user-facing sentence.
    pub message: String,
}

impl RuleDiagnostic {
    fn new(
        kind: RuleDiagnosticKind,
        field: &'static str,
        value: impl Into<String>,
        message: impl Into<String>,
    ) -> Self {
        Self {
            kind,
            field,
            value: value.into(),
            message: message.into(),
        }
    }
}

/// Why a rule was refused: one or more diagnostics, never a partial answer.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RuleError {
    /// Every diagnostic found, in a deterministic field order.
    pub errors: Vec<RuleDiagnostic>,
}

impl RuleError {
    /// An error carrying `errors`.
    fn new(errors: Vec<RuleDiagnostic>) -> Self {
        Self { errors }
    }

    /// An error carrying one diagnostic.
    fn single(error: RuleDiagnostic) -> Self {
        Self {
            errors: vec![error],
        }
    }

    /// Every diagnostic, in order.
    pub fn diagnostics(&self) -> &[RuleDiagnostic] {
        &self.errors
    }

    /// The first diagnostic.
    pub fn first(&self) -> &RuleDiagnostic {
        &self.errors[0]
    }
}

impl fmt::Display for RuleError {
    /// **Every** diagnostic, through the shared renderer, so a rule refusal
    /// reads like every other validation refusal in the crate.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.errors.is_empty() {
            return f.write_str("recurrence rule validation failed");
        }
        f.write_str(&render_diagnostics(
            "E-tix-recurrence",
            self.errors
                .iter()
                .map(|e| (e.kind.as_str(), e.message.as_str())),
        ))
    }
}

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

/// A rule refusal becomes a rendered error at the surface, like every other
/// validation refusal (`crate::error::TixError::Refused`).
impl From<RuleError> for TixError {
    fn from(err: RuleError) -> TixError {
        TixError::Refused(err.to_string())
    }
}

fn missing_anchor(kind: RuleKind) -> RuleDiagnostic {
    RuleDiagnostic::new(
        RuleDiagnosticKind::MissingAnchor,
        "anchor",
        "",
        format!("anchor: is required for a {} rule", kind.as_str()),
    )
}

fn invalid_anchor(value: &str) -> RuleDiagnostic {
    RuleDiagnostic::new(
        RuleDiagnosticKind::InvalidAnchor,
        "anchor",
        value,
        format!("anchor: `{value}` is not a valid `YYYY-MM-DD` calendar date"),
    )
}

fn invalid_interval(value: u32) -> RuleDiagnostic {
    RuleDiagnostic::new(
        RuleDiagnosticKind::InvalidInterval,
        "interval",
        value.to_string(),
        format!("interval: must be between 1 and {MAX_INTERVAL} (got {value})"),
    )
}

fn missing_interval() -> RuleDiagnostic {
    RuleDiagnostic::new(
        RuleDiagnosticKind::MissingInterval,
        "interval",
        "",
        "interval: is required for an interval rule",
    )
}

fn missing_unit() -> RuleDiagnostic {
    RuleDiagnostic::new(
        RuleDiagnosticKind::MissingUnit,
        "unit",
        "",
        "unit: is required for an interval rule",
    )
}

fn unexpected_unit() -> RuleDiagnostic {
    RuleDiagnostic::new(
        RuleDiagnosticKind::UnexpectedUnit,
        "unit",
        "",
        "unit: is only allowed on an interval rule",
    )
}

fn unexpected_expression() -> RuleDiagnostic {
    RuleDiagnostic::new(
        RuleDiagnosticKind::UnexpectedExpression,
        "expression",
        "",
        "expression: is only allowed on a cron-like rule",
    )
}

fn missing_expression() -> RuleDiagnostic {
    RuleDiagnostic::new(
        RuleDiagnosticKind::MissingExpression,
        "expression",
        "",
        "expression: is required for a cron-like rule",
    )
}

fn expression_too_long(value: &str) -> RuleDiagnostic {
    RuleDiagnostic::new(
        RuleDiagnosticKind::ExpressionTooLong,
        "expression",
        value,
        format!(
            "expression: must be at most {MAX_EXPRESSION_LEN} characters (got {})",
            value.len()
        ),
    )
}

fn executable_payload(value: &str) -> RuleDiagnostic {
    RuleDiagnostic::new(
        RuleDiagnosticKind::ExecutablePayload,
        "expression",
        value,
        format!(
            "expression: `{value}` contains characters that are not part of a cron-like expression"
        ),
    )
}

fn malformed_expression(value: &str) -> RuleDiagnostic {
    RuleDiagnostic::new(
        RuleDiagnosticKind::MalformedCronExpression,
        "expression",
        value,
        format!(
            "expression: `{value}` is not a supported cron-like expression \
             (only @daily, @weekly, and @monthly are accepted; a general parser needs the reviewed dependency)"
        ),
    )
}

fn unsupported_timezone(value: &str) -> RuleDiagnostic {
    RuleDiagnostic::new(
        RuleDiagnosticKind::UnsupportedTimezone,
        "timezone",
        value,
        format!(
            "timezone: rule `{value}` is a named zone; only fixed UTC offsets are supported \
             (daylight-saving needs a reviewed tzdb)"
        ),
    )
}

fn invalid_timezone(value: &str) -> RuleDiagnostic {
    RuleDiagnostic::new(
        RuleDiagnosticKind::InvalidTimezone,
        "timezone",
        value,
        format!("timezone: rule `{value}` is not a fixed UTC offset (use ±HH:MM or UTC)"),
    )
}

fn context_unsupported_timezone(value: &str) -> RuleDiagnostic {
    RuleDiagnostic::new(
        RuleDiagnosticKind::UnsupportedTimezone,
        "timezone",
        value,
        format!(
            "timezone: context `{value}` is a named zone; only fixed UTC offsets are supported \
             (daylight-saving needs a reviewed tzdb)"
        ),
    )
}

fn context_invalid_timezone(value: &str) -> RuleDiagnostic {
    RuleDiagnostic::new(
        RuleDiagnosticKind::InvalidTimezone,
        "timezone",
        value,
        format!("timezone: context `{value}` is not a fixed UTC offset (use ±HH:MM or UTC)"),
    )
}

fn timezone_mismatch(rule: UtcOffset, context: UtcOffset) -> RuleDiagnostic {
    let rule = Timezone::Fixed(rule);
    let context = Timezone::Fixed(context);
    RuleDiagnostic::new(
        RuleDiagnosticKind::TimezoneMismatch,
        "timezone",
        rule.to_string(),
        format!("timezone: rule offset `{rule}` does not match context offset `{context}`"),
    )
}

fn calendar_range(anchor: Date, today: Date) -> RuleDiagnostic {
    RuleDiagnostic::new(
        RuleDiagnosticKind::CalendarRange,
        "anchor",
        anchor.to_string(),
        format!(
            "anchor: the next occurrence after `{today}` falls outside the supported calendar range"
        ),
    )
}

impl RecurrenceRule {
    /// Validate the rule before it is persisted (T002, C-004).
    ///
    /// Collects **every** finding rather than failing on the first, so a user
    /// fixes one rule once instead of discovering one problem per attempt. A
    /// refusal writes nothing, so an invalid rule can never reach a series file.
    pub fn validate(&self) -> Result<(), RuleError> {
        let errors = self.diagnostics();
        if errors.is_empty() {
            Ok(())
        } else {
            Err(RuleError::new(errors))
        }
    }

    /// Every diagnostic, in deterministic field order.
    pub fn diagnostics(&self) -> Vec<RuleDiagnostic> {
        let mut errors = Vec::new();

        // anchor — required for every family, and required to be a real date.
        match self.anchor.as_deref() {
            None => errors.push(missing_anchor(self.kind)),
            Some(raw) if parse_date(raw).is_none() => errors.push(invalid_anchor(raw)),
            Some(_) => {}
        }

        // interval — bounded where present, required for the interval family.
        if let Some(interval) = self.interval {
            if !(1..=MAX_INTERVAL).contains(&interval) {
                errors.push(invalid_interval(interval));
            }
        } else if self.kind == RuleKind::Interval {
            errors.push(missing_interval());
        }

        // unit — only the interval family has one, and it must have it.
        if self.unit.is_some() && !self.kind.allows_unit() {
            errors.push(unexpected_unit());
        } else if self.unit.is_none() && self.kind.allows_unit() {
            errors.push(missing_unit());
        }

        // expression — only the cron-like family has one, and it must parse.
        self.push_expression_diagnostics(&mut errors);

        // timezone — carried but only a fixed offset is supported.
        match &self.timezone {
            Some(Timezone::Named(raw)) => errors.push(unsupported_timezone(raw)),
            Some(Timezone::Invalid(raw)) => errors.push(invalid_timezone(raw)),
            _ => {}
        }

        errors
    }

    /// The expression checks, kept out of [`RecurrenceRule::diagnostics`] so the
    /// field order there stays readable.
    fn push_expression_diagnostics(&self, errors: &mut Vec<RuleDiagnostic>) {
        match self.expression.as_deref() {
            Some(raw) if self.kind.allows_expression() => {
                if raw.len() > MAX_EXPRESSION_LEN {
                    errors.push(expression_too_long(raw));
                } else if raw.contains(EXECUTABLE_MARKERS) {
                    errors.push(executable_payload(raw));
                } else if let Err(diagnostic) = BoundedCronParser.parse(raw) {
                    errors.push(diagnostic);
                }
            }
            Some(_) => errors.push(unexpected_expression()),
            None if self.kind.allows_expression() => errors.push(missing_expression()),
            None => {}
        }
    }

    /// The anchor as a calendar date, if the rule has a valid one.
    pub fn anchor_date(&self) -> Result<Date, RuleError> {
        let raw = self
            .anchor
            .as_deref()
            .ok_or_else(|| RuleError::single(missing_anchor(self.kind)))?;
        parse_date(raw).ok_or_else(|| RuleError::single(invalid_anchor(raw)))
    }

    /// The canonical anchor date key.
    pub fn anchor_key(&self) -> Result<DateKey, RuleError> {
        Ok(DateKey::from_date(self.anchor_date()?))
    }

    /// A one-line human summary of the rule, for a warning's `rule_summary`.
    ///
    /// Best-effort on an invalid rule: the summary is display text, and refusing
    /// to render it would hide the very rule a user is trying to fix.
    pub fn summary(&self) -> String {
        let interval = self.interval.unwrap_or(1);
        match self.kind {
            RuleKind::Daily if interval == 1 => "daily".to_string(),
            RuleKind::Daily => format!("every {interval} days"),
            RuleKind::Weekly if interval == 1 => "weekly".to_string(),
            RuleKind::Weekly => format!("every {interval} weeks"),
            RuleKind::Monthly if interval == 1 => "monthly".to_string(),
            RuleKind::Monthly => format!("every {interval} months"),
            RuleKind::Interval => {
                let unit = self.unit.map_or("days", IntervalUnit::as_str);
                format!("every {interval} {unit}")
            }
            RuleKind::CronLike => {
                format!(
                    "cron-like `{}`",
                    self.expression.as_deref().unwrap_or_default()
                )
            }
        }
    }
}

// ---------------------------------------------------------------------------
// T003 — deterministic next-date arithmetic
// ---------------------------------------------------------------------------

/// The injected local date/timezone context.
///
/// Nothing in this module reads the clock: the caller resolves "now" to a local
/// calendar date and hands it over, which is what makes detection and generation
/// reproducible in a test (research R2).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RuleContext {
    /// The local calendar date to evaluate relative to.
    pub today: Date,
    /// The local timezone the date was resolved in, or `None` for a
    /// timezone-independent context.
    pub timezone: Option<Timezone>,
}

impl RuleContext {
    /// A timezone-independent context for `today`.
    pub const fn on(today: Date) -> Self {
        Self {
            today,
            timezone: None,
        }
    }

    /// Attach the timezone the date was resolved in.
    pub fn with_timezone(mut self, timezone: Timezone) -> Self {
        self.timezone = Some(timezone);
        self
    }
}

/// A canonical local date key: `YYYY-MM-DD`.
///
/// `Ord` is the whole point: keys sort chronologically as plain strings, so a
/// caller can order occurrences without parsing them (C-002/C-006). WP02 builds
/// the occurrence key from a series ID and this value.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct DateKey(String);

impl DateKey {
    /// The canonical key for `date`.
    pub fn from_date(date: Date) -> Self {
        Self(date.to_string())
    }

    /// The key as a string slice.
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl fmt::Display for DateKey {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

/// The resolved cadence behind a validated rule.
enum Schedule {
    /// A whole number of days between occurrences.
    Days(u32),
    /// A whole number of weeks between occurrences.
    Weeks(u32),
    /// A whole number of calendar months between occurrences.
    Months(u32),
}

impl RecurrenceRule {
    /// The first occurrence strictly after `context.today` (T003).
    ///
    /// The schedule is `anchor`, `anchor + step`, `anchor + 2·step`, …; the
    /// result is the first of those dates after the injected date key. An anchor
    /// in the future is therefore the answer, and an occurrence exactly on the
    /// injected date is *not* the answer — "next" means next.
    ///
    /// # Month-end and leap-day arithmetic, defined not guessed
    ///
    /// A monthly step keeps the anchor's day-of-month and re-anchors on the
    /// target month's **last day** when that day does not exist. An anchor of
    /// `2026-01-31` therefore recurs on `2026-02-28`, and a `2024-02-29` anchor
    /// recurs on `2025-02-28`; the rules are here, in one place, rather than
    /// left to whichever arithmetic a caller happened to write. A *stored* anchor
    /// that is not a real date at all (`2025-02-29`) never reaches this function:
    /// validation refuses it first.
    ///
    /// # Ambiguity is refused
    ///
    /// The rule is validated, then the injected context: a named zone on either
    /// side, an unparseable offset, or a rule/context offset disagreement is a
    /// diagnostic rather than a silent normalization. A computed occurrence
    /// outside the supported calendar range is a diagnostic too.
    pub fn next_occurrence(&self, context: &RuleContext) -> Result<DateKey, RuleError> {
        self.validate()?;
        self.validate_context(context)?;
        let anchor = self.anchor_date()?;
        let today = context.today;
        let date = match self.schedule()? {
            Schedule::Days(step) => next_day_step(anchor, today, step)?,
            Schedule::Weeks(step) => next_day_step(anchor, today, step.saturating_mul(7))?,
            Schedule::Months(step) => next_month_step(anchor, today, step)?,
        };
        Ok(DateKey::from_date(date))
    }

    /// Refuse an injected context this module cannot evaluate deterministically.
    fn validate_context(&self, context: &RuleContext) -> Result<(), RuleError> {
        let mut errors = Vec::new();
        match &context.timezone {
            Some(Timezone::Named(raw)) => errors.push(context_unsupported_timezone(raw)),
            Some(Timezone::Invalid(raw)) => errors.push(context_invalid_timezone(raw)),
            _ => {}
        }
        if let (Some(Timezone::Fixed(rule)), Some(Timezone::Fixed(injected))) =
            (self.timezone.as_ref(), context.timezone.as_ref())
            && rule != injected
        {
            errors.push(timezone_mismatch(*rule, *injected));
        }
        if errors.is_empty() {
            Ok(())
        } else {
            Err(RuleError::new(errors))
        }
    }

    /// The resolved cadence. Only reachable once validation has passed, so a
    /// missing field is reported rather than panicked on.
    fn schedule(&self) -> Result<Schedule, RuleError> {
        let interval = self.interval.unwrap_or(1);
        Ok(match self.kind {
            RuleKind::Daily => Schedule::Days(interval),
            RuleKind::Weekly => Schedule::Weeks(interval),
            RuleKind::Monthly => Schedule::Months(interval),
            RuleKind::Interval => match self.unit {
                Some(IntervalUnit::Days) => Schedule::Days(interval),
                Some(IntervalUnit::Weeks) => Schedule::Weeks(interval),
                Some(IntervalUnit::Months) => Schedule::Months(interval),
                None => return Err(RuleError::single(missing_unit())),
            },
            RuleKind::CronLike => match BoundedCronParser
                .parse(self.expression.as_deref().unwrap_or_default())
                .map_err(RuleError::single)?
            {
                CronSchedule::Daily => Schedule::Days(1),
                CronSchedule::Weekly => Schedule::Weeks(1),
                CronSchedule::Monthly => Schedule::Months(1),
            },
        })
    }
}

/// Parse a canonical `YYYY-MM-DD` date.
///
/// The calendar authority is [`crate::model::validate_date`] — the same check
/// every other stored date passes — so a rule anchor cannot be "a date" to one
/// part of the crate and not another. `time` provides the arithmetic value.
fn parse_date(value: &str) -> Option<Date> {
    if !crate::model::validate_date(value) {
        return None;
    }
    let year: i32 = value.get(0..4)?.parse().ok()?;
    let month: u8 = value.get(5..7)?.parse().ok()?;
    let day: u8 = value.get(8..10)?.parse().ok()?;
    Date::from_calendar_date(year, Month::try_from(month).ok()?, day).ok()
}

/// The first `anchor + k·step` day after `today`, for day-based cadences.
fn next_day_step(anchor: Date, today: Date, step: u32) -> Result<Date, RuleError> {
    let anchor_day = i64::from(anchor.to_julian_day());
    let today_day = i64::from(today.to_julian_day());
    let step = i64::from(step);
    let elapsed = today_day - anchor_day;
    let next = if elapsed < 0 { 0 } else { elapsed / step + 1 };
    let julian = i32::try_from(anchor_day + next * step)
        .map_err(|_| RuleError::single(calendar_range(anchor, today)))?;
    Date::from_julian_day(julian).map_err(|_| RuleError::single(calendar_range(anchor, today)))
}

/// The first monthly occurrence after `today`, re-anchoring on the last day of
/// a month that is too short for the anchor's day.
fn next_month_step(anchor: Date, today: Date, step: u32) -> Result<Date, RuleError> {
    let step = i64::from(step);
    let anchor_month = month_index(anchor);
    let today_month = month_index(today);
    let mut candidate = if today_month <= anchor_month {
        anchor_month
    } else {
        anchor_month + ((today_month - anchor_month) / step) * step
    };
    loop {
        let (year, month) = split_month_index(candidate)
            .ok_or_else(|| RuleError::single(calendar_range(anchor, today)))?;
        let day = anchor.day().min(month.length(year));
        let date = Date::from_calendar_date(year, month, day)
            .map_err(|_| RuleError::single(calendar_range(anchor, today)))?;
        if date > today {
            return Ok(date);
        }
        candidate += step;
    }
}

/// A date's absolute month index, for month arithmetic that cannot lose a year.
fn month_index(date: Date) -> i64 {
    i64::from(date.year()) * 12 + i64::from(u8::from(date.month())) - 1
}

/// The `(year, month)` a month index names.
fn split_month_index(index: i64) -> Option<(i32, Month)> {
    let year = i32::try_from(index.div_euclid(12)).ok()?;
    let month = u8::try_from(index.rem_euclid(12) + 1).ok()?;
    Month::try_from(month).ok().map(|month| (year, month))
}

// ---------------------------------------------------------------------------
// T004 — the cron-like parser seam and its supply-chain gate
// ---------------------------------------------------------------------------

/// The cadence a cron-like expression resolves to.
///
/// Deliberately the *same* shapes the other families produce, so a cron-like
/// rule goes through the reviewed arithmetic rather than a second scheduler.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CronSchedule {
    /// Once a day.
    Daily,
    /// Once a week, on the anchor's weekday.
    Weekly,
    /// Once a month, on the anchor's day-of-month.
    Monthly,
}

/// The seam through which a cron-like expression is interpreted (T004).
///
/// The mission approves **no** cron parser dependency: `Cargo.toml` is unchanged
/// and `docs/recurrence-dependency-review.md` records why. This trait is the
/// place a reviewed parser would be substituted — one implementation swap, not a
/// grammar spread through the module — and [`BoundedCronParser`] is what ships
/// today.
pub trait CronParser: fmt::Debug {
    /// Interpret `expression`, or refuse with a field-aware diagnostic.
    fn parse(&self, expression: &str) -> Result<CronSchedule, RuleDiagnostic>;
}

/// The shipped parser: a **closed macro vocabulary**, not a cron grammar.
///
/// `@daily`, `@weekly`, and `@monthly` are the entire accepted language, and each
/// maps onto arithmetic this module already owns. Parsing a general five-field
/// expression was rejected for this work package on purpose: hand-rolling that
/// grammar is itself an escalation (`research.md` R8, C-009), and the maintained
/// crates all pull a second date/time stack along with them (see the review
/// record). A general expression is therefore refused, not guessed.
#[derive(Debug, Clone, Copy, Default)]
pub struct BoundedCronParser;

impl CronParser for BoundedCronParser {
    fn parse(&self, expression: &str) -> Result<CronSchedule, RuleDiagnostic> {
        match expression.trim().to_ascii_lowercase().as_str() {
            "@daily" => Ok(CronSchedule::Daily),
            "@weekly" => Ok(CronSchedule::Weekly),
            "@monthly" => Ok(CronSchedule::Monthly),
            _ => Err(malformed_expression(expression)),
        }
    }
}

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

    fn date(year: i32, month: u8, day: u8) -> Date {
        Date::from_calendar_date(year, Month::try_from(month).expect("1..=12"), day)
            .expect("test date is valid")
    }

    fn weekly(anchor: &str) -> RecurrenceRule {
        RecurrenceRule::new(RuleKind::Weekly).with_anchor(anchor)
    }

    #[test]
    fn validate_accepts_every_family() {
        let rules = [
            RecurrenceRule::new(RuleKind::Daily).with_anchor("2026-01-05"),
            weekly("2026-01-05"),
            RecurrenceRule::new(RuleKind::Monthly).with_anchor("2026-01-31"),
            RecurrenceRule::new(RuleKind::Interval)
                .with_anchor("2026-01-05")
                .with_interval(2)
                .with_unit(IntervalUnit::Weeks),
            RecurrenceRule::new(RuleKind::CronLike)
                .with_anchor("2026-01-05")
                .with_expression("@weekly"),
        ];
        for rule in rules {
            assert!(
                rule.validate().is_ok(),
                "expected {:?} to be valid",
                rule.kind
            );
        }
    }

    #[test]
    fn validate_collects_every_diagnostic_not_just_the_first() {
        let rule = RecurrenceRule::new(RuleKind::Interval).with_interval(0);
        let errors = rule.validate().expect_err("rule is invalid").errors;
        let kinds: Vec<_> = errors.iter().map(|e| e.kind).collect();
        assert_eq!(
            kinds,
            vec![
                RuleDiagnosticKind::MissingAnchor,
                RuleDiagnosticKind::InvalidInterval,
                RuleDiagnosticKind::MissingUnit,
            ]
        );
    }

    #[test]
    fn daily_interval_defaults_to_one_day() {
        let rule = RecurrenceRule::new(RuleKind::Daily).with_anchor("2026-01-05");
        let next = rule
            .next_occurrence(&RuleContext::on(date(2026, 1, 5)))
            .expect("valid rule");
        assert_eq!(next.as_str(), "2026-01-06");
    }

    #[test]
    fn anchor_in_the_future_is_the_next_occurrence() {
        let next = weekly("2026-03-02")
            .next_occurrence(&RuleContext::on(date(2026, 1, 5)))
            .expect("valid rule");
        assert_eq!(next.as_str(), "2026-03-02");
    }

    #[test]
    fn weekly_interval_steps_by_whole_weeks() {
        let rule = weekly("2026-01-05").with_interval(2);
        let next = rule
            .next_occurrence(&RuleContext::on(date(2026, 1, 12)))
            .expect("valid rule");
        assert_eq!(next.as_str(), "2026-01-19");
    }

    #[test]
    fn occurrence_on_the_context_date_is_not_the_next_one() {
        let next = weekly("2026-01-05")
            .next_occurrence(&RuleContext::on(date(2026, 1, 5)))
            .expect("valid rule");
        assert_eq!(next.as_str(), "2026-01-12");
    }

    #[test]
    fn monthly_step_reanchors_on_the_last_day_of_a_short_month() {
        let rule = RecurrenceRule::new(RuleKind::Monthly).with_anchor("2026-01-31");
        let next = rule
            .next_occurrence(&RuleContext::on(date(2026, 1, 31)))
            .expect("valid rule");
        assert_eq!(next.as_str(), "2026-02-28");
        let following = rule
            .next_occurrence(&RuleContext::on(date(2026, 2, 28)))
            .expect("valid rule");
        assert_eq!(following.as_str(), "2026-03-31");
    }

    #[test]
    fn monthly_step_keeps_the_original_day_after_a_clamped_month() {
        let rule = RecurrenceRule::new(RuleKind::Monthly).with_anchor("2026-01-30");
        let next = rule
            .next_occurrence(&RuleContext::on(date(2026, 2, 28)))
            .expect("valid rule");
        assert_eq!(next.as_str(), "2026-03-30");
    }

    #[test]
    fn monthly_leap_day_anchor_clamps_in_a_common_year() {
        let rule = RecurrenceRule::new(RuleKind::Monthly).with_anchor("2024-02-29");
        let next = rule
            .next_occurrence(&RuleContext::on(date(2024, 2, 29)))
            .expect("valid rule");
        assert_eq!(next.as_str(), "2024-03-29");
        let common_year = rule
            .next_occurrence(&RuleContext::on(date(2025, 2, 1)))
            .expect("valid rule");
        assert_eq!(common_year.as_str(), "2025-02-28");
    }

    #[test]
    fn far_anchor_does_not_scan_every_step() {
        let rule = RecurrenceRule::new(RuleKind::Daily).with_anchor("1970-01-01");
        let next = rule
            .next_occurrence(&RuleContext::on(date(2026, 1, 5)))
            .expect("valid rule");
        assert_eq!(next.as_str(), "2026-01-06");
    }

    #[test]
    fn occurrence_beyond_the_calendar_range_is_a_diagnostic_not_a_panic() {
        let rule = RecurrenceRule::new(RuleKind::Daily).with_anchor("9999-12-31");
        let error = rule
            .next_occurrence(&RuleContext::on(date(9999, 12, 31)))
            .expect_err("occurrence would fall outside the supported range");
        assert_eq!(error.first().kind, RuleDiagnosticKind::CalendarRange);
    }

    #[test]
    fn interval_rule_without_unit_is_reported() {
        let rule = RecurrenceRule::new(RuleKind::Interval)
            .with_anchor("2026-01-05")
            .with_interval(3);
        assert_eq!(
            rule.validate().expect_err("invalid").first().kind,
            RuleDiagnosticKind::MissingUnit
        );
    }

    #[test]
    fn a_named_zone_on_the_context_is_refused() {
        let context =
            RuleContext::on(date(2026, 1, 5)).with_timezone(Timezone::parse("Europe/Berlin"));
        let error = weekly("2026-01-05")
            .next_occurrence(&context)
            .expect_err("named context zone is refused");
        assert_eq!(error.first().kind, RuleDiagnosticKind::UnsupportedTimezone);
        assert_eq!(error.first().value, "Europe/Berlin");
    }

    #[test]
    fn matching_offsets_are_accepted() {
        let rule = weekly("2026-01-05").with_timezone(Timezone::parse("+01:00"));
        let context = RuleContext::on(date(2026, 1, 12)).with_timezone(Timezone::parse("+01:00"));
        assert_eq!(
            rule.next_occurrence(&context).expect("valid rule").as_str(),
            "2026-01-19"
        );
    }

    #[test]
    fn timezone_text_round_trips_through_its_classification() {
        assert_eq!(
            Timezone::parse("+05:30"),
            Timezone::Fixed(UtcOffset::from_hms(5, 30, 0).expect("valid offset"))
        );
        assert_eq!(Timezone::parse("UTC").to_string(), "+00:00");
        assert_eq!(
            Timezone::parse("+1:00"),
            Timezone::Invalid("+1:00".to_string())
        );
        assert_eq!(
            Timezone::parse("America/New_York"),
            Timezone::Named("America/New_York".to_string())
        );
        assert!(Timezone::parse("+02:00").is_supported());
        assert!(!Timezone::parse("America/New_York").is_supported());
    }

    #[test]
    fn summary_renders_each_family() {
        assert_eq!(
            RecurrenceRule::new(RuleKind::Daily)
                .with_anchor("2026-01-05")
                .summary(),
            "daily"
        );
        assert_eq!(
            weekly("2026-01-05").with_interval(2).summary(),
            "every 2 weeks"
        );
        assert_eq!(
            RecurrenceRule::new(RuleKind::Interval)
                .with_unit(IntervalUnit::Months)
                .with_interval(3)
                .summary(),
            "every 3 months"
        );
        assert_eq!(
            RecurrenceRule::new(RuleKind::CronLike)
                .with_expression("@weekly")
                .summary(),
            "cron-like `@weekly`"
        );
    }

    #[test]
    fn anchor_date_uses_the_crate_calendar_authority() {
        let rule = weekly("2026-01-05");
        assert_eq!(rule.anchor_date().expect("valid"), date(2026, 1, 5));
        assert_eq!(rule.anchor_key().expect("valid").as_str(), "2026-01-05");
        let bad = weekly("2026-02-30");
        assert_eq!(
            bad.anchor_date().expect_err("not a date").first().kind,
            RuleDiagnosticKind::InvalidAnchor
        );
    }

    #[test]
    fn date_key_orders_chronologically() {
        let january = DateKey::from_date(date(2026, 1, 5));
        let february = DateKey::from_date(date(2026, 2, 5));
        let next_year = DateKey::from_date(date(2027, 1, 5));
        assert!(january < february);
        assert!(february < next_year);
        assert_eq!(january.to_string(), "2026-01-05");
    }

    #[test]
    fn bounded_parser_accepts_the_closed_vocabulary() {
        assert_eq!(
            BoundedCronParser.parse("@daily").expect("supported"),
            CronSchedule::Daily
        );
        assert_eq!(
            BoundedCronParser.parse("  @WEEKLY  ").expect("supported"),
            CronSchedule::Weekly
        );
        assert_eq!(
            BoundedCronParser.parse("@monthly").expect("supported"),
            CronSchedule::Monthly
        );
    }

    #[test]
    fn parse_offset_rejects_out_of_range_components() {
        assert!(parse_offset("+24:00").is_none());
        assert!(parse_offset("+01:60").is_none());
        assert!(parse_offset("+00:00:60").is_none());
        assert!(parse_offset("+00:0").is_none());
        assert!(parse_offset("+01:0a").is_none());
        assert_eq!(
            parse_offset("+23:59:59"),
            Some(UtcOffset::from_hms(23, 59, 59).expect("valid offset"))
        );
        assert_eq!(
            parse_offset("-08:00"),
            Some(UtcOffset::from_hms(-8, 0, 0).expect("valid offset"))
        );
    }
}