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
//! `[cycle_schedules.<schedule-id>]`: schedule definitions (WP01, T001–T006).
//!
//! # The record
//!
//! ```toml
//! [cycle_schedules.cs-1a2b3c4d5e6f7788]
//! name = "Platform sprint"
//! cadence = { kind = "weekly", interval = 2 }   # a cycle starts every 2 weeks
//! duration = { count = 2, unit = "weeks" }      # …and lasts 2 weeks
//! start_date = "2026-01-05"                     # the schedule's stable anchor
//! timezone = "+01:00"                           # explicit; never the host's
//! look_ahead = 2                                # generate/consider 2 ahead
//! state = "active"                              # active | paused | ended
//! ```
//!
//! The **map key** is the identity, not `name`: renaming a schedule must not break a
//! generated cycle, a snapshot, or an idempotency key (C-003), so `name` is a
//! mutable display label and the key is a [`CycleScheduleId`].
//!
//! # Nothing here is required to be present, and nothing is defaulted silently
//!
//! The whole section is optional and, when empty, is never written — a `tix.toml`
//! that has never held a schedule gains no key and round-trips byte-identically
//! (C-001). Inside a schedule the fields *are* required, but absence is refused by
//! [`validate_schedules`] with a diagnostic naming the field rather than filled in
//! with a plausible value: a cadence, a timezone or a start date this build invented
//! is a decision the file did not make, and C-005 refuses exactly that. Loading stays
//! lenient (the serde path matches the project/epic/initiative registries); it is
//! validation that refuses.
//!
//! # Validation is field-aware, and it happens before persistence
//!
//! Every message names the schedule and the field
//! (`` `cycle_schedules.<id>.cadence.interval` ``). The cadence's own rules are not
//! re-derived here — [`Cadence::to_rule`] hands them to the recurring-issues
//! mission's validator, so an interval out of range, a missing unit and a unit on a
//! family that has none are refused with the same wording every other surface
//! already uses.
//!
//! # Why the overlap rule is deliberately incomplete
//!
//! A cycle that lasts longer than the gap to the next cycle overlaps it. That is
//! decidable — and refused — when both spans are in the **same** unit family (days
//! and weeks are, since a week is seven days; months are their own family). A span
//! of months compared against one of days is *not* decidable without a calendar
//! (a month is 28 to 31 days), so it is **not** decided here: refusing
//! `cadence = { kind = "monthly" }` with `duration = { count = 2, unit = "weeks" }`
//! would refuse a perfectly sane schedule, and guessing the month length is the
//! silent normalization C-005 forbids. The undecidable case is accepted unchanged.

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

use indexmap::IndexMap;
use serde::{Deserialize, Serialize};

use crate::config::StableId;
use crate::error::{Result, TixError};
use crate::recurrence::rule::{IntervalUnit, RecurrenceRule, RuleKind, Timezone};

/// A stable cycle-schedule identity (`[cycle_schedules.<schedule-id>]` in `tix.toml`).
///
/// The fourth `StableId`, after `ProjectId`, `EpicId` and `InitiativeId`, with a
/// `cs-` prefix and the same rules through the same trait: never blank, never padded,
/// never carrying a TOML-structural character, and **never reused**. It is the
/// registry key, and generated cycles, cursors and snapshots all hang off it, so a
/// rename changes the display label only (C-003). A deleted schedule's id stays
/// spent, so nothing is silently rebound to a later record.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(try_from = "String", into = "String")]
pub struct CycleScheduleId(String);

impl StableId for CycleScheduleId {
    const PREFIX: &'static str = "cs-";
    const LABEL: &'static str = "cycle schedule id";
    const ARTICLE: &'static str = "a";

    fn from_validated(raw: String) -> Self {
        Self(raw)
    }

    fn as_str(&self) -> &str {
        &self.0
    }
}

impl CycleScheduleId {
    /// The longest id the registry accepts (see [`StableId::MAX_LEN`]).
    pub const MAX_LEN: usize = <Self as StableId>::MAX_LEN;

    /// Validate an explicit id; see [`StableId::new`].
    pub fn new(raw: &str) -> Result<Self> {
        <Self as StableId>::new(raw)
    }

    /// Allocate a new id, `cs-`-prefixed; see [`StableId::generate`] for the
    /// never-reused guarantee.
    #[must_use]
    pub fn generate() -> Self {
        <Self as StableId>::generate()
    }

    /// The id as written.
    #[must_use]
    pub fn as_str(&self) -> &str {
        <Self as StableId>::as_str(self)
    }
}

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

impl TryFrom<String> for CycleScheduleId {
    type Error = TixError;

    fn try_from(raw: String) -> Result<Self> {
        Self::new(&raw)
    }
}

impl From<CycleScheduleId> for String {
    fn from(id: CycleScheduleId) -> Self {
        id.0
    }
}

/// A schedule's lifecycle state (T004).
///
/// The state is *configuration*, not derived: it is what a pause/resume/end action
/// writes, and what generation reads before it does anything. `ended` is terminal —
/// a resumed terminal schedule is refused by name rather than silently accepted back
/// to `active`, so "ended" means ended.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum ScheduleState {
    /// The schedule generates and evaluates normally.
    #[default]
    Active,
    /// Explicitly paused: evaluation still reports, generation is refused until
    /// resumed.
    Paused,
    /// Explicitly ended: terminal, and generation is refused.
    Ended,
}

impl ScheduleState {
    /// The contract's spelling, used verbatim in payloads and diagnostics.
    pub const fn as_str(self) -> &'static str {
        match self {
            ScheduleState::Active => "active",
            ScheduleState::Paused => "paused",
            ScheduleState::Ended => "ended",
        }
    }

    /// Whether this state is terminal (no further transition out of it).
    pub const fn is_terminal(self) -> bool {
        matches!(self, ScheduleState::Ended)
    }
}

/// Metadata this build does not interpret, preserved verbatim.
///
/// Used at every level of a schedule record — the schedule itself, its `cadence` and
/// its `duration` — because each is a TOML table a newer `tix` could extend: a field
/// this build has never heard of must survive an edit-and-save round trip instead of
/// being dropped on the floor (T004, the same guarantee
/// `crate::roadmap::registry::InitiativeExtensions` gives the initiative record).
///
/// The one rule it cannot break: a preserved key must not **shadow** a built-in
/// field of the table it sits in. A file can never deliver such a key — serde matches
/// the known field first, so the map only ever holds the leftovers — but the public
/// write path can inject one, and `toml` serializes duplicate table keys without
/// complaining, so the write would *appear* to succeed while the next load failed on
/// a duplicate key. Refusing it is what keeps "an accepted change persists the
/// complete record" true.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(transparent)]
pub struct CycleScheduleExtensions(toml::Table);

impl CycleScheduleExtensions {
    /// Whether no unknown metadata is present.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// The number of preserved keys.
    #[must_use]
    pub fn len(&self) -> usize {
        self.0.len()
    }

    /// Look up a preserved key.
    #[must_use]
    pub fn get(&self, key: &str) -> Option<&toml::Value> {
        self.0.get(key)
    }

    /// The preserved keys, in canonical order.
    pub fn keys(&self) -> impl Iterator<Item = &str> {
        self.0.keys().map(String::as_str)
    }

    /// Iterate the preserved `(key, value)` pairs in canonical order.
    pub fn iter(&self) -> impl Iterator<Item = (&str, &toml::Value)> {
        self.0.iter().map(|(k, v)| (k.as_str(), v))
    }

    /// The underlying table, for a caller that must serialize it whole.
    #[must_use]
    pub fn table(&self) -> &toml::Table {
        &self.0
    }

    /// Preserve one `(key, value)` pair, returning the previous value if any.
    pub fn insert(&mut self, key: impl Into<String>, value: toml::Value) -> Option<toml::Value> {
        self.0.insert(key.into(), value)
    }
}

impl PartialEq for CycleScheduleExtensions {
    fn eq(&self, other: &Self) -> bool {
        toml::Value::Table(self.0.clone()).to_string()
            == toml::Value::Table(other.0.clone()).to_string()
    }
}

impl Eq for CycleScheduleExtensions {}

impl From<toml::Table> for CycleScheduleExtensions {
    fn from(table: toml::Table) -> Self {
        Self(table)
    }
}

/// A span of time that is exactly comparable to another span: whole days, or whole
/// calendar months.
///
/// Days and weeks share the `Days` variant because a week *is* seven days — exact by
/// definition. Months cannot join them: 28 to 31 days is a range, not a number, which
/// is the whole reason [`validate_schedules`] leaves a cross-family comparison
/// undecided instead of picking a length.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Span {
    /// A whole number of days.
    Days(u64),
    /// A whole number of calendar months.
    Months(u64),
}

impl Span {
    /// Whether a duration of `self` reaches **past** a step of `other`, when the two
    /// are comparable at all.
    ///
    /// Strictly past: a duration equal to the step is *back to back*, which is the
    /// canonical sprint — a two-week cycle on a two-week cadence — and refusing it
    /// would refuse the feature's primary use. Only a duration that genuinely reaches
    /// into the next cycle is an overlap.
    fn overlaps_next(self, other: Self) -> Option<bool> {
        match (self, other) {
            (Span::Days(step), Span::Days(duration)) => Some(step < duration),
            (Span::Months(step), Span::Months(duration)) => Some(step < duration),
            _ => None,
        }
    }
}

/// A schedule's repeating cadence: how often a cycle **starts**.
///
/// The family vocabulary is the recurring-issues mission's (`daily`, `weekly`,
/// `monthly`, `interval`), reused rather than restated so a user reads one set of
/// spellings across both features and the arithmetic has one owner.
///
/// Three fields, and each is refused by name when it is wrong rather than defaulted:
///
/// * `kind` — required. An absent family is refused: `weekly` is a decision the file
///   did not make (C-005).
/// * `interval` — the step multiplier, `1..=1000` (the shared bound). Optional;
///   absent means 1, which is the family's own documented default and not an
///   invention of this module.
/// * `unit` — only meaningful for the `interval` family, where it is **required**;
///   on any other family it is refused as unexpected, again through the shared rule.
///
/// `cron-like` is **not** accepted here even though the shared [`RuleKind`] has the
/// variant. Its bounded macro vocabulary (`@daily`, `@weekly`, `@monthly`) exists for
/// an *issue series* rule, where a cron-shaped expression was the reviewed need; a
/// cycle cadence is a calendar step by nature, and `kind = "weekly"` already says
/// `@weekly` without a macro. Accepting it would add a second spelling for the same
/// cadence plus an expression field to a configuration table, for no confirmed need —
/// so it is refused, by name, with that reason.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct Cadence {
    /// The cadence family. Required; refused when absent (`cadence.kind`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub kind: Option<RuleKind>,
    /// The step multiplier; absent means 1. Bounded `1..=1000` by the shared rule.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub interval: Option<u32>,
    /// The step unit; required exactly for the `interval` family.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub unit: Option<IntervalUnit>,
    /// Unknown metadata, preserved verbatim.
    #[serde(flatten)]
    pub extensions: CycleScheduleExtensions,
}

impl Cadence {
    /// A cadence of `kind` with no interval, unit or extensions.
    #[must_use]
    pub fn new(kind: RuleKind) -> Self {
        Self {
            kind: Some(kind),
            ..Self::default()
        }
    }

    /// Set the step multiplier.
    #[must_use]
    pub fn with_interval(mut self, interval: u32) -> Self {
        self.interval = Some(interval);
        self
    }

    /// Set the step unit.
    #[must_use]
    pub fn with_unit(mut self, unit: IntervalUnit) -> Self {
        self.unit = Some(unit);
        self
    }

    /// How long one step reaches, when that is exactly known.
    ///
    /// `None` means "not resolvable in this module" — an absent family, or the
    /// `cron-like` family this module refuses. It is never a guess.
    fn span(&self) -> Option<Span> {
        let interval = u64::from(self.interval.unwrap_or(1));
        match self.kind? {
            RuleKind::Daily => Some(Span::Days(interval)),
            RuleKind::Weekly => Some(Span::Days(interval.saturating_mul(7))),
            RuleKind::Monthly => Some(Span::Months(interval)),
            RuleKind::Interval => match self.unit? {
                IntervalUnit::Days => Some(Span::Days(interval)),
                IntervalUnit::Weeks => Some(Span::Days(interval.saturating_mul(7))),
                IntervalUnit::Months => Some(Span::Months(interval)),
            },
            RuleKind::CronLike => None,
        }
    }

    /// The recognized cadence fields, for the extension-shadow check.
    const KNOWN_FIELDS: &'static [&'static str] = &["kind", "interval", "unit"];

    /// This cadence as the shared [`RecurrenceRule`], anchored and timed by the
    /// owning schedule.
    ///
    /// The schedule owns the anchor and the timezone — one place each, so a stored
    /// cadence cannot carry a second, competing copy of either (a `cadence.anchor`
    /// key would otherwise sit in the preserved metadata and silently do nothing).
    /// Everything else is passed through unchanged, which is what makes the shared
    /// validator and the shared date arithmetic authoritative for a cycle schedule
    /// too: month-end re-anchoring, leap days, the interval bound and the
    /// daylight-saving refusal are not reimplemented here.
    ///
    /// `None` when no family is configured — there is nothing to validate yet, and
    /// the caller reports the absence itself.
    #[must_use]
    pub fn to_rule(&self, schedule: &CycleScheduleConfiguration) -> Option<RecurrenceRule> {
        Some(RecurrenceRule {
            kind: self.kind?,
            interval: self.interval,
            anchor: Some(schedule.start_date.clone()),
            timezone: schedule.timezone.clone(),
            expression: None,
            unit: self.unit,
            extensions: BTreeMap::new(),
        })
    }
}

/// How long one generated cycle lasts: a positive count in a unit.
///
/// Separate from [`Cadence`] because the two answer different questions — the cadence
/// is the gap between starts, the duration is the length of one cycle — and a
/// schedule is allowed to have them differ. What it is not allowed to do is overlap
/// itself, which [`validate_schedules`] refuses when the two spans are comparable.
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct CycleDuration {
    /// How many `unit`s one cycle lasts. Required positive; `0` is refused by name.
    pub count: u32,
    /// The length unit. Required; refused when absent (`duration.unit`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub unit: Option<IntervalUnit>,
    /// Unknown metadata, preserved verbatim.
    #[serde(flatten)]
    pub extensions: CycleScheduleExtensions,
}

impl CycleDuration {
    /// A duration of `count` `unit`s.
    #[must_use]
    pub fn new(count: u32, unit: IntervalUnit) -> Self {
        Self {
            count,
            unit: Some(unit),
            extensions: CycleScheduleExtensions::default(),
        }
    }

    /// How long this duration reaches, when that is exactly known.
    fn span(&self) -> Option<Span> {
        let count = u64::from(self.count);
        match self.unit? {
            IntervalUnit::Days => Some(Span::Days(count)),
            IntervalUnit::Weeks => Some(Span::Days(count.saturating_mul(7))),
            IntervalUnit::Months => Some(Span::Months(count)),
        }
    }

    /// The recognized duration fields, for the extension-shadow check.
    const KNOWN_FIELDS: &'static [&'static str] = &["count", "unit"];
}

/// A repeating cycle schedule (`[cycle_schedules.<schedule-id>]` in `tix.toml`).
///
/// The stable [`CycleScheduleId`] lives as the map key; `name` is a mutable display
/// label and is **not** the identity (C-003). Every field is optional *on disk* so
/// loading stays lenient and forward-compatible; [`validate_schedules`] is what
/// refuses an incomplete or incoherent record, naming the field.
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct CycleScheduleConfiguration {
    /// Display label. Required and unique within the registry (case-folded), so
    /// selection is unambiguous — but never the identity, which is the map key.
    pub name: String,
    /// How often a cycle starts. Required.
    pub cadence: Cadence,
    /// How long one cycle lasts. Required: an absent `duration` table, an absent
    /// `unit` and a non-positive `count` are each refused by name.
    pub duration: CycleDuration,
    /// The schedule's stable anchor, as a canonical `YYYY-MM-DD` calendar date.
    ///
    /// Required, and validated by the crate's one calendar authority
    /// (`crate::model::validate_date` — the same rule every other stored date
    /// passes, so a date cannot be real to one part of the crate and not to
    /// another). It is what makes the sequence deterministic: deriving an anchor
    /// from "today" would make the same configuration mean something different
    /// tomorrow, which is the silent guess C-009 escalates.
    pub start_date: String,
    /// The explicit timezone the schedule is expressed in.
    ///
    /// Required, and **never** the host default: a schedule evaluated against an
    /// ambient host zone is not reproducible on another machine. Only a fixed UTC
    /// offset (`+01:00`, `UTC`) is supported — a named IANA zone is refused because
    /// resolving its daylight-saving transitions needs a tzdb this crate does not
    /// depend on, and inventing a rule for an ambiguous local date is exactly what
    /// C-005 forbids. See `docs/cycle-schedule-dependency-review.md`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub timezone: Option<Timezone>,
    /// How many future cycles to consider (and, on confirmed generation, create)
    /// beyond the current one.
    ///
    /// Non-negative by construction (`u32`), and `0` — including "absent" — means
    /// *only the current cycle*: a schedule with no look-ahead generates nothing
    /// ahead, which is a coherent instruction rather than a missing one.
    pub look_ahead: u32,
    /// The lifecycle state. Absent means [`ScheduleState::Active`], the state a
    /// schedule is in until an explicit action changes it.
    pub state: ScheduleState,
    /// The generation position, written only by a confirmed generation or an explicit
    /// future adjustment (WP04/WP05). Absent until then, so a schedule that has never
    /// generated carries no cursor and a legacy file gains no key.
    ///
    /// It lives **beside the definition it belongs to**, the shape the recurring-issues
    /// mission uses for a series' cursor. See
    /// [`crate::cycle_schedule::identity::GenerationCursor`] for why the stored value is
    /// reconciled against the instances rather than trusted.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cursor: Option<crate::cycle_schedule::identity::GenerationCursor>,
    /// Unknown metadata, preserved verbatim.
    #[serde(flatten)]
    pub extensions: CycleScheduleExtensions,
}

/// The recognized schedule fields, for the extension-shadow check (T004).
pub const CYCLE_SCHEDULE_KNOWN_FIELDS: &[&str] = &[
    "name",
    "cadence",
    "duration",
    "start_date",
    "timezone",
    "look_ahead",
    "state",
    "cursor",
];

impl CycleScheduleConfiguration {
    /// The path prefix every diagnostic for this record uses.
    fn path(id: &str) -> String {
        format!("cycle_schedules.{id}")
    }

    /// Refuse a preserved key that would shadow a built-in field of `subject`.
    fn check_extensions(
        id: &str,
        subject: &str,
        known: &[&str],
        extensions: &CycleScheduleExtensions,
    ) -> Result<()> {
        for key in extensions.keys() {
            if known.contains(&key) {
                // The schedule's own extensions have no `subject`, and an empty one must
                // not render a `..` in the path: the message has to name a field a user
                // can find, which is the whole point of a field-aware diagnostic.
                let path = if subject.is_empty() {
                    format!("cycle_schedules.{id}.{key}")
                } else {
                    format!("cycle_schedules.{id}.{subject}.{key}")
                };
                return Err(TixError::Config(format!(
                    "`{path}` collides with a built-in field; rename the extension key"
                )));
            }
        }
        Ok(())
    }
}

/// Per-schedule validation for `[cycle_schedules.<schedule-id>]` (FR-001, C-001,
/// C-002, C-005, C-009).
///
/// The structural half is the other registries' own, through the shared helpers: a
/// valid stable [`CycleScheduleId`] key, a non-blank unique (case-folded) display
/// name, and a preserved extension key that must not shadow a built-in field.
///
/// The semantic half refuses, in this order, with a message naming the field:
///
/// 1. `start_date` that is not a real `YYYY-MM-DD` calendar date (the crate's one
///    calendar rule);
/// 2. an absent `timezone`, or one that is not a fixed UTC offset — a named zone and
///    a malformed offset are told apart, because the fix differs;
/// 3. an absent cadence family, the `cron-like` family (with its reason), and then
///    every rule the shared validator has for the family that *is* named;
/// 4. an absent duration unit, and a non-positive duration count;
/// 5. a duration that provably reaches past the next cycle's start.
///
/// Resolution of cross-record references is deliberately **not** here: whether a
/// generated cycle's schedule exists is a service/lint concern, so a schedule
/// removed by hand leaves a loadable, diagnosable file rather than an unloadable one.
#[allow(clippy::too_many_lines)]
pub fn validate_schedules(schedules: &IndexMap<String, CycleScheduleConfiguration>) -> Result<()> {
    let mut seen_names: HashSet<String> = HashSet::new();
    for (id, schedule) in schedules {
        crate::config::validate_registry_key::<CycleScheduleId>("cycle_schedules", id)?;
        crate::config::validate_display_name(
            "cycle_schedules",
            id,
            &schedule.name,
            "cycle schedule",
            &mut seen_names,
        )?;
        CycleScheduleConfiguration::check_extensions(
            id,
            "",
            CYCLE_SCHEDULE_KNOWN_FIELDS,
            &schedule.extensions,
        )?;
        let path = CycleScheduleConfiguration::path(id);

        // 1. The anchor. The crate's one calendar authority decides what a date is.
        if !crate::model::validate_date(&schedule.start_date) {
            return Err(TixError::Config(format!(
                "`{path}.start_date` (`{}`) must be a `YYYY-MM-DD` calendar date",
                schedule.start_date
            )));
        }

        // 2. The timezone, before the cadence: an ambiguous zone must be reported as
        //    a timezone problem, not as whatever the rule validator noticed first.
        match schedule.timezone.as_ref() {
            None => {
                return Err(TixError::Config(format!(
                    "`{path}.timezone` is required: give an explicit fixed UTC offset \
                     (`+01:00`, `UTC`); the host zone is never used implicitly"
                )));
            }
            Some(Timezone::Named(raw)) => {
                return Err(TixError::Config(format!(
                    "`{path}.timezone` (`{raw}`) is a named zone; only a fixed UTC offset is \
                     supported (daylight-saving transitions need a reviewed tzdb — see \
                     docs/cycle-schedule-dependency-review.md)"
                )));
            }
            Some(Timezone::Invalid(raw)) => {
                return Err(TixError::Config(format!(
                    "`{path}.timezone` (`{raw}`) is not a fixed UTC offset; use `±HH:MM` or `UTC`"
                )));
            }
            Some(Timezone::Fixed(_)) => {}
        }

        // 3. The cadence, through the shared validator.
        CycleScheduleConfiguration::check_extensions(
            id,
            "cadence",
            Cadence::KNOWN_FIELDS,
            &schedule.cadence.extensions,
        )?;
        if schedule.cadence.extensions.get("anchor").is_some()
            || schedule.cadence.extensions.get("timezone").is_some()
        {
            return Err(TixError::Config(format!(
                "`{path}.cadence` must not carry `anchor` or `timezone`; the schedule's own \
                 `start_date` and `timezone` are the single copy of each"
            )));
        }
        let Some(kind) = schedule.cadence.kind else {
            return Err(TixError::Config(format!(
                "`{path}.cadence.kind` is required: name the cadence family \
                 (`daily`, `weekly`, `monthly`, or `interval` with `interval` and `unit`)"
            )));
        };
        if kind == RuleKind::CronLike {
            return Err(TixError::Config(format!(
                "`{path}.cadence.kind` (`cron-like`) is not supported for a cycle schedule: the \
                 bounded cron vocabulary belongs to an issue series rule, and the same cadence \
                 is spelled `daily`, `weekly` or `monthly` here"
            )));
        }
        let rule = schedule
            .cadence
            .to_rule(schedule)
            .expect("the family was just checked to be present");
        if let Err(err) = rule.validate() {
            let diagnostic = err.first();
            return Err(TixError::Config(format!(
                "`{path}.cadence.{}`: {}",
                diagnostic.field, diagnostic.message
            )));
        }

        // 4. The duration.
        CycleScheduleConfiguration::check_extensions(
            id,
            "duration",
            CycleDuration::KNOWN_FIELDS,
            &schedule.duration.extensions,
        )?;
        if schedule.duration.unit.is_none() {
            return Err(TixError::Config(format!(
                "`{path}.duration.unit` is required: `days`, `weeks` or `months`"
            )));
        }
        // `count` is `u32` under `#[serde(default)]`, so an omitted key and a written
        // `count = 0` are the same effective value — and both are refused. The message
        // states the rule rather than quoting a value, because it cannot tell which of
        // the two the file held.
        if schedule.duration.count == 0 {
            return Err(TixError::Config(format!(
                "`{path}.duration.count` is required and must be a positive number of `{}`",
                schedule.duration.unit.map_or("units", |unit| unit.as_str())
            )));
        }

        // 5. The cadence/duration relationship, when it is decidable.
        if let (Some(step), Some(duration)) = (schedule.cadence.span(), schedule.duration.span())
            && step.overlaps_next(duration) == Some(true)
        {
            return Err(TixError::Config(format!(
                "`{path}.duration` reaches past `{path}.cadence`, so consecutive cycles would \
                 overlap; shorten the duration or widen the cadence"
            )));
        }
        // A span that is not comparable (months against days) is deliberately left
        // unrefused — see the module note on the overlap rule.

        // 6. The generation cursor, when the schedule has one. It is written by
        //    generation, so a hand-edited one is held to the same rules as the fields a
        //    user writes directly.
        if let Some(cursor) = schedule.cursor.as_ref() {
            CycleScheduleConfiguration::check_extensions(
                id,
                "cursor",
                crate::cycle_schedule::identity::GenerationCursor::KNOWN_FIELDS,
                &cursor.extensions,
            )?;
            if cursor.next_sequence == Some(0) {
                return Err(TixError::Config(format!(
                    "`{path}.cursor.next_sequence` must be at least 1; a schedule that has not \
                     generated carries no cursor at all"
                )));
            }
            if cursor.look_ahead_applied_through == Some(0) {
                return Err(TixError::Config(format!(
                    "`{path}.cursor.look_ahead_applied_through` must be at least 1"
                )));
            }
            if let Some(start) = cursor.next_start.as_deref()
                && !crate::model::validate_date(start)
            {
                return Err(TixError::Config(format!(
                    "`{path}.cursor.next_start` (`{start}`) must be a `YYYY-MM-DD` calendar date"
                )));
            }
            if let Some(key) = cursor.last_generated_key.as_ref()
                && key.schedule_id() != id
            {
                return Err(TixError::Config(format!(
                    "`{path}.cursor.last_generated_key` (`{key}`) belongs to schedule `{}`",
                    key.schedule_id()
                )));
            }
        }
    }
    Ok(())
}

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

    fn schedule(name: &str) -> CycleScheduleConfiguration {
        CycleScheduleConfiguration {
            name: name.to_string(),
            cadence: Cadence::new(RuleKind::Weekly),
            duration: CycleDuration::new(1, IntervalUnit::Weeks),
            start_date: "2026-01-05".to_string(),
            timezone: Some(Timezone::parse("+01:00")),
            look_ahead: 2,
            state: ScheduleState::Active,
            cursor: None,
            extensions: CycleScheduleExtensions::default(),
        }
    }

    fn registry(
        entries: impl IntoIterator<Item = (&'static str, CycleScheduleConfiguration)>,
    ) -> IndexMap<String, CycleScheduleConfiguration> {
        entries
            .into_iter()
            .map(|(id, schedule)| (id.to_string(), schedule))
            .collect()
    }

    fn refusal(schedules: &IndexMap<String, CycleScheduleConfiguration>) -> String {
        validate_schedules(schedules)
            .expect_err("expected a refusal")
            .to_string()
    }

    #[test]
    fn a_valid_schedule_is_accepted_and_round_trips() {
        let schedules = registry([("cs-1", schedule("Platform sprint"))]);
        validate_schedules(&schedules).expect("a well-formed schedule");

        let document = toml::to_string(&schedules).expect("serialize");
        let back: IndexMap<String, CycleScheduleConfiguration> =
            toml::from_str(&document).expect("deserialize");
        assert_eq!(back, schedules);
    }

    #[test]
    fn the_section_is_absent_until_a_schedule_exists() {
        let config = Config::default();
        assert!(config.cycle_schedules.is_empty());
        let rendered = toml::to_string(&config).expect("serialize");
        assert!(
            !rendered.contains("cycle_schedules"),
            "an empty registry must not write a section: {rendered}"
        );
    }

    #[test]
    fn a_legacy_named_cycle_registry_is_untouched() {
        let source = "[cycles.\"Cycle 1\"]\nstart_date = \"2026-01-01\"\n";
        let config: Config = toml::from_str(source).expect("a legacy file loads");
        assert!(config.cycles.contains_key("Cycle 1"));
        assert!(config.cycle_schedules.is_empty());
        let rendered = toml::to_string(&config).expect("serialize");
        assert!(rendered.contains("[cycles.\"Cycle 1\"]"));
    }

    #[test]
    fn the_anchor_must_be_a_real_calendar_date() {
        let mut broken = schedule("S");
        broken.start_date = "2025-02-29".into();
        assert!(refusal(&registry([("cs-1", broken)])).contains("start_date"));
    }

    #[test]
    fn the_timezone_is_required_and_never_implicit() {
        let mut missing = schedule("S");
        missing.timezone = None;
        let message = refusal(&registry([("cs-1", missing)]));
        assert!(message.contains("timezone"), "{message}");
        assert!(message.contains("never used implicitly"), "{message}");
    }

    #[test]
    fn a_named_zone_and_a_malformed_offset_are_told_apart() {
        let mut named = schedule("S");
        named.timezone = Some(Timezone::parse("Europe/Berlin"));
        let message = refusal(&registry([("cs-1", named)]));
        assert!(message.contains("named zone"), "{message}");

        let mut malformed = schedule("S");
        malformed.timezone = Some(Timezone::parse("+1:00"));
        let message = refusal(&registry([("cs-1", malformed)]));
        assert!(message.contains("not a fixed UTC offset"), "{message}");
    }

    #[test]
    fn an_absent_cadence_family_is_refused_not_defaulted() {
        let mut broken = schedule("S");
        broken.cadence = Cadence::default();
        let message = refusal(&registry([("cs-1", broken)]));
        assert!(message.contains("cadence.kind"), "{message}");
    }

    #[test]
    fn the_cron_like_family_is_refused_by_name() {
        let mut broken = schedule("S");
        broken.cadence = Cadence::new(RuleKind::CronLike);
        let message = refusal(&registry([("cs-1", broken)]));
        assert!(message.contains("cron-like"), "{message}");
    }

    #[test]
    fn cadence_rule_violations_come_from_the_shared_validator() {
        let mut no_unit = schedule("S");
        no_unit.cadence = Cadence::new(RuleKind::Interval).with_interval(2);
        assert!(refusal(&registry([("cs-1", no_unit)])).contains("unit"));

        let mut out_of_range = schedule("S");
        out_of_range.cadence = Cadence::new(RuleKind::Daily).with_interval(0);
        assert!(refusal(&registry([("cs-1", out_of_range)])).contains("interval"));

        let mut unexpected = schedule("S");
        unexpected.cadence = Cadence::new(RuleKind::Weekly).with_unit(IntervalUnit::Months);
        assert!(refusal(&registry([("cs-1", unexpected)])).contains("unit"));
    }

    #[test]
    fn the_duration_must_be_positive_and_typed() {
        let mut zero = schedule("S");
        zero.duration = CycleDuration::new(0, IntervalUnit::Weeks);
        let message = refusal(&registry([("cs-1", zero)]));
        assert!(message.contains("duration.count"), "{message}");

        let mut untyped = schedule("S");
        untyped.duration = CycleDuration {
            count: 2,
            unit: None,
            ..CycleDuration::default()
        };
        assert!(refusal(&registry([("cs-1", untyped)])).contains("duration.unit"));
    }

    #[test]
    fn a_provably_overlapping_duration_is_refused() {
        let mut overlapping = schedule("S");
        overlapping.cadence = Cadence::new(RuleKind::Weekly);
        overlapping.duration = CycleDuration::new(10, IntervalUnit::Days);
        let message = refusal(&registry([("cs-1", overlapping)]));
        assert!(message.contains("overlap"), "{message}");
    }

    #[test]
    fn an_undecidable_overlap_is_not_guessed_at() {
        // Two weeks inside a month is a sane schedule; a month has no fixed length,
        // so the comparison is left undecided rather than refused.
        let mut cross_family = schedule("S");
        cross_family.cadence = Cadence::new(RuleKind::Monthly);
        cross_family.duration = CycleDuration::new(2, IntervalUnit::Weeks);
        validate_schedules(&registry([("cs-1", cross_family)])).expect("accepted unchanged");

        // …and the same in the other direction.
        let mut other = schedule("S");
        other.cadence = Cadence::new(RuleKind::Interval)
            .with_interval(1)
            .with_unit(IntervalUnit::Months);
        other.duration = CycleDuration::new(90, IntervalUnit::Days);
        validate_schedules(&registry([("cs-1", other)])).expect("accepted unchanged");
    }

    #[test]
    fn back_to_back_cycles_are_the_canonical_sprint_not_an_overlap() {
        // A two-week cycle on a two-week cadence is what a sprint *is*; refusing it
        // would refuse the feature's primary use.
        let mut touching = schedule("S");
        touching.cadence = Cadence::new(RuleKind::Weekly);
        touching.duration = CycleDuration::new(1, IntervalUnit::Weeks);
        validate_schedules(&registry([("cs-1", touching)])).expect("adjacent cycles are fine");

        let mut longer_step = schedule("S");
        longer_step.cadence = Cadence::new(RuleKind::Daily).with_interval(30);
        longer_step.duration = CycleDuration::new(1, IntervalUnit::Months);
        validate_schedules(&registry([("cs-1", longer_step)])).expect("one month inside 30 days");
    }

    #[test]
    fn a_name_is_required_and_unique_case_folded() {
        let mut blank = schedule("   ");
        blank.name = "   ".into();
        assert!(refusal(&registry([("cs-1", blank)])).contains("name"));

        let duplicate = registry([
            ("cs-1", schedule("Platform")),
            ("cs-2", schedule("platform")),
        ]);
        assert!(refusal(&duplicate).contains("unique"));
    }

    #[test]
    fn the_registry_key_is_a_valid_schedule_id() {
        let bad = registry([("cs 1", schedule("S"))]);
        assert!(refusal(&bad).contains("cycle schedule id"));
    }

    #[test]
    fn unknown_metadata_inside_each_table_is_preserved_verbatim() {
        let mut extended = schedule("S");
        extended
            .extensions
            .insert("future_field", toml::Value::Integer(7));
        extended
            .cadence
            .extensions
            .insert("future_cadence", toml::Value::String("kept".into()));
        extended
            .duration
            .extensions
            .insert("future_duration", toml::Value::Boolean(true));
        let schedules = registry([("cs-1", extended)]);
        validate_schedules(&schedules).expect("unknown metadata is inert, not an error");

        let document = toml::to_string(&schedules).expect("serialize");
        let back: IndexMap<String, CycleScheduleConfiguration> =
            toml::from_str(&document).expect("deserialize");
        assert_eq!(back, schedules);
        assert_eq!(
            back["cs-1"].cadence.extensions.get("future_cadence"),
            Some(&toml::Value::String("kept".into()))
        );
    }

    #[test]
    fn a_preserved_key_may_not_shadow_a_built_in_field() {
        // The refusal must name a field a user can find: the schedule's own extension
        // map has no `subject`, and an empty one used to render `cycle_schedules.cs-1..name`.
        let mut shadowing = schedule("S");
        shadowing
            .extensions
            .insert("name", toml::Value::String("other".into()));
        let message = refusal(&registry([("cs-1", shadowing)]));
        assert!(message.contains("`cycle_schedules.cs-1.name`"), "{message}");
        assert!(!message.contains(".."), "a malformed path: {message}");

        let mut cadence_shadow = schedule("S");
        cadence_shadow
            .cadence
            .extensions
            .insert("interval", toml::Value::Integer(3));
        assert!(
            refusal(&registry([("cs-1", cadence_shadow)]))
                .contains("`cycle_schedules.cs-1.cadence.interval`")
        );

        let mut duration_shadow = schedule("S");
        duration_shadow
            .duration
            .extensions
            .insert("count", toml::Value::Integer(3));
        assert!(
            refusal(&registry([("cs-1", duration_shadow)]))
                .contains("`cycle_schedules.cs-1.duration.count`")
        );
    }

    #[test]
    fn the_cadence_may_not_carry_a_second_anchor_or_timezone() {
        for key in ["anchor", "timezone"] {
            let mut split = schedule("S");
            split
                .cadence
                .extensions
                .insert(key, toml::Value::String("elsewhere".into()));
            let message = refusal(&registry([("cs-1", split)]));
            assert!(message.contains("single copy"), "{key}: {message}");
        }
    }

    #[test]
    fn a_schedule_without_look_ahead_means_the_current_cycle_only() {
        let mut bare = schedule("S");
        bare.look_ahead = 0;
        validate_schedules(&registry([("cs-1", bare)])).expect("a coherent instruction");
    }

    #[test]
    fn the_state_defaults_to_active_and_ended_is_terminal() {
        let config: CycleScheduleConfiguration =
            toml::from_str("name = \"S\"\nstart_date = \"2026-01-01\"\ntimezone = \"UTC\"\n")
                .expect("loads");
        assert_eq!(config.state, ScheduleState::Active);
        assert!(!config.state.is_terminal());
        assert!(ScheduleState::Ended.is_terminal());
        assert_eq!(ScheduleState::Ended.as_str(), "ended");
    }

    #[test]
    fn the_cadence_anchors_on_the_schedule_not_on_itself() {
        let schedule = schedule("S");
        let rule = schedule.cadence.to_rule(&schedule).expect("a rule");
        assert_eq!(rule.anchor.as_deref(), Some("2026-01-05"));
        assert_eq!(rule.timezone, schedule.timezone);
        assert!(rule.expression.is_none());
    }

    #[test]
    fn a_generated_id_is_valid_under_the_shared_rules() {
        let id = CycleScheduleId::generate();
        assert!(id.as_str().starts_with("cs-"));
        CycleScheduleId::new(id.as_str()).expect("a generated id validates");
    }
}