Skip to main content

aidaemon_work/
schedule.rs

1//! Cron schedule parsing and next-run computation utilities.
2//!
3//! Extracted from the deprecated `scheduler` module. Used by health probes
4//! and evergreen goal scheduling.
5
6use chrono::{
7    DateTime, Datelike, FixedOffset, Local, LocalResult, NaiveDate, NaiveDateTime, Offset,
8    TimeZone, Timelike, Utc,
9};
10use croner::Cron;
11use regex::Regex;
12use std::sync::LazyLock;
13
14/// Parse a human-friendly schedule string into a 5-field cron expression.
15/// Supports natural shortcuts and raw cron pass-through.
16pub fn parse_schedule(input: &str) -> anyhow::Result<String> {
17    let input = input.trim().trim_end_matches(['.', '!', '?']).trim();
18    let now_local = Local::now();
19
20    // Simple keyword shortcuts
21    match input.to_lowercase().as_str() {
22        "hourly" => return Ok("0 * * * *".to_string()),
23        "daily" => return Ok("0 0 * * *".to_string()),
24        "weekly" => return Ok("0 0 * * 0".to_string()),
25        "monthly" => return Ok("0 0 1 * *".to_string()),
26        _ => {}
27    }
28
29    // "every Nm" / "every N minutes" / "each 5 minutes" / "1 each 5m"
30    let re_minutes =
31        Regex::new(r"(?i)^(?:\d+\s+)?(?:every|each)\s+(\d+)\s*(?:m|min|mins|minutes?)$")?;
32    if let Some(caps) = re_minutes.captures(input) {
33        let n: u32 = caps[1].parse()?;
34        if n == 0 || n > 59 {
35            anyhow::bail!("Minutes interval must be between 1 and 59");
36        }
37        return Ok(format!("*/{} * * * *", n));
38    }
39
40    // "every Nh" / "every N hours" / "each 2h" / "1 each 6 hours"
41    let re_hours = Regex::new(r"(?i)^(?:\d+\s+)?(?:every|each)\s+(\d+)\s*(?:h|hrs?|hours?)$")?;
42    if let Some(caps) = re_hours.captures(input) {
43        let n: u32 = caps[1].parse()?;
44        if n == 0 || n > 23 {
45            anyhow::bail!("Hours interval must be between 1 and 23");
46        }
47        return Ok(format!("0 */{} * * *", n));
48    }
49
50    // Multi-time variants (minutes must match):
51    // - "daily at 6am, 12pm, 6pm"
52    // - "every day at 6am, 12pm, 6pm"
53    // - "weekdays at 9am and 5pm"
54    // - "weekends at noon"
55    let re_daily_at = Regex::new(r"(?i)^daily\s+at\s+(.+)$")?;
56    if let Some(caps) = re_daily_at.captures(input) {
57        let times = parse_time_list(caps.get(1).unwrap().as_str())?;
58        return cron_for_recurring_times(times, "*");
59    }
60    let re_every_day_at = Regex::new(r"(?i)^(?:every\s+day|everyday)\s+at\s+(.+)$")?;
61    if let Some(caps) = re_every_day_at.captures(input) {
62        let times = parse_time_list(caps.get(1).unwrap().as_str())?;
63        return cron_for_recurring_times(times, "*");
64    }
65    let re_weekdays_at = Regex::new(r"(?i)^weekdays?\s+at\s+(.+)$")?;
66    if let Some(caps) = re_weekdays_at.captures(input) {
67        let times = parse_time_list(caps.get(1).unwrap().as_str())?;
68        return cron_for_recurring_times(times, "1-5");
69    }
70    let re_every_weekdays_at = Regex::new(r"(?i)^every\s+weekdays?\s+at\s+(.+)$")?;
71    if let Some(caps) = re_every_weekdays_at.captures(input) {
72        let times = parse_time_list(caps.get(1).unwrap().as_str())?;
73        return cron_for_recurring_times(times, "1-5");
74    }
75    let re_weekends_at = Regex::new(r"(?i)^weekends?\s+at\s+(.+)$")?;
76    if let Some(caps) = re_weekends_at.captures(input) {
77        let times = parse_time_list(caps.get(1).unwrap().as_str())?;
78        return cron_for_recurring_times(times, "0,6");
79    }
80    let re_every_weekends_at = Regex::new(r"(?i)^every\s+weekends?\s+at\s+(.+)$")?;
81    if let Some(caps) = re_every_weekends_at.captures(input) {
82        let times = parse_time_list(caps.get(1).unwrap().as_str())?;
83        return cron_for_recurring_times(times, "0,6");
84    }
85
86    // Specific named days: "Monday and Friday at 9am", "every Tuesday, Thursday at 3pm"
87    let re_specific_days_at = Regex::new(
88        r"(?i)^(?:every\s+|on\s+)?(?P<days>(?:monday|tuesday|wednesday|thursday|friday|saturday|sunday|mon|tue|wed|thu|fri|sat|sun)(?:\s*(?:,|\band\b|&)\s*(?:monday|tuesday|wednesday|thursday|friday|saturday|sunday|mon|tue|wed|thu|fri|sat|sun))*)\s+at\s+(?P<times>.+)$",
89    )?;
90    if let Some(caps) = re_specific_days_at.captures(input) {
91        let days = parse_day_list(caps.name("days").unwrap().as_str())?;
92        let times = parse_time_list(caps.name("times").unwrap().as_str())?;
93        let dow = days
94            .iter()
95            .map(|d| d.to_string())
96            .collect::<Vec<_>>()
97            .join(",");
98        return cron_for_recurring_times(times, &dow);
99    }
100
101    // A relative delay: "in 2h", "after 90 minutes", "in 1 hour 30 minutes".
102    // The whole input must be the delay; anything else is refused rather
103    // than guessed (see `parse_relative_duration`).
104    if let Some(duration) = parse_relative_duration(input)? {
105        let target = now_local + duration;
106        return Ok(one_shot_cron_from_local(target));
107    }
108
109    // "today at 11:09pm" / "tonight at 23:10" / "tomorrow at 9am -05:00" /
110    // "tomorrow at 9am Europe/Madrid": the owner's zone unless a numeric
111    // offset, UTC or an IANA zone name follows.
112    if let Some(target) = parse_day_time_with_optional_timezone(input, now_local)? {
113        if target <= now_local {
114            anyhow::bail!(
115                "Schedule time '{}' is in the past for system timezone {}.",
116                input,
117                system_timezone_display()
118            );
119        }
120        return Ok(one_shot_cron_from_local(target));
121    }
122
123    // Dynamic absolute datetime parser: RFC3339, ISO-like forms, and common
124    // date/time formats, in the owner's zone or a trailing zone token's.
125    if let Some(target) = parse_absolute_datetime(input, now_local)? {
126        if target <= now_local {
127            anyhow::bail!(
128                "Schedule time '{}' is in the past for system timezone {}.",
129                input,
130                system_timezone_display()
131            );
132        }
133        return Ok(one_shot_cron_from_local(target));
134    }
135
136    // Raw cron pass-through: validate with croner
137    let parts: Vec<&str> = input.split_whitespace().collect();
138    if parts.len() == 5 {
139        // Try to parse as cron
140        input
141            .parse::<Cron>()
142            .map_err(|e| anyhow::anyhow!("Invalid cron expression '{}': {}", input, e))?;
143        return Ok(input.to_string());
144    }
145
146    anyhow::bail!(
147        "Unrecognized schedule format '{}'. Use 'daily at 9am', 'every 5m', 'in 2 hours', 'tomorrow at 9am', an exact time like 2026-03-14T09:30:00-04:00 or '2026-03-14 09:30', or a 5-field cron expression. Interpreted in the owner's timezone {} unless a time names its zone (an IANA name like Europe/Madrid, a numeric offset or UTC).",
148        input,
149        system_timezone_display()
150    )
151}
152
153fn one_shot_cron_from_local(target: DateTime<Local>) -> String {
154    format!(
155        "{} {} {} {} *",
156        target.minute(),
157        target.hour(),
158        target.day(),
159        target.month()
160    )
161}
162
163/// A relative delay, only when the whole input is one: `in`/`after`, then one
164/// or more `<whole number> <unit>` terms (optionally joined by `and` or a
165/// comma). Units are a closed set of whole words: minutes, hours, days,
166/// weeks, with their usual short forms (`m`, `min`, `h`, `hr`, `d`, `w`).
167///
168/// `Ok(None)` when the input does not start with `in`/`after` and a number.
169/// When it does but cannot be fully read ("in 2 months", "in 10 days at
170/// 9am"), it is an error asking for a precise time: a guess there fired
171/// "in 2 months" after 2 minutes and dropped the "at 9am".
172fn parse_relative_duration(input: &str) -> anyhow::Result<Option<chrono::Duration>> {
173    static LEAD: LazyLock<Regex> =
174        LazyLock::new(|| Regex::new(r"(?i)^(?:in|after)\s+\d").expect("relative lead regex"));
175    static TERM: LazyLock<Regex> = LazyLock::new(|| {
176        Regex::new(r"(?i)^(\d+)\s*([a-z]+)(?:\s*,\s*|\s+and\s+|\s*)").expect("relative term regex")
177    });
178    if !LEAD.is_match(input) {
179        return Ok(None);
180    }
181    let refuse = || {
182        anyhow::anyhow!(
183            "'{input}' is not a delay this can read exactly. Give a delay in whole minutes, hours, days or weeks (e.g. 'in 90 minutes', 'in 3 days'), or an exact time like 2026-03-14T09:30:00-04:00."
184        )
185    };
186    let mut rest = input
187        .split_once(char::is_whitespace)
188        .map(|(_, rest)| rest.trim_start())
189        .unwrap_or("");
190    let mut total = chrono::Duration::zero();
191    while !rest.is_empty() {
192        let caps = TERM.captures(rest).ok_or_else(refuse)?;
193        let n: i64 = caps[1].parse().map_err(|_| refuse())?;
194        let unit = caps[2].to_ascii_lowercase();
195        let term = match unit.as_str() {
196            "m" | "min" | "mins" | "minute" | "minutes" => chrono::Duration::try_minutes(n),
197            "h" | "hr" | "hrs" | "hour" | "hours" => chrono::Duration::try_hours(n),
198            "d" | "day" | "days" => chrono::Duration::try_days(n),
199            "w" | "wk" | "wks" | "week" | "weeks" => chrono::Duration::try_weeks(n),
200            _ => None,
201        }
202        .ok_or_else(refuse)?;
203        total += term;
204        rest = &rest[caps.get(0).map_or(rest.len(), |m| m.end())..];
205    }
206    if total <= chrono::Duration::zero() {
207        return Err(refuse());
208    }
209    Ok(Some(total))
210}
211
212/// The zone a schedule's wall-clock time is read in. Stored in
213/// `goal_schedules.tz` as [`ScheduleZone::stored`]: `local` for the owner's
214/// zone, an IANA name, or a fixed offset (`UTC`, `+05:30`).
215#[derive(Clone, Copy, Debug, PartialEq)]
216pub enum ScheduleZone {
217    /// The owner's own clock (the system zone), with its daylight-saving rules.
218    Owner,
219    /// A numeric offset or UTC: no daylight saving.
220    Fixed(FixedOffset),
221    /// A named IANA zone such as `Europe/Madrid`, with its daylight-saving rules.
222    Named(chrono_tz::Tz),
223}
224
225impl ScheduleZone {
226    /// The calendar date `now` falls on in this zone.
227    fn date_at(&self, now: DateTime<Local>) -> NaiveDate {
228        match self {
229            Self::Owner => now.date_naive(),
230            Self::Fixed(offset) => now.with_timezone(offset).date_naive(),
231            Self::Named(tz) => now.with_timezone(tz).date_naive(),
232        }
233    }
234
235    /// The instant a wall-clock time in this zone names. A time the clocks
236    /// skip (the spring-forward gap) is an error naming it; a time they pass
237    /// twice (the fall-back hour) is the earlier of the two.
238    fn resolve(&self, naive: NaiveDateTime) -> anyhow::Result<DateTime<Local>> {
239        let resolved = match self {
240            // The owner's zone by its IANA rules when it has a name the
241            // system clock agrees with: the system clock's own lookup does
242            // not always report a fall-back time as ambiguous.
243            Self::Owner => match owner_tz() {
244                Some(tz) => tz
245                    .from_local_datetime(&naive)
246                    .map(|dt| dt.with_timezone(&Local)),
247                None => Local.from_local_datetime(&naive),
248            },
249            Self::Fixed(offset) => offset
250                .from_local_datetime(&naive)
251                .map(|dt| dt.with_timezone(&Local)),
252            Self::Named(tz) => tz
253                .from_local_datetime(&naive)
254                .map(|dt| dt.with_timezone(&Local)),
255        };
256        match resolved {
257            LocalResult::Single(dt) => Ok(dt),
258            LocalResult::Ambiguous(earlier, _) => Ok(earlier),
259            LocalResult::None => anyhow::bail!(
260                "{} does not exist in {}: the clocks skip it for daylight saving. Pick a time outside the skipped hour.",
261                naive.format("%Y-%m-%d %H:%M"),
262                self.name()
263            ),
264        }
265    }
266
267    /// The zone a stored `goal_schedules.tz` names. `local` is the owner's
268    /// zone; anything else is read as a zone token, so a value this cannot
269    /// resolve is an error, never a silent fallback to the owner's clock.
270    pub fn from_stored(tz: &str) -> anyhow::Result<Self> {
271        if tz.trim() == LOCAL_TZ {
272            return Ok(Self::Owner);
273        }
274        parse_schedule_zone(tz)
275            .map_err(|error| anyhow::anyhow!("Stored schedule time zone '{tz}': {error}"))
276    }
277
278    /// The `goal_schedules.tz` value for this zone.
279    pub fn stored(&self) -> String {
280        match self {
281            Self::Owner => LOCAL_TZ.to_string(),
282            Self::Fixed(offset) if offset.local_minus_utc() == 0 => "UTC".to_string(),
283            Self::Fixed(offset) => offset.to_string(),
284            Self::Named(tz) => tz.name().to_string(),
285        }
286    }
287
288    /// How the owner reads this zone beside a schedule's clock time
289    /// ("Europe/Madrid", "UTC+05:30"); `None` for the owner's own zone.
290    pub fn label(&self) -> Option<String> {
291        match self {
292            Self::Owner => None,
293            Self::Fixed(offset) if offset.local_minus_utc() == 0 => Some("UTC".to_string()),
294            Self::Fixed(offset) => Some(format!("UTC{offset}")),
295            Self::Named(tz) => Some(tz.name().to_string()),
296        }
297    }
298
299    fn name(&self) -> String {
300        match self {
301            Self::Owner => owner_zone_name().unwrap_or_else(system_timezone_display),
302            Self::Fixed(offset) => offset.to_string(),
303            Self::Named(tz) => tz.name().to_string(),
304        }
305    }
306}
307
308fn parse_day_time_with_optional_timezone(
309    input: &str,
310    now_local: DateTime<Local>,
311) -> anyhow::Result<Option<DateTime<Local>>> {
312    static RE: LazyLock<Regex> = LazyLock::new(|| {
313        Regex::new(
314            r"(?i)^(today|tonight|tomorrow)\s+at\s+(\d{1,2})(?::(\d{2}))?\s*(am|pm)?(?:\s+(\S+))?$",
315        )
316        .expect("day-time regex")
317    });
318    let Some(caps) = RE.captures(input) else {
319        return Ok(None);
320    };
321    let Some(day_kw) = caps.get(1).map(|m| m.as_str().to_ascii_lowercase()) else {
322        return Ok(None);
323    };
324    let Some((hour, minute)) = parse_time_with_offset_captures(&caps, 2, 3, 4) else {
325        return Ok(None);
326    };
327    let zone = match caps.get(5).map(|m| m.as_str().trim()) {
328        Some(token) => parse_schedule_zone(token)?,
329        None => ScheduleZone::Owner,
330    };
331    let today = zone.date_at(now_local);
332    let base_date = match day_kw.as_str() {
333        "tomorrow" => today.succ_opt().unwrap_or(today),
334        _ => today,
335    };
336    let Some(naive) = base_date.and_hms_opt(hour, minute, 0) else {
337        return Ok(None);
338    };
339    zone.resolve(naive).map(Some)
340}
341
342/// The `goal_schedules.tz` value for the owner's own zone.
343pub const LOCAL_TZ: &str = "local";
344
345/// A schedule as stored: its cron, read on the wall clock of `tz` (a
346/// `goal_schedules.tz` value, see [`ScheduleZone::stored`]).
347#[derive(Clone, Debug, PartialEq, Eq)]
348pub struct ParsedSchedule {
349    pub cron: String,
350    pub tz: String,
351}
352
353/// [`parse_schedule`], plus a recurring schedule with a trailing zone
354/// ("every weekday at 8am Europe/Madrid", "0 9 * * 1-5 America/Guayaquil"):
355/// its cron is then read on that zone's wall clock, daylight saving
356/// included. The zone follows the same rules as a one-time time's (an IANA
357/// name, a numeric offset or UTC; an abbreviation is refused). A one-time
358/// time already resolves its zone to an instant, so it is stored `local`.
359pub fn parse_schedule_with_zone(input: &str) -> anyhow::Result<ParsedSchedule> {
360    let first_error = match parse_schedule(input) {
361        Ok(cron) => {
362            return Ok(ParsedSchedule {
363                cron,
364                tz: LOCAL_TZ.to_string(),
365            });
366        }
367        Err(error) => error,
368    };
369    let trimmed = input.trim().trim_end_matches(['.', '!', '?']).trim();
370    let Some((rest, token)) = trimmed.rsplit_once(char::is_whitespace) else {
371        return Err(first_error);
372    };
373    let Ok(cron) = parse_schedule(rest.trim_end()) else {
374        return Err(first_error);
375    };
376    if is_one_shot_schedule(&cron) {
377        return Err(first_error);
378    }
379    let zone = parse_schedule_zone(token)?;
380    Ok(ParsedSchedule {
381        cron,
382        tz: zone.stored(),
383    })
384}
385
386/// The zone a time names after it: a numeric offset (`-05:00`, `+0530`),
387/// `UTC`/`GMT`/`Z`, or any IANA zone name (`Europe/Madrid`,
388/// `America/Guayaquil`; exact, or the same name in another letter case),
389/// read with that zone's daylight-saving rules. An abbreviation such as EST
390/// or PST is refused, not mapped to a fixed offset: "EST" in July is read as
391/// EDT by people and would fire an hour off. So are the IANA database's
392/// legacy names without a region (`EST`, `CET`, `Japan`): a real zone name
393/// has a `/`.
394fn parse_schedule_zone(token: &str) -> anyhow::Result<ScheduleZone> {
395    static NUMERIC: LazyLock<Regex> = LazyLock::new(|| {
396        Regex::new(r"^(?:UTC|GMT)?([+-])(\d{2})(?::?(\d{2}))?$").expect("numeric offset regex")
397    });
398    let token = token.trim();
399    let upper = token.to_ascii_uppercase();
400    if matches!(upper.as_str(), "UTC" | "GMT" | "Z") {
401        return Ok(ScheduleZone::Fixed(
402            FixedOffset::east_opt(0).expect("zero offset"),
403        ));
404    }
405    if let Some(caps) = NUMERIC.captures(&upper) {
406        let hours: i32 = caps[2].parse()?;
407        let minutes: i32 = caps.get(3).map_or(Ok(0), |m| m.as_str().parse())?;
408        if hours <= 23 && minutes <= 59 {
409            let seconds = hours * 3600 + minutes * 60;
410            let offset = if &caps[1] == "+" {
411                FixedOffset::east_opt(seconds)
412            } else {
413                FixedOffset::west_opt(seconds)
414            };
415            if let Some(offset) = offset {
416                return Ok(ScheduleZone::Fixed(offset));
417            }
418        }
419    }
420    if token.contains('/') {
421        if let Ok(tz) = token.parse::<chrono_tz::Tz>() {
422            return Ok(ScheduleZone::Named(tz));
423        }
424        if let Some(tz) = chrono_tz::TZ_VARIANTS
425            .iter()
426            .find(|tz| tz.name().eq_ignore_ascii_case(token))
427        {
428            return Ok(ScheduleZone::Named(*tz));
429        }
430        anyhow::bail!(
431            "'{token}' is not an IANA time zone name. Use a name like Europe/Madrid or America/New_York, a numeric offset like -05:00, or UTC."
432        );
433    }
434    let example = zone_abbreviation_example(&upper).unwrap_or("America/New_York or Europe/Madrid");
435    anyhow::bail!(
436        "Time zone '{token}' is not one this can resolve exactly: an abbreviation hides daylight saving. Name the IANA zone instead (e.g. {example}), give a numeric offset like -05:00 or UTC, or leave it out to use the owner's timezone ({}).",
437        owner_zone_name().unwrap_or_else(system_timezone_display)
438    )
439}
440
441/// An IANA zone a common abbreviation usually means, for the refusal's hint
442/// only: an abbreviation is ambiguous (IST, CST), so it is never resolved.
443fn zone_abbreviation_example(upper: &str) -> Option<&'static str> {
444    Some(match upper {
445        "ET" | "EST" | "EDT" => "America/New_York",
446        "CT" | "CST" | "CDT" => "America/Chicago",
447        "MT" | "MST" | "MDT" => "America/Denver",
448        "PT" | "PST" | "PDT" => "America/Los_Angeles",
449        "AKST" | "AKDT" => "America/Anchorage",
450        "HST" => "Pacific/Honolulu",
451        "BST" | "WET" | "WEST" => "Europe/London",
452        "CET" | "CEST" | "MET" | "MEST" => "Europe/Madrid",
453        "EET" | "EEST" => "Europe/Athens",
454        "MSK" => "Europe/Moscow",
455        "IST" => "Asia/Kolkata",
456        "JST" => "Asia/Tokyo",
457        "KST" => "Asia/Seoul",
458        "AEST" | "AEDT" => "Australia/Sydney",
459        "NZST" | "NZDT" => "Pacific/Auckland",
460        "ECT" => "America/Guayaquil",
461        _ => return None,
462    })
463}
464
465/// An exact date or date-time, read in the owner's zone, or in the zone a
466/// trailing token names (`2026-03-14 09:30 Europe/Madrid`). RFC 3339 carries
467/// its own offset.
468fn parse_absolute_datetime(
469    input: &str,
470    now_local: DateTime<Local>,
471) -> anyhow::Result<Option<DateTime<Local>>> {
472    if let Some(dt) = parse_absolute_datetime_in(input, ScheduleZone::Owner, now_local)? {
473        return Ok(Some(dt));
474    }
475    if let Some((rest, token)) = input.rsplit_once(char::is_whitespace) {
476        let rest = rest.trim_end();
477        // Only a trailing token after a date the parser reads is a zone; the
478        // token is then held to `parse_schedule_zone`, so "... EST" is refused.
479        // The shape is checked in UTC, which skips no time.
480        let probe = ScheduleZone::Fixed(FixedOffset::east_opt(0).expect("zero offset"));
481        if !rest.is_empty()
482            && parse_absolute_datetime_in(rest, probe, now_local).is_ok_and(|dt| dt.is_some())
483        {
484            let zone = parse_schedule_zone(token)?;
485            return parse_absolute_datetime_in(rest, zone, now_local);
486        }
487    }
488    Ok(None)
489}
490
491fn parse_absolute_datetime_in(
492    input: &str,
493    zone: ScheduleZone,
494    now_local: DateTime<Local>,
495) -> anyhow::Result<Option<DateTime<Local>>> {
496    if let Ok(dt) = DateTime::parse_from_rfc3339(input) {
497        return Ok(Some(dt.with_timezone(&Local)));
498    }
499
500    let dt_formats = [
501        "%Y-%m-%d %H:%M",
502        "%Y-%m-%d %H:%M:%S",
503        "%Y/%m/%d %H:%M",
504        "%Y/%m/%d %H:%M:%S",
505        "%m/%d/%Y %H:%M",
506        "%m/%d/%Y %I:%M %p",
507        "%Y-%m-%d %I:%M %p",
508        "%Y-%m-%d %I%p",
509        "%b %d %Y %H:%M",
510        "%b %d %Y %I:%M %p",
511        "%B %d %Y %H:%M",
512        "%B %d %Y %I:%M %p",
513    ];
514    for fmt in dt_formats {
515        if let Ok(naive) = NaiveDateTime::parse_from_str(input, fmt) {
516            return zone.resolve(naive).map(Some);
517        }
518    }
519
520    if let Some(dt) = parse_named_month_datetime(input, zone, now_local)? {
521        return Ok(Some(dt));
522    }
523
524    let date_formats = ["%Y-%m-%d", "%Y/%m/%d", "%m/%d/%Y"];
525    for fmt in date_formats {
526        if let Ok(date) = NaiveDate::parse_from_str(input, fmt)
527            && let Some(naive) = date.and_hms_opt(0, 0, 0)
528        {
529            return zone.resolve(naive).map(Some);
530        }
531    }
532
533    Ok(None)
534}
535
536fn parse_named_month_datetime(
537    input: &str,
538    zone: ScheduleZone,
539    now_local: DateTime<Local>,
540) -> anyhow::Result<Option<DateTime<Local>>> {
541    static RE: LazyLock<Regex> = LazyLock::new(|| {
542        Regex::new(
543            r"(?i)^(?:on\s+)?(?P<month>jan(?:uary)?|feb(?:ruary)?|mar(?:ch)?|apr(?:il)?|may|jun(?:e)?|jul(?:y)?|aug(?:ust)?|sep(?:t(?:ember)?)?|oct(?:ober)?|nov(?:ember)?|dec(?:ember)?)\s+(?P<day>\d{1,2})(?:st|nd|rd|th)?(?:,\s*(?P<year>\d{4}))?(?:\s+at\s+(?P<hour>\d{1,2})(?::(?P<minute>\d{2}))?\s*(?P<ampm>am|pm)?)?$",
544        )
545        .expect("named-month regex")
546    });
547    let Some(caps) = RE.captures(input.trim()) else {
548        return Ok(None);
549    };
550
551    let Some(month) = caps
552        .name("month")
553        .and_then(|m| parse_month_name(m.as_str()))
554    else {
555        return Ok(None);
556    };
557    let Some(day) = caps
558        .name("day")
559        .and_then(|m| m.as_str().parse::<u32>().ok())
560    else {
561        return Ok(None);
562    };
563    let explicit_year = caps
564        .name("year")
565        .and_then(|m| m.as_str().parse::<i32>().ok());
566
567    let mut hour: u32 = caps
568        .name("hour")
569        .and_then(|m| m.as_str().parse::<u32>().ok())
570        .unwrap_or(0);
571    let minute: u32 = caps
572        .name("minute")
573        .and_then(|m| m.as_str().parse::<u32>().ok())
574        .unwrap_or(0);
575    if let Some(ampm) = caps.name("ampm") {
576        let ampm = ampm.as_str().to_ascii_lowercase();
577        if ampm == "pm" && hour < 12 {
578            hour += 12;
579        } else if ampm == "am" && hour == 12 {
580            hour = 0;
581        }
582    }
583    if hour > 23 || minute > 59 {
584        return Ok(None);
585    }
586
587    let build = |year: i32| -> anyhow::Result<Option<DateTime<Local>>> {
588        let Some(naive) =
589            NaiveDate::from_ymd_opt(year, month, day).and_then(|d| d.and_hms_opt(hour, minute, 0))
590        else {
591            return Ok(None);
592        };
593        zone.resolve(naive).map(Some)
594    };
595    let year = explicit_year.unwrap_or_else(|| zone.date_at(now_local).year());
596    let candidate = build(year)?;
597    if explicit_year.is_none() && candidate.is_some_and(|dt| dt <= now_local) {
598        return build(year + 1);
599    }
600    Ok(candidate)
601}
602
603fn parse_month_name(month: &str) -> Option<u32> {
604    match month.trim().to_ascii_lowercase().as_str() {
605        "jan" | "january" => Some(1),
606        "feb" | "february" => Some(2),
607        "mar" | "march" => Some(3),
608        "apr" | "april" => Some(4),
609        "may" => Some(5),
610        "jun" | "june" => Some(6),
611        "jul" | "july" => Some(7),
612        "aug" | "august" => Some(8),
613        "sep" | "sept" | "september" => Some(9),
614        "oct" | "october" => Some(10),
615        "nov" | "november" => Some(11),
616        "dec" | "december" => Some(12),
617        _ => None,
618    }
619}
620
621fn parse_time_with_offset_captures(
622    caps: &regex::Captures,
623    hour_idx: usize,
624    minute_idx: usize,
625    ampm_idx: usize,
626) -> Option<(u32, u32)> {
627    let mut hour: u32 = caps.get(hour_idx)?.as_str().parse().ok()?;
628    let minute: u32 = caps
629        .get(minute_idx)
630        .map_or(Some(0), |m| m.as_str().parse().ok())?;
631    if let Some(ampm) = caps.get(ampm_idx) {
632        let ampm = ampm.as_str().to_ascii_lowercase();
633        if ampm == "pm" && hour < 12 {
634            hour += 12;
635        } else if ampm == "am" && hour == 12 {
636            hour = 0;
637        }
638    }
639    if hour > 23 || minute > 59 {
640        return None;
641    }
642    Some((hour, minute))
643}
644
645fn parse_time_list(raw: &str) -> anyhow::Result<Vec<(u32, u32)>> {
646    let raw = raw.trim();
647    if raw.is_empty() {
648        anyhow::bail!("Missing time after 'at'");
649    }
650
651    // Split on commas + "and" (case-insensitive); keep it permissive for LLM text.
652    let and_re = Regex::new(r"(?i)\s+and\s+")?;
653    let normalized = and_re.replace_all(raw, ",").replace('&', ",");
654    let parts: Vec<&str> = normalized
655        .split(',')
656        .map(str::trim)
657        .filter(|p| !p.is_empty())
658        .collect();
659    if parts.is_empty() {
660        anyhow::bail!("Missing time after 'at'");
661    }
662
663    let mut out = Vec::new();
664    for p in parts {
665        out.push(parse_time_token(p)?);
666    }
667    Ok(out)
668}
669
670fn parse_time_token(token: &str) -> anyhow::Result<(u32, u32)> {
671    let token = token.trim();
672    if token.is_empty() {
673        anyhow::bail!("Empty time token");
674    }
675    let lower = token.to_ascii_lowercase();
676    if lower == "noon" {
677        return Ok((12, 0));
678    }
679    if lower == "midnight" {
680        return Ok((0, 0));
681    }
682
683    let re = Regex::new(r"(?i)^(\d{1,2})(?::(\d{2}))?\s*(am|pm)?$")?;
684    let Some(caps) = re.captures(token) else {
685        anyhow::bail!("Unrecognized time token '{}'", token);
686    };
687
688    let mut hour: u32 = caps.get(1).unwrap().as_str().parse()?;
689    let minute: u32 = caps.get(2).map_or(Ok(0), |m| m.as_str().parse())?;
690    if let Some(ampm) = caps.get(3) {
691        let ampm = ampm.as_str().to_ascii_lowercase();
692        if ampm == "pm" && hour < 12 {
693            hour += 12;
694        } else if ampm == "am" && hour == 12 {
695            hour = 0;
696        }
697    }
698
699    if hour > 23 {
700        anyhow::bail!("Hour must be between 0 and 23");
701    }
702    if minute > 59 {
703        anyhow::bail!("Minute must be between 0 and 59");
704    }
705    Ok((hour, minute))
706}
707
708/// Parse a day name (or abbreviation) to cron day-of-week number (0=Sun..6=Sat).
709fn day_name_to_cron(name: &str) -> Option<u32> {
710    match name.trim().to_ascii_lowercase().as_str() {
711        "sun" | "sunday" => Some(0),
712        "mon" | "monday" => Some(1),
713        "tue" | "tuesday" => Some(2),
714        "wed" | "wednesday" => Some(3),
715        "thu" | "thursday" => Some(4),
716        "fri" | "friday" => Some(5),
717        "sat" | "saturday" => Some(6),
718        _ => None,
719    }
720}
721
722/// Parse a comma/and-separated day-name string into sorted cron day numbers.
723fn parse_day_list(raw: &str) -> anyhow::Result<Vec<u32>> {
724    let and_re = Regex::new(r"(?i)\s+and\s+")?;
725    let normalized = and_re.replace_all(raw, ",").replace('&', ",");
726    let parts: Vec<&str> = normalized
727        .split(',')
728        .map(str::trim)
729        .filter(|p| !p.is_empty())
730        .collect();
731    if parts.is_empty() {
732        anyhow::bail!("No day names found");
733    }
734    let mut days = Vec::new();
735    for p in parts {
736        let d =
737            day_name_to_cron(p).ok_or_else(|| anyhow::anyhow!("Unrecognized day name '{}'", p))?;
738        if !days.contains(&d) {
739            days.push(d);
740        }
741    }
742    days.sort_unstable();
743    Ok(days)
744}
745
746fn cron_for_recurring_times(times: Vec<(u32, u32)>, dow: &str) -> anyhow::Result<String> {
747    if times.is_empty() {
748        anyhow::bail!("Missing time after 'at'");
749    }
750    let minute = times[0].1;
751    if times.iter().any(|(_, m)| *m != minute) {
752        anyhow::bail!(
753            "Multiple times must share the same minute (e.g. 'daily at 6am, 12pm, 6pm'). For different minutes, create multiple schedules."
754        );
755    }
756    let mut hours: Vec<u32> = times.iter().map(|(h, _)| *h).collect();
757    hours.sort_unstable();
758    hours.dedup();
759    let hour_field = hours
760        .into_iter()
761        .map(|h| h.to_string())
762        .collect::<Vec<_>>()
763        .join(",");
764    Ok(format!("{} {} * * {}", minute, hour_field, dow))
765}
766
767/// Compute the next occurrence from a cron expression using croner.
768pub fn compute_next_run(cron_expr: &str) -> anyhow::Result<DateTime<Utc>> {
769    Ok(compute_next_run_local(cron_expr)?.with_timezone(&Utc))
770}
771
772/// Compute the next occurrence from a cron expression in system-local timezone.
773pub fn compute_next_run_local(cron_expr: &str) -> anyhow::Result<DateTime<Local>> {
774    let cron: Cron = cron_expr
775        .parse()
776        .map_err(|e| anyhow::anyhow!("Failed to parse cron '{}': {}", cron_expr, e))?;
777
778    cron.find_next_occurrence(&Local::now(), false)
779        .map_err(|e| anyhow::anyhow!("No next occurrence for '{}': {}", cron_expr, e))
780}
781
782/// Compute a fixed number of occurrences after an already-computed next run,
783/// in the zone `next` carries (wall-clock times stay put across a
784/// daylight-saving change).
785pub fn following_runs<Tz: TimeZone>(
786    cron_expr: &str,
787    next: &DateTime<Tz>,
788    count: usize,
789) -> anyhow::Result<Vec<DateTime<Tz>>> {
790    let cron: Cron = cron_expr
791        .parse()
792        .map_err(|e| anyhow::anyhow!("Failed to parse cron '{}': {}", cron_expr, e))?;
793    let mut cursor = next.clone();
794    let mut runs = Vec::with_capacity(count);
795    for _ in 0..count {
796        cursor = cron
797            .find_next_occurrence(&cursor, false)
798            .map_err(|e| anyhow::anyhow!("No next occurrence for '{}': {}", cron_expr, e))?;
799        runs.push(cursor.clone());
800    }
801    Ok(runs)
802}
803
804/// The runs an owner confirms before scheduled work is saved: `first` (the
805/// already-computed next run) and, for a recurring schedule, the ones after
806/// it, `count` in all. A one-time schedule has only its single time. A cron
807/// with no later occurrence lists what it has.
808pub fn upcoming_runs<Tz: TimeZone>(
809    cron_expr: &str,
810    first: &DateTime<Tz>,
811    one_shot: bool,
812    count: usize,
813) -> Vec<DateTime<Tz>> {
814    let mut runs = vec![first.clone()];
815    if !one_shot && count > 1 {
816        runs.extend(following_runs(cron_expr, first, count - 1).unwrap_or_default());
817    }
818    runs.truncate(count.max(1));
819    runs
820}
821
822#[cfg(test)]
823mod following_runs_tests {
824    use chrono::{Local, TimeZone};
825
826    #[test]
827    fn weekday_runs_skip_the_weekend_and_do_not_repeat_next() {
828        let friday = Local
829            .with_ymd_and_hms(2026, 11, 20, 8, 0, 0)
830            .single()
831            .unwrap();
832        let runs = super::following_runs("0 8 * * 1-5", &friday, 2).unwrap();
833        assert_eq!(runs[0].date_naive().to_string(), "2026-11-23");
834        assert_eq!(runs[1].date_naive().to_string(), "2026-11-24");
835        assert!(runs.iter().all(|run| run.time() == friday.time()));
836    }
837
838    /// US Eastern time (rules since 2007), test-only, so the daylight-saving
839    /// cases do not depend on the machine's zone and need no zone crate.
840    #[derive(Debug, Clone, Copy)]
841    struct Eastern;
842
843    impl Eastern {
844        fn nth_sunday(year: i32, month: u32, n: u32) -> chrono::NaiveDate {
845            use chrono::Datelike;
846            let first = chrono::NaiveDate::from_ymd_opt(year, month, 1).unwrap();
847            let to_sunday = (7 - first.weekday().num_days_from_sunday()) % 7;
848            first + chrono::Duration::days(i64::from(to_sunday + 7 * (n - 1)))
849        }
850
851        fn utc_offset(utc: &chrono::NaiveDateTime) -> chrono::FixedOffset {
852            use chrono::Datelike;
853            // 2:00 AM local both times: 7:00 UTC in March, 6:00 UTC in November.
854            let starts = Self::nth_sunday(utc.year(), 3, 2)
855                .and_hms_opt(7, 0, 0)
856                .unwrap();
857            let ends = Self::nth_sunday(utc.year(), 11, 1)
858                .and_hms_opt(6, 0, 0)
859                .unwrap();
860            let hours = if (starts..ends).contains(utc) { -4 } else { -5 };
861            chrono::FixedOffset::east_opt(hours * 3600).unwrap()
862        }
863    }
864
865    impl TimeZone for Eastern {
866        type Offset = chrono::FixedOffset;
867
868        fn from_offset(_offset: &chrono::FixedOffset) -> Self {
869            Eastern
870        }
871
872        fn offset_from_local_date(
873            &self,
874            local: &chrono::NaiveDate,
875        ) -> chrono::LocalResult<chrono::FixedOffset> {
876            self.offset_from_local_datetime(&local.and_hms_opt(0, 0, 0).unwrap())
877        }
878
879        fn offset_from_local_datetime(
880            &self,
881            local: &chrono::NaiveDateTime,
882        ) -> chrono::LocalResult<chrono::FixedOffset> {
883            // Daylight time first, so an ambiguous time lists the earlier instant first.
884            let fits: Vec<chrono::FixedOffset> = [-4, -5]
885                .into_iter()
886                .map(|hours| chrono::FixedOffset::east_opt(hours * 3600).unwrap())
887                .filter(|offset| {
888                    Self::utc_offset(
889                        &(*local - chrono::Duration::seconds(offset.local_minus_utc().into())),
890                    ) == *offset
891                })
892                .collect();
893            match fits.as_slice() {
894                [one] => chrono::LocalResult::Single(*one),
895                [earlier, later] => chrono::LocalResult::Ambiguous(*earlier, *later),
896                _ => chrono::LocalResult::None,
897            }
898        }
899
900        fn offset_from_utc_date(&self, utc: &chrono::NaiveDate) -> chrono::FixedOffset {
901            Self::utc_offset(&utc.and_hms_opt(0, 0, 0).unwrap())
902        }
903
904        fn offset_from_utc_datetime(&self, utc: &chrono::NaiveDateTime) -> chrono::FixedOffset {
905            Self::utc_offset(utc)
906        }
907    }
908
909    fn et(y: i32, mo: u32, d: u32, h: u32, mi: u32) -> chrono::DateTime<Eastern> {
910        Eastern
911            .with_ymd_and_hms(y, mo, d, h, mi, 0)
912            .single()
913            .unwrap()
914    }
915
916    /// Formatted as every owner-facing time is, as seen on Mon Nov 16, 2026.
917    fn shown(runs: &[chrono::DateTime<Eastern>]) -> Vec<String> {
918        let now = et(2026, 11, 16, 9, 17).fixed_offset();
919        runs.iter()
920            .map(|run| super::format_owner_time(&run.fixed_offset(), &now, "ET"))
921            .collect()
922    }
923
924    #[test]
925    fn upcoming_runs_keep_the_wall_clock_across_the_fall_back() {
926        // Daylight time ends Sun Nov 1, 2026: 9:00 AM stays 9:00 AM ET, and
927        // that day's run is 25 hours after the last one.
928        let runs = super::upcoming_runs("0 9 * * *", &et(2026, 10, 31, 9, 0), false, 3);
929        assert_eq!(
930            shown(&runs),
931            vec![
932                "Sat, Oct 31, 9:00 AM ET",
933                "Sun, Nov 1, 9:00 AM ET",
934                "Mon, Nov 2, 9:00 AM ET",
935            ]
936        );
937        assert_eq!(runs[0].offset().local_minus_utc(), -4 * 3600);
938        assert_eq!(runs[1].offset().local_minus_utc(), -5 * 3600);
939        assert_eq!(runs[1] - runs[0], chrono::Duration::hours(25));
940    }
941
942    #[test]
943    fn upcoming_runs_keep_the_wall_clock_across_the_spring_forward() {
944        // Daylight time starts Sun Mar 8, 2026: that day's run is 23 hours later.
945        let runs = super::upcoming_runs("30 8 * * *", &et(2026, 3, 7, 8, 30), false, 3);
946        assert_eq!(
947            shown(&runs),
948            vec![
949                "Sat, Mar 7, 8:30 AM ET",
950                "Sun, Mar 8, 8:30 AM ET",
951                "Mon, Mar 9, 8:30 AM ET",
952            ]
953        );
954        assert_eq!(runs[1] - runs[0], chrono::Duration::hours(23));
955    }
956
957    #[test]
958    fn a_wrong_cadence_shows_in_the_upcoming_runs() {
959        // "Every minute" where "every month" was meant reads as minutes apart.
960        let first = et(2026, 12, 1, 9, 0);
961        assert_eq!(
962            shown(&super::upcoming_runs("* * * * *", &first, false, 3)),
963            vec![
964                "Tue, Dec 1, 9:00 AM ET",
965                "Tue, Dec 1, 9:01 AM ET",
966                "Tue, Dec 1, 9:02 AM ET"
967            ]
968        );
969        assert_eq!(
970            shown(&super::upcoming_runs("0 9 1 * *", &first, false, 3)),
971            vec![
972                "Tue, Dec 1, 9:00 AM ET",
973                "Jan 1, 2027, 9:00 AM ET",
974                "Feb 1, 2027, 9:00 AM ET"
975            ]
976        );
977    }
978
979    #[test]
980    fn a_one_time_schedule_has_its_single_time() {
981        let first = et(2026, 11, 20, 9, 15);
982        let runs = super::upcoming_runs("15 9 20 11 *", &first, true, 3);
983        assert_eq!(shown(&runs), vec!["Fri, Nov 20, 9:15 AM ET"]);
984        assert_eq!(super::upcoming_runs("0 9 * * *", &first, false, 1).len(), 1);
985    }
986}
987
988/// The next run of `cron_expr` on the wall clock of a stored zone `tz`
989/// (`goal_schedules.tz`). `local` is exactly [`compute_next_run`]. In a
990/// named zone a fixed-time run that falls in the spring-forward gap runs at
991/// the first instant after the gap (8:30 in a 2:00-3:00 gap runs at 3:00),
992/// and one in the fall-back hour runs once, at the earlier instant.
993pub fn compute_next_run_in(cron_expr: &str, tz: &str) -> anyhow::Result<DateTime<Utc>> {
994    if tz.trim() == LOCAL_TZ {
995        return compute_next_run(cron_expr);
996    }
997    next_run_after_in(cron_expr, tz, Utc::now())
998}
999
1000/// The first run of `cron_expr` after `after`, on the wall clock of the
1001/// stored zone `tz` (see [`compute_next_run_in`]).
1002pub fn next_run_after_in(
1003    cron_expr: &str,
1004    tz: &str,
1005    after: DateTime<Utc>,
1006) -> anyhow::Result<DateTime<Utc>> {
1007    fn next<Z: TimeZone>(
1008        cron: &Cron,
1009        cron_expr: &str,
1010        after: DateTime<Z>,
1011    ) -> anyhow::Result<DateTime<Utc>> {
1012        cron.find_next_occurrence(&after, false)
1013            .map(|at| at.with_timezone(&Utc))
1014            .map_err(|e| anyhow::anyhow!("No next occurrence for '{}': {}", cron_expr, e))
1015    }
1016    let cron: Cron = cron_expr
1017        .parse()
1018        .map_err(|e| anyhow::anyhow!("Failed to parse cron '{}': {}", cron_expr, e))?;
1019    match ScheduleZone::from_stored(tz)? {
1020        ScheduleZone::Owner => next(&cron, cron_expr, after.with_timezone(&Local)),
1021        ScheduleZone::Fixed(offset) => next(&cron, cron_expr, after.with_timezone(&offset)),
1022        ScheduleZone::Named(zone) => next(&cron, cron_expr, after.with_timezone(&zone)),
1023    }
1024}
1025
1026/// [`upcoming_runs`] for a schedule stored in zone `tz`, computed on that
1027/// zone's wall clock and shown on the owner's.
1028pub fn upcoming_runs_in(
1029    cron_expr: &str,
1030    tz: &str,
1031    first: DateTime<Utc>,
1032    one_shot: bool,
1033    count: usize,
1034) -> Vec<DateTime<Local>> {
1035    fn runs<Z: TimeZone>(
1036        cron_expr: &str,
1037        first: DateTime<Z>,
1038        one_shot: bool,
1039        count: usize,
1040    ) -> Vec<DateTime<Local>> {
1041        upcoming_runs(cron_expr, &first, one_shot, count)
1042            .iter()
1043            .map(|at| at.with_timezone(&Local))
1044            .collect()
1045    }
1046    match ScheduleZone::from_stored(tz) {
1047        Ok(ScheduleZone::Fixed(offset)) => {
1048            runs(cron_expr, first.with_timezone(&offset), one_shot, count)
1049        }
1050        Ok(ScheduleZone::Named(zone)) => {
1051            runs(cron_expr, first.with_timezone(&zone), one_shot, count)
1052        }
1053        Ok(ScheduleZone::Owner) | Err(_) => {
1054            runs(cron_expr, first.with_timezone(&Local), one_shot, count)
1055        }
1056    }
1057}
1058
1059/// [`catch_up_window`] for a schedule stored in zone `tz`.
1060pub fn catch_up_window_in(
1061    cron_expr: &str,
1062    tz: &str,
1063    due: DateTime<Utc>,
1064) -> Option<chrono::Duration> {
1065    if tz.trim() == LOCAL_TZ {
1066        return catch_up_window(cron_expr, due);
1067    }
1068    let after = next_run_after_in(cron_expr, tz, due).ok()?;
1069    Some(window_for_period(after - due))
1070}
1071
1072fn window_for_period(period: chrono::Duration) -> chrono::Duration {
1073    (period / 2)
1074        .max(chrono::Duration::minutes(5))
1075        .min(chrono::Duration::hours(2))
1076}
1077
1078/// How late a recurring run may start and still be worth starting: half its
1079/// period, between 5 minutes and 2 hours. A daily 9:00 AM digest the daemon
1080/// was off for is not sent at 11 PM; an hourly check missed by a few
1081/// minutes still runs, and a busy daemon's slow tick never skips one. `None` when the cron has no later occurrence.
1082pub fn catch_up_window(cron_expr: &str, due: DateTime<Utc>) -> Option<chrono::Duration> {
1083    let cron: Cron = cron_expr.parse().ok()?;
1084    let due_local = due.with_timezone(&Local);
1085    let after = cron.find_next_occurrence(&due_local, false).ok()?;
1086    Some(window_for_period(after.with_timezone(&Utc) - due))
1087}
1088
1089#[cfg(test)]
1090mod catch_up_tests {
1091    use super::{catch_up_window, compute_next_run};
1092    use chrono::{Duration, Utc};
1093
1094    #[test]
1095    fn a_late_run_may_start_within_half_its_period_between_5_minutes_and_2_hours() {
1096        let window = |cron: &str| catch_up_window(cron, compute_next_run(cron).unwrap());
1097        assert_eq!(window("0 9 * * *"), Some(Duration::hours(2)));
1098        assert_eq!(window("0 * * * *"), Some(Duration::minutes(30)));
1099        assert_eq!(window("* * * * *"), Some(Duration::minutes(5)));
1100        assert_eq!(catch_up_window("not a cron", Utc::now()), None);
1101    }
1102}
1103
1104/// Human-readable system timezone label used in schedule confirmations: the
1105/// same short label every owner-facing time carries ([`owner_time`]).
1106pub fn system_timezone_display() -> String {
1107    owner_zone_label(Local::now().offset().local_minus_utc())
1108}
1109
1110/// The IANA name of the owner's time zone. The daemon runs on the owner's
1111/// machine, so the owner's zone is the system one: `TZ` when it names a zone,
1112/// else the system setting.
1113fn owner_zone_name() -> Option<String> {
1114    static NAME: LazyLock<Option<String>> = LazyLock::new(|| {
1115        std::env::var("TZ")
1116            .ok()
1117            .map(|tz| tz.trim().trim_start_matches(':').to_string())
1118            .filter(|tz| tz.contains('/') || tz.eq_ignore_ascii_case("UTC"))
1119            .or_else(|| iana_time_zone::get_timezone().ok())
1120    });
1121    NAME.clone()
1122}
1123
1124/// The owner's zone as an IANA zone, when its name is one and it keeps the
1125/// system clock's current offset (a `TZ` the name lookup misread is never
1126/// used over the clock itself).
1127fn owner_tz() -> Option<chrono_tz::Tz> {
1128    let tz = owner_zone_name()?.parse::<chrono_tz::Tz>().ok()?;
1129    let now = Utc::now();
1130    (now.with_timezone(&tz).offset().fix() == now.with_timezone(&Local).offset().fix())
1131        .then_some(tz)
1132}
1133
1134/// The owner's zone as a short label at a given UTC offset.
1135pub fn owner_zone_label(offset_secs: i32) -> String {
1136    zone_label(owner_zone_name().as_deref(), offset_secs)
1137}
1138
1139/// A short label for a zone: the everyday name for zones people say by
1140/// name ("ET", "PT"), else the offset ("UTC+5:30"). One label per zone all
1141/// year, so a time never reads "EST" in one message and "UTC-05:00" in the
1142/// next.
1143pub fn zone_label(iana: Option<&str>, offset_secs: i32) -> String {
1144    const NAMED: &[(&str, &str)] = &[
1145        ("America/New_York", "ET"),
1146        ("America/Detroit", "ET"),
1147        ("America/Toronto", "ET"),
1148        ("America/Indiana/Indianapolis", "ET"),
1149        ("America/Kentucky/Louisville", "ET"),
1150        ("US/Eastern", "ET"),
1151        ("America/Chicago", "CT"),
1152        ("America/Winnipeg", "CT"),
1153        ("US/Central", "CT"),
1154        ("America/Denver", "MT"),
1155        ("America/Edmonton", "MT"),
1156        ("America/Boise", "MT"),
1157        ("America/Phoenix", "MT"),
1158        ("US/Mountain", "MT"),
1159        ("America/Los_Angeles", "PT"),
1160        ("America/Vancouver", "PT"),
1161        ("US/Pacific", "PT"),
1162        ("America/Anchorage", "AKT"),
1163        ("Pacific/Honolulu", "HT"),
1164        ("UTC", "UTC"),
1165        ("Etc/UTC", "UTC"),
1166        ("Etc/GMT", "UTC"),
1167    ];
1168    if let Some(label) = iana.and_then(|name| {
1169        NAMED
1170            .iter()
1171            .find(|(zone, _)| *zone == name)
1172            .map(|(_, label)| *label)
1173    }) {
1174        return label.to_string();
1175    }
1176    if offset_secs == 0 {
1177        return "UTC".to_string();
1178    }
1179    let sign = if offset_secs < 0 { '-' } else { '+' };
1180    let minutes = offset_secs.unsigned_abs() / 60;
1181    match minutes % 60 {
1182        0 => format!("UTC{sign}{}", minutes / 60),
1183        rest => format!("UTC{sign}{}:{rest:02}", minutes / 60),
1184    }
1185}
1186
1187/// A time as the owner reads it, in their zone and one format: "2:39 PM ET"
1188/// today, "Thu, Nov 13, 2:39 PM ET" another day this year, and
1189/// "Jan 4, 2027, 2:39 PM ET" another year. Tool outputs keep the RFC 3339
1190/// value beside it where the model needs one.
1191pub fn owner_time<Tz: TimeZone>(at: &DateTime<Tz>) -> String {
1192    let at = at.with_timezone(&Local);
1193    let label = owner_zone_label(at.offset().local_minus_utc());
1194    format_owner_time(&at.fixed_offset(), &Local::now().fixed_offset(), &label)
1195}
1196
1197/// A moment in full, in the owner's zone, for the model's prompt: the
1198/// weekday and date it needs plus the same clock and zone label as
1199/// [`owner_time`] ("Thursday, November 12, 2026, 2:39 PM ET"), so replies
1200/// speak the owner's time instead of UTC.
1201pub fn owner_date_time_long<Tz: TimeZone>(at: &DateTime<Tz>) -> String {
1202    let at = at.with_timezone(&Local);
1203    let label = owner_zone_label(at.offset().local_minus_utc());
1204    format_owner_date_time_long(&at.fixed_offset(), &label)
1205}
1206
1207/// Testable core of [`owner_date_time_long`]: `at` in the owner's zone.
1208pub fn format_owner_date_time_long(at: &DateTime<FixedOffset>, zone_label: &str) -> String {
1209    format!(
1210        "{}, {} {zone_label}",
1211        at.format("%A, %B %-d, %Y"),
1212        at.format("%-I:%M %p")
1213    )
1214}
1215
1216/// [`owner_time`] for an RFC 3339 timestamp; `None` when it does not parse.
1217pub fn owner_time_rfc3339(value: &str) -> Option<String> {
1218    DateTime::parse_from_rfc3339(value)
1219        .ok()
1220        .map(|at| owner_time(&at))
1221}
1222
1223/// Testable core of [`owner_time`]: `at` and `now` in the owner's zone.
1224pub fn format_owner_time(
1225    at: &DateTime<FixedOffset>,
1226    now: &DateTime<FixedOffset>,
1227    zone_label: &str,
1228) -> String {
1229    let clock = at.format("%-I:%M %p");
1230    if at.date_naive() == now.with_timezone(at.offset()).date_naive() {
1231        format!("{clock} {zone_label}")
1232    } else if at.year() == now.year() {
1233        format!("{}, {clock} {zone_label}", at.format("%a, %b %-d"))
1234    } else {
1235        format!("{}, {clock} {zone_label}", at.format("%b %-d, %Y"))
1236    }
1237}
1238
1239/// Render a run time the way a person would say it: "today at 1:46 PM
1240/// (in 1 minute)", "tomorrow at 9:00 AM", "Friday at 9:00 AM", or
1241/// "on Jul 15 at 9:00 AM" for dates further out.
1242pub fn humanize_run_time(dt: DateTime<Local>) -> String {
1243    humanize_run_time_from(dt, Local::now())
1244}
1245
1246/// Testable core of [`humanize_run_time`] with an explicit "now".
1247pub fn humanize_run_time_from(dt: DateTime<Local>, now: DateTime<Local>) -> String {
1248    let time = dt.format("%-I:%M %p").to_string();
1249    let days_ahead = (dt.date_naive() - now.date_naive()).num_days();
1250    match days_ahead {
1251        0 => {
1252            let mins = (dt - now).num_minutes();
1253            if (1..60).contains(&mins) {
1254                let unit = if mins == 1 { "minute" } else { "minutes" };
1255                format!("today at {} (in {} {})", time, mins, unit)
1256            } else {
1257                format!("today at {}", time)
1258            }
1259        }
1260        1 => format!("tomorrow at {}", time),
1261        2..=6 => format!("{} at {}", dt.format("%A"), time),
1262        _ if dt.year() == now.year() => format!("on {} at {}", dt.format("%b %-d"), time),
1263        _ => format!("on {} at {}", dt.format("%b %-d, %Y"), time),
1264    }
1265}
1266
1267/// Heuristic: whether a cron expression looks like a one-shot absolute schedule.
1268///
1269/// This is intentionally conservative and should only be used as a fallback when
1270/// higher-confidence intent classification data is unavailable.
1271pub fn is_one_shot_schedule(cron_expr: &str) -> bool {
1272    let parts: Vec<&str> = cron_expr.split_whitespace().collect();
1273    if parts.len() != 5 {
1274        return false;
1275    }
1276
1277    let dom = parts[2];
1278    let month = parts[3];
1279    dom != "*" && month != "*" && !dom.contains('/') && !month.contains('/')
1280}
1281
1282#[cfg(test)]
1283mod tests {
1284    use super::*;
1285
1286    #[test]
1287    fn the_prompt_gets_the_full_date_in_the_owners_zone() {
1288        let eastern = FixedOffset::west_opt(5 * 3600).unwrap();
1289        let at = eastern.with_ymd_and_hms(2026, 11, 12, 13, 57, 0).unwrap();
1290        assert_eq!(
1291            format_owner_date_time_long(&at, "ET"),
1292            "Thursday, November 12, 2026, 1:57 PM ET"
1293        );
1294    }
1295
1296    #[test]
1297    fn owner_time_is_one_local_format_with_one_zone_label() {
1298        let eastern = FixedOffset::west_opt(5 * 3600).unwrap();
1299        let now = eastern.with_ymd_and_hms(2026, 11, 12, 9, 0, 0).unwrap();
1300        let today = eastern.with_ymd_and_hms(2026, 11, 12, 14, 39, 0).unwrap();
1301        let tomorrow = eastern.with_ymd_and_hms(2026, 11, 13, 14, 39, 0).unwrap();
1302        let next_year = eastern.with_ymd_and_hms(2027, 1, 4, 6, 0, 0).unwrap();
1303        assert_eq!(format_owner_time(&today, &now, "ET"), "2:39 PM ET");
1304        assert_eq!(
1305            format_owner_time(&tomorrow, &now, "ET"),
1306            "Fri, Nov 13, 2:39 PM ET"
1307        );
1308        assert_eq!(
1309            format_owner_time(&next_year, &now, "ET"),
1310            "Jan 4, 2027, 6:00 AM ET"
1311        );
1312    }
1313
1314    #[test]
1315    fn zone_label_names_common_zones_and_falls_back_to_the_offset() {
1316        assert_eq!(zone_label(Some("America/New_York"), -5 * 3600), "ET");
1317        // The label does not change with daylight saving time.
1318        assert_eq!(zone_label(Some("America/New_York"), -4 * 3600), "ET");
1319        assert_eq!(zone_label(Some("America/Los_Angeles"), -8 * 3600), "PT");
1320        assert_eq!(zone_label(Some("Asia/Kolkata"), 19_800), "UTC+5:30");
1321        assert_eq!(zone_label(Some("Europe/Berlin"), 3600), "UTC+1");
1322        assert_eq!(zone_label(None, -5 * 3600), "UTC-5");
1323        assert_eq!(zone_label(None, 0), "UTC");
1324    }
1325
1326    #[test]
1327    fn test_humanize_run_time() {
1328        let now = Local.with_ymd_and_hms(2026, 6, 11, 13, 45, 0).unwrap();
1329        let in_1m = Local.with_ymd_and_hms(2026, 6, 11, 13, 46, 0).unwrap();
1330        assert_eq!(
1331            humanize_run_time_from(in_1m, now),
1332            "today at 1:46 PM (in 1 minute)"
1333        );
1334        let later_today = Local.with_ymd_and_hms(2026, 6, 11, 18, 0, 0).unwrap();
1335        assert_eq!(humanize_run_time_from(later_today, now), "today at 6:00 PM");
1336        let tomorrow = Local.with_ymd_and_hms(2026, 6, 12, 9, 0, 0).unwrap();
1337        assert_eq!(humanize_run_time_from(tomorrow, now), "tomorrow at 9:00 AM");
1338        // 2026-06-15 is a Monday, 4 days out
1339        let monday = Local.with_ymd_and_hms(2026, 6, 15, 9, 0, 0).unwrap();
1340        assert_eq!(humanize_run_time_from(monday, now), "Monday at 9:00 AM");
1341        let next_month = Local.with_ymd_and_hms(2026, 7, 15, 9, 0, 0).unwrap();
1342        assert_eq!(
1343            humanize_run_time_from(next_month, now),
1344            "on Jul 15 at 9:00 AM"
1345        );
1346        let next_year = Local.with_ymd_and_hms(2027, 1, 5, 9, 0, 0).unwrap();
1347        assert_eq!(
1348            humanize_run_time_from(next_year, now),
1349            "on Jan 5, 2027 at 9:00 AM"
1350        );
1351    }
1352
1353    #[test]
1354    fn test_parse_schedule_keywords() {
1355        assert_eq!(parse_schedule("hourly").unwrap(), "0 * * * *");
1356        assert_eq!(parse_schedule("daily").unwrap(), "0 0 * * *");
1357        assert_eq!(parse_schedule("weekly").unwrap(), "0 0 * * 0");
1358        assert_eq!(parse_schedule("monthly").unwrap(), "0 0 1 * *");
1359    }
1360
1361    #[test]
1362    fn test_parse_schedule_every_minutes() {
1363        assert_eq!(parse_schedule("every 5m").unwrap(), "*/5 * * * *");
1364        assert_eq!(parse_schedule("every 15 minutes").unwrap(), "*/15 * * * *");
1365        assert_eq!(parse_schedule("every 1 min").unwrap(), "*/1 * * * *");
1366        assert_eq!(parse_schedule("each 5 minutes").unwrap(), "*/5 * * * *");
1367        assert_eq!(parse_schedule("each 5m").unwrap(), "*/5 * * * *");
1368        assert_eq!(parse_schedule("1 each 5m").unwrap(), "*/5 * * * *");
1369    }
1370
1371    #[test]
1372    fn test_parse_schedule_every_hours() {
1373        assert_eq!(parse_schedule("every 2h").unwrap(), "0 */2 * * *");
1374        assert_eq!(parse_schedule("every 4 hours").unwrap(), "0 */4 * * *");
1375        assert_eq!(parse_schedule("each 6h").unwrap(), "0 */6 * * *");
1376    }
1377
1378    #[test]
1379    fn test_parse_schedule_daily_at() {
1380        assert_eq!(parse_schedule("daily at 9am").unwrap(), "0 9 * * *");
1381        assert_eq!(parse_schedule("daily at 14:30").unwrap(), "30 14 * * *");
1382        assert_eq!(parse_schedule("daily at 2pm").unwrap(), "0 14 * * *");
1383        assert_eq!(parse_schedule("daily at 2:30pm").unwrap(), "30 14 * * *");
1384        assert_eq!(parse_schedule("daily at 12am").unwrap(), "0 0 * * *");
1385        assert_eq!(
1386            parse_schedule("daily at 6am, 12pm, 6pm").unwrap(),
1387            "0 6,12,18 * * *"
1388        );
1389        assert_eq!(
1390            parse_schedule("daily at 6, 12 and 6 pm").unwrap(),
1391            "0 6,12,18 * * *"
1392        );
1393        assert_eq!(
1394            parse_schedule("every day at 6, 12 and 6 pm").unwrap(),
1395            "0 6,12,18 * * *"
1396        );
1397        assert_eq!(
1398            parse_schedule("everyday at 6am, 12pm, 6pm").unwrap(),
1399            "0 6,12,18 * * *"
1400        );
1401    }
1402
1403    #[test]
1404    fn test_parse_schedule_weekdays() {
1405        assert_eq!(parse_schedule("weekdays at 8:30").unwrap(), "30 8 * * 1-5");
1406        assert_eq!(parse_schedule("weekdays at 9am").unwrap(), "0 9 * * 1-5");
1407        assert_eq!(
1408            parse_schedule("weekdays at 9am and 5pm").unwrap(),
1409            "0 9,17 * * 1-5"
1410        );
1411        assert_eq!(
1412            parse_schedule("every weekday at 9am and 5pm").unwrap(),
1413            "0 9,17 * * 1-5"
1414        );
1415    }
1416
1417    #[test]
1418    fn test_parse_schedule_weekends() {
1419        assert_eq!(parse_schedule("weekends at 10am").unwrap(), "0 10 * * 0,6");
1420        assert_eq!(
1421            parse_schedule("weekends at noon, 6pm").unwrap(),
1422            "0 12,18 * * 0,6"
1423        );
1424        assert_eq!(
1425            parse_schedule("every weekend at noon, 6pm").unwrap(),
1426            "0 12,18 * * 0,6"
1427        );
1428    }
1429
1430    #[test]
1431    fn test_parse_schedule_cron_passthrough() {
1432        assert_eq!(parse_schedule("0 9 * * 1-5").unwrap(), "0 9 * * 1-5");
1433        assert_eq!(parse_schedule("*/5 * * * *").unwrap(), "*/5 * * * *");
1434    }
1435
1436    #[test]
1437    fn test_parse_schedule_tomorrow_at() {
1438        let cron = parse_schedule("tomorrow at 9am").unwrap();
1439        let parts: Vec<&str> = cron.split_whitespace().collect();
1440        assert_eq!(parts.len(), 5);
1441        assert_eq!(parts[0], "0");
1442        assert_eq!(parts[1], "9");
1443        assert_eq!(parts[4], "*");
1444    }
1445
1446    #[test]
1447    fn test_parse_schedule_day_time_with_numeric_offset() {
1448        let offset = FixedOffset::west_opt(5 * 3600).unwrap();
1449        let now_there = Local::now().with_timezone(&offset);
1450        let target = now_there + chrono::Duration::minutes(30);
1451        let day_kw = if target.date_naive() == now_there.date_naive() {
1452            "today"
1453        } else {
1454            "tomorrow"
1455        };
1456        let input = format!("{} at {} -05:00.", day_kw, target.format("%I:%M%P"));
1457        let cron = parse_schedule(&input).unwrap();
1458        let local = target.with_timezone(&Local);
1459        assert_eq!(
1460            cron,
1461            format!(
1462                "{} {} {} {} *",
1463                local.minute(),
1464                local.hour(),
1465                local.day(),
1466                local.month()
1467            )
1468        );
1469    }
1470
1471    #[test]
1472    fn a_zone_abbreviation_is_refused_not_mapped_to_a_fixed_offset() {
1473        for input in [
1474            "tomorrow at 9am EST",
1475            "tomorrow at 9am PST",
1476            "tomorrow at 9am CET",
1477        ] {
1478            let error = parse_schedule(input).unwrap_err().to_string();
1479            assert!(error.contains("numeric offset"), "{input}: {error}");
1480        }
1481    }
1482
1483    #[test]
1484    fn test_parse_schedule_named_month_with_ordinal() {
1485        let cron = parse_schedule("on March 5th at 3pm").unwrap();
1486        let parts: Vec<&str> = cron.split_whitespace().collect();
1487        assert_eq!(parts.len(), 5);
1488        assert_eq!(parts[0], "0");
1489        assert_eq!(parts[1], "15");
1490        assert_eq!(parts[2], "5");
1491        assert_eq!(parts[3], "3");
1492    }
1493
1494    #[test]
1495    fn test_is_one_shot_schedule() {
1496        assert!(is_one_shot_schedule("15 9 12 3 *"));
1497        assert!(!is_one_shot_schedule("0 */6 * * *"));
1498        assert!(!is_one_shot_schedule("0 9 * * 1-5"));
1499    }
1500
1501    #[test]
1502    fn test_parse_schedule_invalid() {
1503        assert!(parse_schedule("never").is_err());
1504        assert!(parse_schedule("every 0m").is_err());
1505        assert!(parse_schedule("daily at 25:00").is_err());
1506    }
1507
1508    #[test]
1509    fn test_parse_schedule_zone_numeric_utc_owner_and_iana() {
1510        let seconds = |token: &str| match parse_schedule_zone(token).unwrap() {
1511            ScheduleZone::Fixed(offset) => offset.local_minus_utc(),
1512            other => panic!("{token}: {other:?}"),
1513        };
1514        assert_eq!(seconds("+05:30"), 5 * 3600 + 30 * 60);
1515        assert_eq!(seconds("-0400"), -4 * 3600);
1516        assert_eq!(seconds("UTC"), 0);
1517        assert_eq!(seconds("UTC-03:00"), -3 * 3600);
1518        // The owner's own zone named is that named zone (same rules), so a
1519        // schedule that names it keeps it if the owner's clock moves.
1520        if let Some(zone) = owner_zone_name().filter(|zone| zone.contains('/')) {
1521            match parse_schedule_zone(&zone).unwrap() {
1522                ScheduleZone::Named(tz) => assert!(tz.name().eq_ignore_ascii_case(&zone)),
1523                other => panic!("{zone}: {other:?}"),
1524            }
1525        }
1526        // Any other IANA zone, exact or in another letter case.
1527        for (token, name) in [
1528            ("Asia/Tokyo", "Asia/Tokyo"),
1529            ("america/guayaquil", "America/Guayaquil"),
1530            ("EUROPE/MADRID", "Europe/Madrid"),
1531        ] {
1532            match parse_schedule_zone(token).unwrap() {
1533                ScheduleZone::Named(tz) => assert_eq!(tz.name(), name),
1534                other => panic!("{token}: {other:?}"),
1535            }
1536        }
1537        assert!(parse_schedule_zone("EDT").is_err());
1538    }
1539
1540    /// Noon UTC on a fixed day, as the owner's clock: a fixed "now" so the
1541    /// zone tests do not depend on the date they run.
1542    fn fixed_now(y: i32, mo: u32, d: u32) -> DateTime<Local> {
1543        Utc.with_ymd_and_hms(y, mo, d, 12, 0, 0)
1544            .unwrap()
1545            .with_timezone(&Local)
1546    }
1547
1548    fn utc(input: &str, now: DateTime<Local>) -> String {
1549        parse_absolute_datetime(input, now)
1550            .unwrap()
1551            .unwrap_or_else(|| panic!("{input}: not read"))
1552            .with_timezone(&Utc)
1553            .to_rfc3339()
1554    }
1555
1556    #[test]
1557    fn a_named_zone_follows_its_daylight_saving_rules() {
1558        let now = fixed_now(2030, 1, 1);
1559        // Madrid is UTC+1 in winter and UTC+2 in summer.
1560        assert_eq!(
1561            utc("2030-01-15 09:00 Europe/Madrid", now),
1562            "2030-01-15T08:00:00+00:00"
1563        );
1564        assert_eq!(
1565            utc("2030-07-15 09:00 Europe/Madrid", now),
1566            "2030-07-15T07:00:00+00:00"
1567        );
1568        assert_eq!(
1569            utc("July 15, 2030 at 9am Europe/Madrid", now),
1570            "2030-07-15T07:00:00+00:00"
1571        );
1572        // Guayaquil keeps UTC-5 all year.
1573        assert_eq!(
1574            utc("2030-01-15 09:00 America/Guayaquil", now),
1575            "2030-01-15T14:00:00+00:00"
1576        );
1577        assert_eq!(
1578            utc("2030-07-15 09:00 America/Guayaquil", now),
1579            "2030-07-15T14:00:00+00:00"
1580        );
1581        assert_eq!(
1582            utc("2030-07-15 09:00 Asia/Tokyo", now),
1583            "2030-07-15T00:00:00+00:00"
1584        );
1585        // A fall-back time the clocks pass twice is the earlier one (CEST).
1586        assert_eq!(
1587            utc("2030-10-27 02:30 Europe/Madrid", now),
1588            "2030-10-27T00:30:00+00:00"
1589        );
1590        // The owner's zone and numeric offsets still read as before.
1591        assert_eq!(
1592            utc("2030-07-15 09:00 -05:00", now),
1593            "2030-07-15T14:00:00+00:00"
1594        );
1595        assert_eq!(
1596            utc("2030-07-15 09:00 UTC", now),
1597            "2030-07-15T09:00:00+00:00"
1598        );
1599    }
1600
1601    #[test]
1602    fn tomorrow_at_a_time_in_a_named_zone_uses_that_zones_calendar_and_offset() {
1603        let resolve = |input: &str, now: DateTime<Local>| {
1604            parse_day_time_with_optional_timezone(input, now)
1605                .unwrap()
1606                .unwrap()
1607                .with_timezone(&Utc)
1608                .to_rfc3339()
1609        };
1610        assert_eq!(
1611            resolve("tomorrow at 9am Europe/Madrid", fixed_now(2030, 1, 14)),
1612            "2030-01-15T08:00:00+00:00"
1613        );
1614        assert_eq!(
1615            resolve("tomorrow at 9am Europe/Madrid", fixed_now(2030, 7, 14)),
1616            "2030-07-15T07:00:00+00:00"
1617        );
1618        assert_eq!(
1619            resolve("tomorrow at 9am America/Guayaquil", fixed_now(2030, 7, 14)),
1620            "2030-07-15T14:00:00+00:00"
1621        );
1622        // 12:00 UTC on the 14th is already the 14th at 21:00 in Tokyo.
1623        assert_eq!(
1624            resolve("tomorrow at 9:30am Asia/Tokyo", fixed_now(2030, 7, 14)),
1625            "2030-07-15T00:30:00+00:00"
1626        );
1627    }
1628
1629    #[test]
1630    fn a_time_the_clocks_skip_in_a_named_zone_is_an_error_naming_it() {
1631        let now = fixed_now(2030, 1, 1);
1632        let error = parse_absolute_datetime("2030-03-31 02:30 Europe/Madrid", now)
1633            .unwrap_err()
1634            .to_string();
1635        assert!(error.contains("2030-03-31 02:30"), "{error}");
1636        assert!(error.contains("Europe/Madrid"), "{error}");
1637        assert!(error.contains("daylight saving"), "{error}");
1638        let error = parse_day_time_with_optional_timezone(
1639            "tomorrow at 2:30am Europe/Madrid",
1640            fixed_now(2030, 3, 30),
1641        )
1642        .unwrap_err()
1643        .to_string();
1644        assert!(error.contains("does not exist"), "{error}");
1645    }
1646
1647    fn at(y: i32, mo: u32, d: u32, h: u32, mi: u32) -> DateTime<Utc> {
1648        Utc.with_ymd_and_hms(y, mo, d, h, mi, 0).unwrap()
1649    }
1650
1651    /// The runs after `after` of a schedule stored in `tz`, in UTC.
1652    fn runs_after(cron: &str, tz: &str, after: DateTime<Utc>, count: usize) -> Vec<String> {
1653        let first = next_run_after_in(cron, tz, after).unwrap();
1654        upcoming_runs_in(cron, tz, first, false, count)
1655            .iter()
1656            .map(|run| run.with_timezone(&Utc).format("%a %m-%d %H:%M").to_string())
1657            .collect()
1658    }
1659
1660    #[test]
1661    fn a_recurring_schedule_with_a_zone_keeps_that_zone() {
1662        let parsed = |input: &str| parse_schedule_with_zone(input).unwrap();
1663        assert_eq!(
1664            parsed("every weekday at 8am Europe/Madrid"),
1665            ParsedSchedule {
1666                cron: "0 8 * * 1-5".to_string(),
1667                tz: "Europe/Madrid".to_string()
1668            }
1669        );
1670        let daily = parsed("daily at 9:30 america/guayaquil");
1671        assert_eq!(daily.cron, "30 9 * * *");
1672        assert_eq!(daily.tz, "America/Guayaquil");
1673        assert_eq!(parsed("0 9 * * 1-5 Asia/Tokyo").tz, "Asia/Tokyo");
1674        assert_eq!(parsed("weekdays at 9am +05:30").tz, "+05:30");
1675        assert_eq!(parsed("daily at 7am UTC").tz, "UTC");
1676        assert_eq!(parsed("every weekday at 8am").tz, LOCAL_TZ);
1677        let error = parse_schedule_with_zone("every weekday at 8am EST")
1678            .unwrap_err()
1679            .to_string();
1680        assert!(error.contains("America/New_York"), "{error}");
1681        assert!(parse_schedule_with_zone("every weekday at 8am Mars/Olympus").is_err());
1682        assert!(parse_schedule_with_zone("whenever the moon is full").is_err());
1683    }
1684
1685    #[test]
1686    fn weekday_runs_in_madrid_follow_its_clock_across_both_switches() {
1687        // Madrid moves to CEST on Sun Mar 31 2030 and back on Sun Oct 27.
1688        assert_eq!(
1689            runs_after("0 8 * * 1-5", "Europe/Madrid", at(2030, 3, 27, 12, 0), 3),
1690            vec!["Thu 03-28 07:00", "Fri 03-29 07:00", "Mon 04-01 06:00"]
1691        );
1692        assert_eq!(
1693            runs_after("0 8 * * 1-5", "Europe/Madrid", at(2030, 10, 24, 12, 0), 3),
1694            vec!["Fri 10-25 06:00", "Mon 10-28 07:00", "Tue 10-29 07:00"]
1695        );
1696        // A run in the skipped hour runs at the first instant after it; one
1697        // in the repeated hour runs once, at the earlier instant.
1698        assert_eq!(
1699            runs_after("30 2 * * *", "Europe/Madrid", at(2030, 3, 30, 12, 0), 2),
1700            vec!["Sun 03-31 01:00", "Mon 04-01 00:30"]
1701        );
1702        assert_eq!(
1703            runs_after("30 2 * * *", "Europe/Madrid", at(2030, 10, 26, 12, 0), 2),
1704            vec!["Sun 10-27 00:30", "Mon 10-28 01:30"]
1705        );
1706    }
1707
1708    #[test]
1709    fn daily_runs_in_guayaquil_keep_one_offset_all_year() {
1710        assert_eq!(
1711            runs_after("30 9 * * *", "America/Guayaquil", at(2030, 3, 30, 0, 0), 2),
1712            vec!["Sat 03-30 14:30", "Sun 03-31 14:30"]
1713        );
1714        assert_eq!(
1715            runs_after("30 9 * * *", "America/Guayaquil", at(2030, 10, 26, 0, 0), 2),
1716            vec!["Sat 10-26 14:30", "Sun 10-27 14:30"]
1717        );
1718        assert_eq!(
1719            runs_after("0 9 * * *", "+05:30", at(2030, 7, 1, 0, 0), 1),
1720            vec!["Mon 07-01 03:30"]
1721        );
1722    }
1723
1724    #[test]
1725    fn a_local_schedule_is_computed_exactly_as_before() {
1726        for cron in ["0 9 * * *", "0 8 * * 1-5", "15 9 12 3 *"] {
1727            assert_eq!(
1728                compute_next_run_in(cron, LOCAL_TZ).unwrap(),
1729                compute_next_run(cron).unwrap()
1730            );
1731            let due = at(2030, 7, 1, 9, 0);
1732            assert_eq!(
1733                catch_up_window_in(cron, LOCAL_TZ, due),
1734                catch_up_window(cron, due)
1735            );
1736        }
1737        assert_eq!(
1738            ScheduleZone::from_stored("local").unwrap(),
1739            ScheduleZone::Owner
1740        );
1741    }
1742
1743    #[test]
1744    fn a_stored_zone_this_cannot_read_is_an_error_not_the_owners_clock() {
1745        for tz in ["Mars/Olympus", "EST", ""] {
1746            assert!(ScheduleZone::from_stored(tz).is_err(), "{tz:?}");
1747            assert!(compute_next_run_in("0 9 * * *", tz).is_err(), "{tz:?}");
1748        }
1749        for tz in ["Europe/Madrid", "UTC", "+05:30", "-04:00"] {
1750            assert_eq!(ScheduleZone::from_stored(tz).unwrap().stored(), tz);
1751        }
1752    }
1753
1754    #[test]
1755    fn an_abbreviation_or_unknown_zone_after_a_time_is_refused_with_a_hint() {
1756        let now = fixed_now(2030, 1, 1);
1757        let error = parse_absolute_datetime("2030-07-15 09:00 EST", now)
1758            .unwrap_err()
1759            .to_string();
1760        assert!(error.contains("America/New_York"), "{error}");
1761        let error = parse_schedule("tomorrow at 9am CET")
1762            .unwrap_err()
1763            .to_string();
1764        assert!(error.contains("Europe/Madrid"), "{error}");
1765        // IANA's legacy region-less names are abbreviations too.
1766        assert!(parse_schedule_zone("EST").is_err());
1767        assert!(parse_schedule_zone("Japan").is_err());
1768        let error = parse_absolute_datetime("2030-07-15 09:00 Europe/Atlantis", now)
1769            .unwrap_err()
1770            .to_string();
1771        assert!(error.contains("not an IANA time zone"), "{error}");
1772        assert!(parse_schedule("tomorrow at 9am Mars/Olympus").is_err());
1773    }
1774
1775    #[test]
1776    fn test_parse_schedule_relative_duration_phrase() {
1777        let before = Local::now();
1778        let cron = parse_schedule("in 1 hour 30 minutes").unwrap();
1779        let expected = before + chrono::Duration::minutes(90);
1780        let parts: Vec<&str> = cron.split_whitespace().collect();
1781        assert_eq!(parts[1], expected.hour().to_string());
1782        for input in [
1783            "in 2h30m",
1784            "after 90 minutes",
1785            "in 1 hour, 30 min",
1786            "in 1 day and 2 hours",
1787            "in 3 weeks",
1788        ] {
1789            assert!(parse_schedule(input).is_ok(), "{input}");
1790        }
1791    }
1792
1793    #[test]
1794    fn a_relative_delay_it_cannot_fully_read_is_refused_not_guessed() {
1795        // "2 months" once read as 2 minutes ("m"), and "at 9am" was dropped.
1796        for input in [
1797            "in 2 months",
1798            "in 10 days at 9am",
1799            "in 1 year",
1800            "in 5 minutes or so",
1801            "after 0 minutes",
1802        ] {
1803            let error = parse_schedule(input).unwrap_err().to_string();
1804            assert!(error.contains("not a delay"), "{input}: {error}");
1805        }
1806    }
1807
1808    #[test]
1809    fn test_parse_schedule_absolute_datetime_iso() {
1810        let target = Local::now() + chrono::Duration::hours(2);
1811        let input = target.format("%Y-%m-%d %H:%M").to_string();
1812        let cron = parse_schedule(&input).unwrap();
1813        let parts: Vec<&str> = cron.split_whitespace().collect();
1814        assert_eq!(parts.len(), 5);
1815        assert_eq!(parts[0], target.minute().to_string());
1816        assert_eq!(parts[1], target.hour().to_string());
1817    }
1818
1819    #[test]
1820    fn test_system_timezone_display_non_empty() {
1821        assert!(!system_timezone_display().is_empty());
1822    }
1823
1824    #[test]
1825    fn test_compute_next_run() {
1826        let next = compute_next_run("* * * * *").unwrap();
1827        assert!(next > Utc::now());
1828    }
1829
1830    #[test]
1831    fn test_compute_next_run_local() {
1832        let next = compute_next_run_local("* * * * *").unwrap();
1833        assert!(next > Local::now());
1834    }
1835
1836    #[test]
1837    fn test_parse_schedule_specific_days() {
1838        assert_eq!(
1839            parse_schedule("Monday and Friday at 3pm").unwrap(),
1840            "0 15 * * 1,5"
1841        );
1842        assert_eq!(
1843            parse_schedule("every Monday and Friday at 9am").unwrap(),
1844            "0 9 * * 1,5"
1845        );
1846        assert_eq!(
1847            parse_schedule("every Tuesday, Thursday at 2pm").unwrap(),
1848            "0 14 * * 2,4"
1849        );
1850    }
1851}