Skip to main content

dateoxide_core/
relative.rs

1use std::borrow::Cow;
2
3use crate::fast_path::{days_in_month, parse_time_str, resolve_time_only_date};
4use crate::locale::{
5    fold_diacritics, CompiledLocale, LocaleRegistry, RelativeAffix, RelativeSpec, TimeUnit,
6};
7use crate::settings::{PartOfDay, Period, PreferDatesFrom, Settings};
8use chrono::{Datelike, Duration, NaiveDate, NaiveDateTime, NaiveTime};
9
10#[derive(Debug, Clone)]
11pub struct RelativeMatch {
12    pub naive: NaiveDateTime,
13    pub period: Period,
14    pub locale: String,
15    pub has_time: bool,
16    pub parts: Vec<&'static str>,
17    pub part_of_day: Option<PartOfDay>,
18}
19
20/// Calendar-accurate offset addition (matches dateutil.relativedelta semantics for months/years).
21pub fn apply_relative_offset(
22    base: NaiveDateTime,
23    sign: i8,
24    amount: f64,
25    unit: TimeUnit,
26) -> Option<NaiveDateTime> {
27    if !amount.is_finite() || amount < 0.0 || amount > 10_000_000.0 {
28        return None;
29    }
30    let signed = if sign < 0 { -amount } else { amount };
31    let dt = match unit {
32        TimeUnit::Second => {
33            let ms = (signed * 1000.0).round() as i64;
34            base.checked_add_signed(Duration::milliseconds(ms))?
35        }
36        TimeUnit::Minute => {
37            let ms = (signed * 60_000.0).round() as i64;
38            base.checked_add_signed(Duration::milliseconds(ms))?
39        }
40        TimeUnit::Hour => {
41            let ms = (signed * 3_600_000.0).round() as i64;
42            base.checked_add_signed(Duration::milliseconds(ms))?
43        }
44        TimeUnit::Day => {
45            if amount > 3_650_000.0 {
46                return None;
47            }
48            let ms = (signed * 86_400_000.0).round() as i64;
49            base.checked_add_signed(Duration::milliseconds(ms))?
50        }
51        TimeUnit::Week => {
52            if amount > 520_000.0 {
53                return None;
54            }
55            let ms = (signed * 7.0 * 86_400_000.0).round() as i64;
56            base.checked_add_signed(Duration::milliseconds(ms))?
57        }
58        TimeUnit::Fortnight => {
59            if amount > 260_000.0 {
60                return None;
61            }
62            let ms = (signed * 14.0 * 86_400_000.0).round() as i64;
63            base.checked_add_signed(Duration::milliseconds(ms))?
64        }
65        TimeUnit::Month => {
66            if amount > 120_000.0 {
67                return None;
68            }
69            if signed.fract().abs() > 1e-6 {
70                let whole_months = signed.trunc() as i32;
71                let frac_days = (signed.fract() * 30.0).round() as i64;
72                let shifted = if whole_months != 0 {
73                    add_months(base, whole_months)?
74                } else {
75                    base
76                };
77                shifted.checked_add_signed(Duration::days(frac_days))?
78            } else {
79                add_months(base, signed.round() as i32)?
80            }
81        }
82        TimeUnit::Year => {
83            if amount > 9_999.0 {
84                return None;
85            }
86            add_months(base, (signed * 12.0).round() as i32)?
87        }
88        TimeUnit::Decade => {
89            if amount > 1_000.0 {
90                return None;
91            }
92            add_months(base, (signed * 120.0).round() as i32)?
93        }
94        TimeUnit::Century => {
95            if amount > 100.0 {
96                return None;
97            }
98            add_months(base, (signed * 1200.0).round() as i32)?
99        }
100    };
101    if !(1..=9999).contains(&dt.year()) {
102        return None;
103    }
104    Some(dt)
105}
106
107fn add_months(base: NaiveDateTime, delta_months: i32) -> Option<NaiveDateTime> {
108    let total_months = (base.year() * 12 + (base.month() as i32 - 1)) + delta_months;
109    let new_year = total_months.div_euclid(12);
110    let new_month = (total_months.rem_euclid(12) + 1) as u32;
111    let max_day = days_in_month(new_year, new_month);
112    let new_day = base.day().min(max_day);
113    let nd = NaiveDate::from_ymd_opt(new_year, new_month, new_day)?;
114    Some(nd.and_time(base.time()))
115}
116
117#[inline]
118fn is_time_unit(unit: TimeUnit) -> bool {
119    matches!(unit, TimeUnit::Hour | TimeUnit::Minute | TimeUnit::Second)
120}
121
122fn period_for_unit(unit: TimeUnit) -> Period {
123    match unit {
124        TimeUnit::Year | TimeUnit::Decade | TimeUnit::Century => Period::Year,
125        TimeUnit::Month => Period::Month,
126        TimeUnit::Week => Period::Week,
127        _ => Period::Day,
128    }
129}
130
131fn parts_for_relative(has_time: bool, unit: Option<TimeUnit>) -> Vec<&'static str> {
132    let time_unit = matches!(
133        unit,
134        Some(TimeUnit::Hour | TimeUnit::Minute | TimeUnit::Second)
135    );
136    if has_time || time_unit {
137        vec!["year", "month", "day", "time"]
138    } else {
139        vec!["year", "month", "day"]
140    }
141}
142
143fn time_for_hour_anchor(hour: u8, settings: &Settings) -> (NaiveTime, Option<PartOfDay>) {
144    match hour {
145        3 | 6 => (settings.parts_of_day.time_for(PartOfDay::EarlyMorning), Some(PartOfDay::EarlyMorning)),
146        9 => (settings.parts_of_day.time_for(PartOfDay::Morning), Some(PartOfDay::Morning)),
147        15 => (settings.parts_of_day.time_for(PartOfDay::Afternoon), Some(PartOfDay::Afternoon)),
148        18 => (settings.parts_of_day.time_for(PartOfDay::Evening), Some(PartOfDay::Evening)),
149        20 => (settings.parts_of_day.time_for(PartOfDay::Night), Some(PartOfDay::Night)),
150        12 => (NaiveTime::from_hms_opt(12, 0, 0).unwrap(), None),
151        0 => (NaiveTime::from_hms_opt(0, 0, 0).unwrap(), None),
152        h => (NaiveTime::from_hms_opt(h as u32, 0, 0).unwrap(), None),
153    }
154}
155
156fn select_relative_spec(specs: &[RelativeSpec], pref: PreferDatesFrom) -> RelativeSpec {
157    if specs.len() == 1 {
158        return specs[0];
159    }
160    match pref {
161        PreferDatesFrom::Past => specs
162            .iter()
163            .copied()
164            .find(|s| s.sign < 0)
165            .unwrap_or(specs[0]),
166        PreferDatesFrom::Future | PreferDatesFrom::CurrentPeriod => specs
167            .iter()
168            .copied()
169            .find(|s| s.sign > 0)
170            .unwrap_or(specs[0]),
171    }
172}
173
174fn lookup_exact_in_locale(
175    phrase: &str,
176    loc: &CompiledLocale,
177    normalize: bool,
178    pref: PreferDatesFrom,
179) -> Option<RelativeSpec> {
180    if let Some(specs) = loc.relative_exact.get(phrase) {
181        return Some(select_relative_spec(specs, pref));
182    }
183    if normalize {
184        let f = fold_diacritics(phrase);
185        if let Some(specs) = loc.folded_relative_exact.get(f.as_ref()) {
186            return Some(select_relative_spec(specs, pref));
187        }
188    }
189    None
190}
191
192fn strip_approx_prefix(s: &str) -> String {
193    let mut cur = s.trim();
194    for _ in 0..2 {
195        cur = cur.trim_start_matches(['~', '≈']).trim_start();
196        let mut matched = false;
197        for p in [
198            "approximately ",
199            "approx. ",
200            "approx ",
201            "about ",
202            "around ",
203            "roughly ",
204            "nearly ",
205            "almost ",
206            "circa ",
207            "ca. ",
208            "environ ",
209            "etwa ",
210            "ungefähr ",
211            "ungefahr ",
212            "ongeveer ",
213            "około ",
214            "okolo ",
215            "около ",
216            "yaklaşık ",
217            "yaklasik ",
218            "sekitar ",
219            "약 ",
220            "約",
221        ] {
222            if let Some(rest) = cur.strip_prefix(p) {
223                let r = rest.trim_start();
224                if !r.is_empty() {
225                    cur = r;
226                    matched = true;
227                    break;
228                }
229            }
230        }
231        if !matched {
232            break;
233        }
234    }
235    let out = cur.to_string();
236    for (pat, rep) in [
237        ("vor etwa ", "vor "),
238        ("vor ungefähr ", "vor "),
239        ("vor ungefahr ", "vor "),
240        ("il y a environ ", "il y a "),
241        ("há cerca de ", "há "),
242        ("ha cerca de ", "ha "),
243        ("hace aproximadamente ", "hace "),
244        ("hace unos ", "hace "),
245    ] {
246        if let Some(idx) = out.find(pat) {
247            let mut s_new = String::with_capacity(out.len());
248            s_new.push_str(&out[..idx]);
249            s_new.push_str(rep);
250            s_new.push_str(&out[idx + pat.len()..]);
251            return s_new;
252        }
253    }
254    out
255}
256
257#[derive(Debug, Clone)]
258pub enum RelativeOutcome {
259    Matched(RelativeMatch),
260    OutOfBounds,
261    NoMatch,
262}
263
264/// Try parsing a normalized lowercase string as a relative date across candidate locales.
265pub fn try_parse_relative(
266    normalized: &str,
267    candidate_ids: &[usize],
268    registry: &LocaleRegistry,
269    settings: &Settings,
270) -> Option<RelativeMatch> {
271    match try_parse_relative_outcome(normalized, candidate_ids, registry, settings) {
272        RelativeOutcome::Matched(m) => Some(m),
273        RelativeOutcome::OutOfBounds | RelativeOutcome::NoMatch => None,
274    }
275}
276
277/// Like `try_parse_relative`, distinguishing calendar underflow/overflow from non-matches
278/// so out-of-range relative expressions (e.g. `"1 day ago"` at `0001-01-01`) are not re-parsed
279/// as another locale's absolute month.
280pub fn try_parse_relative_outcome(
281    normalized: &str,
282    candidate_ids: &[usize],
283    registry: &LocaleRegistry,
284    settings: &Settings,
285) -> RelativeOutcome {
286    let base = settings.effective_base();
287    let trimmed_article = normalized.strip_prefix("the ").unwrap_or(normalized);
288    let approx_stripped = strip_approx_prefix(trimmed_article);
289    let eff = approx_stripped.trim();
290    let folded_full = if settings.normalize {
291        fold_diacritics(eff)
292    } else {
293        Cow::Borrowed(eff)
294    };
295
296    // 0. Special compound day + time-of-day idioms, half/fractional durations & conversational clocks
297    if let Some(m) = try_conversational_clock_or_fraction(eff, settings) {
298        return RelativeOutcome::Matched(m);
299    }
300    if let Some(m) =
301        try_compound_tod_idiom(eff, folded_full.as_ref(), candidate_ids, registry, base, settings)
302    {
303        return RelativeOutcome::Matched(m);
304    }
305
306    // 1. O(1) Global Exact Relative Phrase lookup ("yesterday", "bugün", "yarın", "demain", "今日", "कल", "غدا")
307    if let Some(matches) = registry.exact_phrase_index.get(eff) {
308        let mut matched_specs: Vec<(usize, RelativeSpec)> = Vec::new();
309        if settings.use_given_language_order && !candidate_ids.is_empty() {
310            for &cid in candidate_ids {
311                for &(lid, spec) in matches {
312                    if lid as usize == cid {
313                        matched_specs.push((cid, spec));
314                    }
315                }
316            }
317        } else {
318            for &(lid, spec) in matches {
319                let lid_usize = lid as usize;
320                if candidate_ids.is_empty() || candidate_ids.contains(&lid_usize) {
321                    matched_specs.push((lid_usize, spec));
322                }
323            }
324        }
325        if !matched_specs.is_empty() {
326            let specs_only: Vec<RelativeSpec> = if settings.use_given_language_order && !candidate_ids.is_empty() {
327                let first_lid = matched_specs[0].0;
328                matched_specs
329                    .iter()
330                    .filter(|(l, _)| *l == first_lid)
331                    .map(|(_, s)| *s)
332                    .collect()
333            } else {
334                matched_specs.iter().map(|(_, s)| *s).collect()
335            };
336            let chosen = select_relative_spec(&specs_only, settings.prefer_dates_from);
337            let chosen_lid = matched_specs
338                .iter()
339                .find(|(_, s)| *s == chosen)
340                .map(|(l, _)| *l)
341                .unwrap_or(matched_specs[0].0);
342            let Some(dt) = apply_relative_offset(base, chosen.sign, chosen.amount as f64, chosen.unit) else {
343                return RelativeOutcome::OutOfBounds;
344            };
345            let has_t = is_time_unit(chosen.unit);
346            return RelativeOutcome::Matched(RelativeMatch {
347                naive: dt,
348                period: period_for_unit(chosen.unit),
349                locale: registry.locales[chosen_lid].code.clone(),
350                has_time: has_t,
351                parts: parts_for_relative(has_t, Some(chosen.unit)),
352                part_of_day: None,
353            });
354        }
355    }
356
357    if settings.normalize {
358        if let Some(matches) = registry.folded_exact_phrase_index.get(folded_full.as_ref()) {
359            let mut matched_specs: Vec<(usize, RelativeSpec)> = Vec::new();
360            if settings.use_given_language_order && !candidate_ids.is_empty() {
361                for &cid in candidate_ids {
362                    for &(lid, spec) in matches {
363                        if lid as usize == cid {
364                            matched_specs.push((cid, spec));
365                        }
366                    }
367                }
368            } else {
369                for &(lid, spec) in matches {
370                    let lid_usize = lid as usize;
371                    if candidate_ids.is_empty() || candidate_ids.contains(&lid_usize) {
372                        matched_specs.push((lid_usize, spec));
373                    }
374                }
375            }
376            if !matched_specs.is_empty() {
377                let specs_only: Vec<RelativeSpec> = if settings.use_given_language_order && !candidate_ids.is_empty() {
378                    let first_lid = matched_specs[0].0;
379                    matched_specs
380                        .iter()
381                        .filter(|(l, _)| *l == first_lid)
382                        .map(|(_, s)| *s)
383                        .collect()
384                } else {
385                    matched_specs.iter().map(|(_, s)| *s).collect()
386                };
387                let chosen = select_relative_spec(&specs_only, settings.prefer_dates_from);
388                let chosen_lid = matched_specs
389                    .iter()
390                    .find(|(_, s)| *s == chosen)
391                    .map(|(l, _)| *l)
392                    .unwrap_or(matched_specs[0].0);
393                let Some(dt) = apply_relative_offset(base, chosen.sign, chosen.amount as f64, chosen.unit) else {
394                    return RelativeOutcome::OutOfBounds;
395                };
396                let has_t = is_time_unit(chosen.unit);
397                return RelativeOutcome::Matched(RelativeMatch {
398                    naive: dt,
399                    period: period_for_unit(chosen.unit),
400                    locale: registry.locales[chosen_lid].code.clone(),
401                    has_time: has_t,
402                    parts: parts_for_relative(has_t, Some(chosen.unit)),
403                    part_of_day: None,
404                });
405            }
406        }
407    }
408
409    // 2. Peel off optional explicit time component
410    let (phrase_no_time, extracted_time) = extract_trailing_or_leading_time(eff);
411    let top_is_month_or_wd = candidate_ids.first().is_some_and(|&top_id| {
412        let tloc = &registry.locales[top_id];
413        tloc.months.contains_key(eff) || tloc.weekdays.contains_key(eff)
414    });
415
416    for &lid in candidate_ids {
417        let loc = &registry.locales[lid];
418
419        // 2a. Exact relative phrase + explicit time
420        if let Some(t) = extracted_time {
421            let cleaned = strip_connector_words(phrase_no_time, loc);
422            if let Some(spec) = lookup_exact_in_locale(cleaned, loc, settings.normalize, settings.prefer_dates_from) {
423                let Some(dt) = apply_relative_offset(base, spec.sign, spec.amount as f64, spec.unit) else {
424                    return RelativeOutcome::OutOfBounds;
425                };
426                return RelativeOutcome::Matched(RelativeMatch {
427                    naive: dt.date().and_time(t),
428                    period: Period::Day,
429                    locale: loc.code.clone(),
430                    has_time: true,
431                    parts: vec!["year", "month", "day", "time"],
432                    part_of_day: None,
433                });
434            }
435        }
436
437        // 2b. <relative_exact|relative_weekday> [connector] <time_of_day> ("yesterday at noon", "next Monday morning")
438        // Never allow a bare TOD word from a secondary locale to shadow an exact month/weekday in top candidate (e.g. "Jun" vs fy "jûn").
439        if extracted_time.is_none() && !(top_is_month_or_wd && lid != candidate_ids[0]) {
440            if let Some((dt, pod)) = try_relative_plus_tod(eff, loc, base, settings) {
441                return RelativeOutcome::Matched(RelativeMatch {
442                    naive: dt,
443                    period: Period::Day,
444                    locale: loc.code.clone(),
445                    has_time: true,
446                    parts: vec!["year", "month", "day", "time"],
447                    part_of_day: pod,
448                });
449            }
450        }
451
452        // 2c. Zero-regex structured affix patterns (3,592+ CLDR/dateparser patterns across 205 langs!)
453        let target_str = if extracted_time.is_some() {
454            strip_connector_words(phrase_no_time, loc)
455        } else {
456            eff
457        };
458
459        let affix_hit = if let Some((spec_sign, amount, unit)) = try_affix_match(
460            target_str,
461            loc,
462            settings.normalize,
463            settings.prefer_dates_from,
464        ) {
465            Some((spec_sign, amount, unit, extracted_time))
466        } else if extracted_time.is_some() {
467            // Re-check full phrase in case a shorthand duration ("in 3h", "dans 3h") looked like a trailing time
468            try_affix_match(eff, loc, settings.normalize, settings.prefer_dates_from)
469                .map(|(spec_sign, amount, unit)| (spec_sign, amount, unit, None))
470        } else {
471            None
472        };
473
474        if let Some((spec_sign, amount, unit, used_time)) = affix_hit {
475            let Some(mut dt) = apply_relative_offset(base, spec_sign, amount, unit) else {
476                return RelativeOutcome::OutOfBounds;
477            };
478            if let Some(t) = used_time {
479                dt = dt.date().and_time(t);
480            }
481            let explicit_t = used_time.is_some();
482            let has_t = explicit_t || is_time_unit(unit);
483            return RelativeOutcome::Matched(RelativeMatch {
484                naive: dt,
485                period: if explicit_t { Period::Day } else { period_for_unit(unit) },
486                locale: loc.code.clone(),
487                has_time: has_t,
488                parts: parts_for_relative(has_t, Some(unit)),
489                part_of_day: None,
490            });
491        }
492
493        // 2d. Compound & word-number relative expressions ("2 ay 3 gün önce", "5 dk önce", "1 year, 2 months, 3 days ago")
494        if let Some((mut dt, period, has_time_unit)) =
495            try_compound_relative(target_str, loc, base, settings.normalize)
496        {
497            if let Some(t) = extracted_time {
498                dt = dt.date().and_time(t);
499            }
500            let explicit_t = extracted_time.is_some();
501            let has_t = explicit_t || has_time_unit;
502            return RelativeOutcome::Matched(RelativeMatch {
503                naive: dt,
504                period: if explicit_t { Period::Day } else { period },
505                locale: loc.code.clone(),
506                has_time: has_t,
507                parts: if has_t {
508                    vec!["year", "month", "day", "time"]
509                } else {
510                    vec!["year", "month", "day"]
511                },
512                part_of_day: None,
513            });
514        }
515
516        // 2e. Bare relative duration ("2 days", "3 hours", "1 week", "2 gün") without explicit ago/in
517        if let Some((mut dt, period, has_time_unit)) =
518            try_bare_duration_relative(target_str, loc, base, settings)
519        {
520            if let Some(t) = extracted_time {
521                dt = dt.date().and_time(t);
522            }
523            let explicit_t = extracted_time.is_some();
524            let has_t = explicit_t || has_time_unit;
525            return RelativeOutcome::Matched(RelativeMatch {
526                naive: dt,
527                period: if explicit_t { Period::Day } else { period },
528                locale: loc.code.clone(),
529                has_time: has_t,
530                parts: if has_t {
531                    vec!["year", "month", "day", "time"]
532                } else {
533                    vec!["year", "month", "day"]
534                },
535                part_of_day: None,
536            });
537        }
538
539        // 2f. Relative period/weekday expressions: "last Monday", "geçen hafta", "gelecek ay"
540        if let Some((mut dt, period)) =
541            try_relative_period_or_weekday(target_str, loc, base, settings.normalize)
542        {
543            if let Some(t) = extracted_time {
544                dt = dt.date().and_time(t);
545            }
546            let has_t = extracted_time.is_some();
547            return RelativeOutcome::Matched(RelativeMatch {
548                naive: dt,
549                period: if has_t { Period::Day } else { period },
550                locale: loc.code.clone(),
551                has_time: has_t,
552                parts: parts_for_relative(has_t, None),
553                part_of_day: None,
554            });
555        }
556    }
557
558    RelativeOutcome::NoMatch
559}
560
561fn try_compound_tod_idiom(
562    normalized: &str,
563    folded: &str,
564    candidate_ids: &[usize],
565    registry: &LocaleRegistry,
566    base: NaiveDateTime,
567    settings: &Settings,
568) -> Option<RelativeMatch> {
569    let check = if settings.normalize { folded } else { normalized };
570    let (day_offset, hour, lang_code): (i64, u8, &str) = match check {
571        "tonight" | "this night" => (0, 20, "en"),
572        "last night" => (-1, 20, "en"),
573        "this morning" | "today morning" => (0, 9, "en"),
574        "this afternoon" | "today afternoon" => (0, 15, "en"),
575        "this evening" | "today evening" => (0, 18, "en"),
576        "day before yesterday" => {
577            let dt = base.checked_sub_signed(Duration::days(2))?;
578            if !(1..=9999).contains(&dt.year()) {
579                return None;
580            }
581            return Some(RelativeMatch {
582                naive: dt,
583                period: Period::Day,
584                locale: "en".to_string(),
585                has_time: false,
586                parts: vec!["year", "month", "day"],
587                part_of_day: None,
588            });
589        }
590        "day after tomorrow" => {
591            let dt = base.checked_add_signed(Duration::days(2))?;
592            if !(1..=9999).contains(&dt.year()) {
593                return None;
594            }
595            return Some(RelativeMatch {
596                naive: dt,
597                period: Period::Day,
598                locale: "en".to_string(),
599                has_time: false,
600                parts: vec!["year", "month", "day"],
601                part_of_day: None,
602            });
603        }
604        "yesterday morning" => (-1, 9, "en"),
605        "yesterday afternoon" => (-1, 15, "en"),
606        "yesterday evening" => (-1, 18, "en"),
607        "tomorrow morning" => (1, 9, "en"),
608        "tomorrow evening" => (1, 18, "en"),
609        "tomorrow night" => (1, 20, "en"),
610        "dün gece" | "dun gece" => (-1, 20, "tr"),
611        "dün akşam" | "dun aksam" => (-1, 18, "tr"),
612        "dün sabah" | "dun sabah" => (-1, 9, "tr"),
613        "bu akşam" | "bu aksam" => (0, 18, "tr"),
614        "bu sabah" => (0, 9, "tr"),
615        "bu gece" => (0, 20, "tr"),
616        "yarın sabah" | "yarin sabah" => (1, 9, "tr"),
617        "yarın akşam" | "yarin aksam" => (1, 18, "tr"),
618        "heute abend" => (0, 18, "de"),
619        "heute morgen" => (0, 9, "de"),
620        "gestern abend" => (-1, 18, "de"),
621        "heute nacht" => (0, 20, "de"),
622        "ce soir" => (0, 18, "fr"),
623        "ce matin" => (0, 9, "fr"),
624        "hier soir" => (-1, 18, "fr"),
625        "anoche" => (-1, 20, "es"),
626        "esta noche" => (0, 20, "es"),
627        "esta tarde" => (0, 15, "es"),
628        _ => return None,
629    };
630
631    if !candidate_ids.is_empty() {
632        let lang_allowed = candidate_ids
633            .iter()
634            .any(|&id| registry.locales[id].code == lang_code);
635        if !lang_allowed {
636            return None;
637        }
638    }
639
640    let shifted = base.checked_add_signed(Duration::days(day_offset))?;
641    if !(1..=9999).contains(&shifted.year()) {
642        return None;
643    }
644    let target_date = shifted.date();
645    let (nt, pod) = time_for_hour_anchor(hour, settings);
646    Some(RelativeMatch {
647        naive: target_date.and_time(nt),
648        period: Period::Day,
649        locale: lang_code.to_string(),
650        has_time: true,
651        parts: vec!["year", "month", "day", "time"],
652        part_of_day: pod,
653    })
654}
655
656fn split_tod_hour<'a>(
657    s: &'a str,
658    loc: &CompiledLocale,
659    normalize: bool,
660) -> Option<(&'a str, u8)> {
661    let mut best: Option<(&'a str, u8, usize)> = None;
662    for (phrase, &hour) in &loc.time_of_day {
663        if let Some(rest) = s.strip_suffix(phrase.as_str()) {
664            if (rest.is_empty() || rest.ends_with(' '))
665                && best.is_none_or(|(_, _, bl)| phrase.len() > bl)
666            {
667                best = Some((rest.trim_end(), hour, phrase.len()));
668            }
669        }
670    }
671    if let Some((prefix, hour, _)) = best {
672        return Some((prefix, hour));
673    }
674    if normalize {
675        let fs = fold_diacritics(s);
676        let total_words = s.split_whitespace().count();
677        let mut best_folded: Option<(usize, u8, usize)> = None;
678        for (phrase, &hour) in loc.folded_time_of_day.iter().chain(loc.time_of_day.iter()) {
679            if let Some(rest) = fs.strip_suffix(phrase.as_str()) {
680                if rest.is_empty() || rest.ends_with(' ') {
681                    let p_words = phrase.split_whitespace().count();
682                    if p_words <= total_words
683                        && fs.split_whitespace().count() == total_words
684                        && best_folded.is_none_or(|(_, _, bl)| phrase.len() > bl)
685                    {
686                        best_folded = Some((total_words - p_words, hour, phrase.len()));
687                    }
688                }
689            }
690        }
691        if let Some((keep_words, hour, _)) = best_folded {
692            if keep_words == 0 {
693                return Some(("", hour));
694            }
695            let mut count = 0usize;
696            let mut in_word = false;
697            for (idx, ch) in s.char_indices() {
698                if ch.is_whitespace() {
699                    if in_word {
700                        count += 1;
701                        if count == keep_words {
702                            return Some((s[..idx].trim_end(), hour));
703                        }
704                        in_word = false;
705                    }
706                } else {
707                    in_word = true;
708                }
709            }
710        }
711    }
712    None
713}
714
715fn try_relative_plus_tod(
716    normalized: &str,
717    loc: &CompiledLocale,
718    base: NaiveDateTime,
719    settings: &Settings,
720) -> Option<(NaiveDateTime, Option<PartOfDay>)> {
721    let (prefix_raw, hour) = split_tod_hour(normalized, loc, settings.normalize)?;
722    let (nt, pod) = time_for_hour_anchor(hour, settings);
723    if prefix_raw.is_empty() {
724        return Some((base.date().and_time(nt), pod));
725    }
726
727    let cleaned = strip_connector_words(prefix_raw, loc);
728    if let Some(spec) = lookup_exact_in_locale(
729        cleaned,
730        loc,
731        settings.normalize,
732        settings.prefer_dates_from,
733    ) {
734        let dt = apply_relative_offset(base, spec.sign, spec.amount as f64, spec.unit)?;
735        return Some((dt.date().and_time(nt), pod));
736    }
737
738    if let Some((dt, _period)) =
739        try_relative_period_or_weekday(cleaned, loc, base, settings.normalize)
740    {
741        return Some((dt.date().and_time(nt), pod));
742    }
743
744    None
745}
746
747/// Zero-regex prefix + number + suffix matcher covering 99.97% of dateparser's relative-type-regex!
748fn try_affix_match(
749    s: &str,
750    loc: &CompiledLocale,
751    normalize: bool,
752    pref: PreferDatesFrom,
753) -> Option<(i8, f64, TimeUnit)> {
754    let mut candidates: Vec<String> = Vec::with_capacity(3);
755    candidates.push(s.to_string());
756    if let Some(r) = replace_word_numbers_once(s, loc, normalize) {
757        candidates.push(r);
758    }
759    if normalize {
760        let fs = fold_diacritics(s);
761        if fs.as_ref() != s {
762            if let Some(r) = replace_word_numbers_once(fs.as_ref(), loc, true) {
763                candidates.push(r);
764            }
765            candidates.push(fs.into_owned());
766        }
767    }
768
769    let lookup_word_num = |ns: &str| -> Option<f64> {
770        let toks: Vec<&str> = ns.split_whitespace().collect();
771        if toks.len() > 1 {
772            if let Some((val, consumed)) = crate::numerals::parse_cardinal_slice(&toks, loc, normalize) {
773                if consumed == toks.len() {
774                    return Some(val as f64);
775                }
776            }
777        }
778        lookup_word_number_val(ns, loc, normalize)
779    };
780
781    let want_future = !matches!(pref, PreferDatesFrom::Past);
782
783    let match_against = |cand: &str, affixes: &[RelativeAffix]| -> Option<(i8, f64, TimeUnit)> {
784        let mut fallback: Option<(i8, f64, TimeUnit)> = None;
785        for affix in affixes {
786            let after_prefix = if affix.prefix.is_empty() {
787                cand
788            } else if let Some(rest) = cand.strip_prefix(&affix.prefix) {
789                rest
790            } else {
791                continue;
792            };
793
794            let middle = if affix.suffix.is_empty() {
795                after_prefix
796            } else if let Some(rest) = after_prefix.strip_suffix(&affix.suffix) {
797                rest
798            } else {
799                continue;
800            };
801
802            let num_str = middle.trim();
803            if let Some(val) = parse_positive_number(num_str).or_else(|| lookup_word_num(num_str)) {
804                let is_pref = (affix.sign > 0) == want_future;
805                if is_pref {
806                    return Some((affix.sign, val, affix.unit));
807                }
808                if fallback.is_none() {
809                    fallback = Some((affix.sign, val, affix.unit));
810                }
811            }
812        }
813        fallback
814    };
815
816    for cand in &candidates {
817        if let Some(hit) = match_against(cand, &loc.relative_affix) {
818            return Some(hit);
819        }
820    }
821    if normalize && !loc.folded_relative_affix.is_empty() {
822        for cand in &candidates {
823            if let Some(hit) = match_against(cand, &loc.folded_relative_affix) {
824                return Some(hit);
825            }
826        }
827    }
828    None
829}
830
831fn parse_positive_number(s: &str) -> Option<f64> {
832    if s.is_empty() || s.len() > 12 {
833        return None;
834    }
835    let mut seen_sep = false;
836    let mut has_digit = false;
837    for b in s.bytes() {
838        if b.is_ascii_digit() {
839            has_digit = true;
840        } else if (b == b'.' || b == b',') && !seen_sep {
841            seen_sep = true;
842        } else {
843            return None;
844        }
845    }
846    if !has_digit {
847        return None;
848    }
849    if s.contains(',') {
850        s.replace(',', ".").parse::<f64>().ok()
851    } else {
852        s.parse::<f64>().ok()
853    }
854}
855
856fn lookup_word_number_val(tok: &str, loc: &CompiledLocale, normalize: bool) -> Option<f64> {
857    if let Some(v) = crate::numerals::parse_single_word_cardinal(tok, loc, normalize) {
858        return Some(v as f64);
859    }
860    None
861}
862
863fn replace_word_numbers_once(s: &str, loc: &CompiledLocale, normalize: bool) -> Option<String> {
864    crate::numerals::collapse_word_numbers(s, loc, normalize)
865}
866
867#[inline]
868fn is_plural_bare_unit_without_count(clean: &str, loc_code: &str) -> bool {
869    if loc_code == "en" {
870        return matches!(
871            clean,
872            "seconds" | "secs" | "minutes" | "mins" | "hours" | "hrs" | "days" | "weeks"
873                | "months" | "years" | "decades" | "centuries" | "fortnights"
874        );
875    }
876    false
877}
878
879fn try_compound_relative(
880    s: &str,
881    loc: &CompiledLocale,
882    base: NaiveDateTime,
883    normalize: bool,
884) -> Option<(NaiveDateTime, Period, bool)> {
885    let mut sign: Option<i8> = None;
886    let mut rest = s.trim().to_string();
887
888    let strip_marker = |text: &str, markers: &[String]| -> Option<String> {
889        for w in markers {
890            let w = w.as_str();
891            if let Some(stripped) = text.strip_suffix(w) {
892                if stripped.is_empty() || stripped.ends_with(' ') || !w.is_ascii() {
893                    return Some(stripped.trim().to_string());
894                }
895            }
896            if let Some(stripped) = text.strip_prefix(w) {
897                if stripped.is_empty() || stripped.starts_with(' ') || !w.is_ascii() {
898                    return Some(stripped.trim().to_string());
899                }
900            }
901        }
902        None
903    };
904
905    if let Some(r) = strip_marker(&rest, &loc.ago_sorted) {
906        sign = Some(-1);
907        rest = r;
908    } else if normalize {
909        let f_rest = fold_diacritics(&rest);
910        if let Some(r) = strip_marker(f_rest.as_ref(), &loc.folded_ago_sorted) {
911            sign = Some(-1);
912            rest = r;
913        } else if let Some(r) = strip_marker(f_rest.as_ref(), &loc.ago_sorted) {
914            sign = Some(-1);
915            rest = r;
916        }
917    }
918
919    if sign.is_none() {
920        if let Some(r) = strip_marker(&rest, &loc.in_words_sorted) {
921            sign = Some(1);
922            rest = r;
923        } else if normalize {
924            let f_rest = fold_diacritics(&rest);
925            if let Some(r) = strip_marker(f_rest.as_ref(), &loc.folded_in_words_sorted) {
926                sign = Some(1);
927                rest = r;
928            } else if let Some(r) = strip_marker(f_rest.as_ref(), &loc.in_words_sorted) {
929                sign = Some(1);
930                rest = r;
931            }
932        }
933    }
934
935    let sign = sign?;
936    if rest.is_empty() {
937        return None;
938    }
939
940    apply_token_duration_pairs(&rest, loc, base, sign, normalize, true)
941}
942
943fn try_bare_duration_relative(
944    s: &str,
945    loc: &CompiledLocale,
946    base: NaiveDateTime,
947    settings: &Settings,
948) -> Option<(NaiveDateTime, Period, bool)> {
949    if settings.languages.is_none() && !crate::locale::is_major_auto_locale(&loc.code) {
950        let mut toks = s.split_whitespace();
951        if let (Some(_), Some(u_tok), None) = (toks.next(), toks.next(), toks.next()) {
952            let u_clean = u_tok.trim_end_matches('.');
953            if u_clean.len() <= 3 && u_clean.is_ascii() {
954                return None;
955            }
956        }
957    }
958    let sign = if settings.prefer_dates_from == PreferDatesFrom::Future {
959        1
960    } else {
961        -1
962    };
963    apply_token_duration_pairs(s, loc, base, sign, settings.normalize, false)
964}
965
966fn apply_token_duration_pairs(
967    rest: &str,
968    loc: &CompiledLocale,
969    base: NaiveDateTime,
970    sign: i8,
971    normalize: bool,
972    allow_single_char_attached_units: bool,
973) -> Option<(NaiveDateTime, Period, bool)> {
974    let lookup_unit = |tok: &str| -> Option<TimeUnit> {
975        if let Some(&u) = loc.units.get(tok) {
976            return Some(u);
977        }
978        if normalize {
979            let ft = fold_diacritics(tok);
980            if let Some(&u) = loc
981                .units
982                .get(ft.as_ref())
983                .or_else(|| loc.folded_units.get(ft.as_ref()))
984            {
985                return Some(u);
986            }
987        }
988        None
989    };
990
991    let tokens: Vec<&str> = rest
992        .split(|c: char| c.is_whitespace() || c == ',' || c == ';')
993        .filter(|t| !t.is_empty())
994        .collect();
995
996    let mut pairs: Vec<(f64, TimeUnit)> = Vec::new();
997    let mut pending_num: Option<f64> = None;
998
999    for &tok in &tokens {
1000        let clean = tok.trim_matches(|c: char| c == ',' || c == '.');
1001        if clean.is_empty() {
1002            continue;
1003        }
1004        if matches!(clean, "and" | "ve" | "und" | "et" | "y" | "e" | "of") || loc.skip.contains(clean)
1005        {
1006            continue;
1007        }
1008
1009        if pending_num.is_none() && allow_single_char_attached_units {
1010            if let Some(multi) = split_all_attached_num_units(clean) {
1011                if multi.len() >= 2 {
1012                    let mut all_ok = true;
1013                    let mut resolved = Vec::with_capacity(multi.len());
1014                    for (num, unit_str) in multi {
1015                        if let Some(u) = lookup_unit(unit_str) {
1016                            resolved.push((num, u));
1017                        } else {
1018                            all_ok = false;
1019                            break;
1020                        }
1021                    }
1022                    if all_ok {
1023                        pairs.extend(resolved);
1024                        continue;
1025                    }
1026                }
1027            }
1028            if let Some((num, unit_str)) = split_attached_num_unit(clean) {
1029                if let Some(u) = lookup_unit(unit_str) {
1030                    pairs.push((num, u));
1031                    continue;
1032                }
1033            }
1034        }
1035
1036        if let Some(n) = parse_positive_number(clean) {
1037            if pending_num.is_some() {
1038                return None;
1039            }
1040            pending_num = Some(n);
1041        } else if let Some(wn) = lookup_word_number_val(clean, loc, normalize) {
1042            if pending_num.is_some() {
1043                return None;
1044            }
1045            pending_num = Some(wn);
1046        } else {
1047            let u = lookup_unit(clean)?;
1048            if !allow_single_char_attached_units && pending_num.is_none() {
1049                return None;
1050            }
1051            if !allow_single_char_attached_units && clean.chars().count() < 2 {
1052                return None;
1053            }
1054            if pending_num.is_none() && is_plural_bare_unit_without_count(clean, &loc.code) {
1055                return None;
1056            }
1057            let amt = pending_num.take().unwrap_or(1.0);
1058            pairs.push((amt, u));
1059        }
1060    }
1061
1062    if pairs.is_empty() || pending_num.is_some() {
1063        return None;
1064    }
1065
1066    let mut dt = base;
1067    let mut finest_period = Period::Year;
1068    let mut has_time_unit = false;
1069    for (amt, unit) in pairs {
1070        // Avoid misinterpreting calendar years like "2000 год" / "1000 год" as "2000 years ago"
1071        if !allow_single_char_attached_units && unit == TimeUnit::Year && amt >= 1000.0 {
1072            return None;
1073        }
1074        if matches!(unit, TimeUnit::Hour | TimeUnit::Minute | TimeUnit::Second) {
1075            has_time_unit = true;
1076        }
1077        dt = apply_relative_offset(dt, sign, amt, unit)?;
1078        let p = period_for_unit(unit);
1079        let rank = |per: Period| match per {
1080            Period::Year => 0,
1081            Period::Month => 1,
1082            Period::Week => 2,
1083            Period::Day => 3,
1084            Period::Time => 4,
1085        };
1086        if rank(p) > rank(finest_period) {
1087            finest_period = p;
1088        }
1089    }
1090
1091    Some((dt, finest_period, has_time_unit))
1092}
1093
1094fn split_attached_num_unit(s: &str) -> Option<(f64, &str)> {
1095    let idx = s.find(|c: char| !c.is_ascii_digit() && c != '.' && c != ',')?;
1096    if idx == 0 {
1097        return None;
1098    }
1099    let num = parse_positive_number(&s[..idx])?;
1100    let unit = &s[idx..];
1101    if unit.is_empty() {
1102        return None;
1103    }
1104    Some((num, unit))
1105}
1106
1107fn split_all_attached_num_units(s: &str) -> Option<Vec<(f64, &str)>> {
1108    let mut out = Vec::new();
1109    let mut pos = 0usize;
1110    while pos < s.len() {
1111        let rest = &s[pos..];
1112        let mut num_end = 0usize;
1113        let mut seen_sep = false;
1114        for (i, ch) in rest.char_indices() {
1115            if ch.is_ascii_digit() {
1116                num_end = i + 1;
1117            } else if (ch == '.' || ch == ',') && !seen_sep && num_end > 0 {
1118                seen_sep = true;
1119                num_end = i + 1;
1120            } else {
1121                break;
1122            }
1123        }
1124        if num_end == 0 {
1125            return None;
1126        }
1127        let num = parse_positive_number(&rest[..num_end])?;
1128        pos += num_end;
1129        let after_num = &s[pos..];
1130        if after_num.is_empty() {
1131            return None;
1132        }
1133        let unit_end = after_num
1134            .find(|c: char| c.is_ascii_digit())
1135            .unwrap_or(after_num.len());
1136        let unit_raw = &after_num[..unit_end];
1137        let unit = unit_raw.trim_end_matches(['と', '和', '및']);
1138        if unit.is_empty() {
1139            return None;
1140        }
1141        out.push((num, unit));
1142        pos += unit_end;
1143    }
1144    if out.is_empty() {
1145        None
1146    } else {
1147        Some(out)
1148    }
1149}
1150
1151fn classify_relative_modifier(tok: &str) -> Option<i8> {
1152    match tok {
1153        "last" | "previous" | "past" | "geçen" | "gecen" | "önceki" | "onceki" | "letzten"
1154        | "letzter" | "letzte" | "vergangenen" | "dernier" | "dernière" | "derniere"
1155        | "pasado" | "pasada" | "passado" | "passada" | "darrer" | "darrera" | "trecut"
1156        | "trecută" | "trecuta" | "múlt" | "mult" | "előző" | "elozo" | "scorso" | "scorsa"
1157        | "vorige" | "afgelopen" | "zeszły" | "zeszła" | "zeszly" | "zeszla" | "poprzedni"
1158        | "прошлый" | "прошлая" | "минулий" | "минула" | "миналата" | "minuly" | "minulý"
1159        | "minulá" | "prejšnji" | "prejsnji" | "prethodni" | "prethodna" | "претходни"
1160        | "претходна" | "förra" | "forra" | "sidste" | "forrige" | "viime" | "praėjęs"
1161        | "praeitas" | "pagājušais" | "eelmine" | "síðasti" | "sidasti" | "diwethaf" | "joan"
1162        | "aurreko" | "pasat" | "περασμένο" | "περασμένη" | "שעבר" | "שעברה" | "lalu"
1163        | "yang lalu" | "trước" | "truoc" | "iliyopita" | "verlede" | "pasinta"
1164        | "antaŭa" | "nakaraang" | "keçən" | "kecen" | "o'tgan" | "өткен" | "otken"
1165        | "지난" => Some(-1),
1166        "next" | "coming" | "following" | "gelecek" | "önümüzdeki" | "onumuzdeki" | "sonraki"
1167        | "nächsten" | "nächster" | "nächste" | "nachsten" | "nachster" | "nachste"
1168        | "kommenden" | "prochain" | "prochaine" | "próximo" | "próxima" | "proximo"
1169        | "proxima" | "siguiente" | "vinent" | "următorul" | "urmatorul" | "următoarea"
1170        | "jövő" | "jovo" | "következő" | "kovetkezo" | "prossimo" | "prossima" | "volgende"
1171        | "komende" | "przyszły" | "przyszła" | "przyszly" | "przyszla" | "następny"
1172        | "nastepny" | "следующий" | "следующая" | "наступний" | "наступна" | "следващ"
1173        | "příští" | "pristi" | "budúci" | "buduci" | "naslednji" | "sljedeći" | "sljedeci"
1174        | "следећи" | "следећа" | "nästa" | "nasta" | "næste" | "naeste" | "neste" | "ensi"
1175        | "kitas" | "nākamais" | "järgmine" | "næsti" | "naesti" | "nesaf" | "hurrengo"
1176        | "vindeiro" | "επόμενο" | "επόμενη" | "הבא" | "הבאה" | "depan" | "berikutnya"
1177        | "tới" | "toi" | "sau" | "ijayo" | "venonta" | "susunod" | "gələn"
1178        | "gelen" | "keyingi" | "келесі" | "kelesi" | "다음" => Some(1),
1179        "this" | "bu" | "diesen" | "dieser" | "diese" | "ce" | "cette" | "cet" | "este"
1180        | "esta" | "aquest" | "aquesta" | "acest" | "această" | "aceasta" | "ez" | "ebben"
1181        | "questo" | "questa" | "deze" | "dit" | "ten" | "ta" | "этот" | "эта" | "цей"
1182        | "ця" | "този" | "tento" | "táto" | "ovaj" | "ova" | "овај" | "ова"
1183        | "denna" | "denne" | "tämä" | "tama" | "šis" | "šī" | "see" | "þessi" | "hwn"
1184        | "hau" | "αυτό" | "αυτή" | "הזה" | "הזאת" | "ini" | "này" | "nay"
1185        | "hii" | "hierdie" | "ĉi" | "itong" | "ushbu" | "осы" | "osy" | "이번" => Some(0),
1186        _ => None,
1187    }
1188}
1189
1190fn try_cjk_relative_weekday(s: &str, base: NaiveDateTime) -> Option<(NaiveDateTime, Period)> {
1191    // Chinese: 上/下/本周[一..日|天] or 上/下星期[一..日|天]
1192    // Japanese: 先週/来週/今週[の][月..日][曜[日]]
1193    let (dir, rest): (i8, &str) = if let Some(r) = s.strip_prefix("先週の").or_else(|| s.strip_prefix("先週")) {
1194        (-1, r)
1195    } else if let Some(r) = s.strip_prefix("来週の").or_else(|| s.strip_prefix("来週")) {
1196        (1, r)
1197    } else if let Some(r) = s.strip_prefix("今週の").or_else(|| s.strip_prefix("今週")) {
1198        (0, r)
1199    } else if let Some(r) = s.strip_prefix("上星期").or_else(|| s.strip_prefix("上周")) {
1200        (-1, r)
1201    } else if let Some(r) = s.strip_prefix("下星期").or_else(|| s.strip_prefix("下周")) {
1202        (1, r)
1203    } else {
1204        let r = s
1205            .strip_prefix("本星期")
1206            .or_else(|| s.strip_prefix("本周"))
1207            .or_else(|| s.strip_prefix("这星期"))
1208            .or_else(|| s.strip_prefix("这周"))?;
1209        (0, r)
1210    };
1211
1212    let target_wd: i64 = match rest.trim() {
1213        "一" | "月" | "月曜" | "月曜日" => 0,
1214        "二" | "火" | "火曜" | "火曜日" => 1,
1215        "三" | "水" | "水曜" | "水曜日" => 2,
1216        "四" | "木" | "木曜" | "木曜日" => 3,
1217        "五" | "金" | "金曜" | "金曜日" => 4,
1218        "六" | "土" | "土曜" | "土曜日" => 5,
1219        "日" | "天" | "日曜" | "日曜日" => 6,
1220        _ => return None,
1221    };
1222
1223    let current_wd = base.weekday().num_days_from_monday() as i64;
1224    let delta_days = compute_weekday_delta(dir, current_wd, target_wd);
1225    base.checked_add_signed(Duration::days(delta_days))
1226        .map(|dt| (dt.date().and_hms_opt(0, 0, 0).unwrap_or(dt), Period::Day))
1227}
1228
1229#[inline]
1230fn compute_weekday_delta(dir: i8, current_wd: i64, target_wd: i64) -> i64 {
1231    if dir < 0 {
1232        let mut diff = target_wd - current_wd;
1233        if diff >= 0 {
1234            diff -= 7;
1235        }
1236        diff
1237    } else if dir > 0 {
1238        let mut diff = target_wd - current_wd;
1239        if diff <= 0 {
1240            diff += 7;
1241        }
1242        diff
1243    } else {
1244        target_wd - current_wd
1245    }
1246}
1247
1248fn try_relative_period_or_weekday(
1249    s: &str,
1250    loc: &CompiledLocale,
1251    base: NaiveDateTime,
1252    normalize: bool,
1253) -> Option<(NaiveDateTime, Period)> {
1254    if matches!(loc.code.as_str(), "zh" | "ja") {
1255        if let Some(cjk) = try_cjk_relative_weekday(s.trim(), base) {
1256            return Some(cjk);
1257        }
1258    }
1259
1260    let fs = if normalize {
1261        fold_diacritics(s)
1262    } else {
1263        Cow::Borrowed(s)
1264    };
1265    let mut tokens: Vec<&str> = fs.split_whitespace().collect();
1266    if tokens.len() == 3 && matches!(tokens[0], "el" | "la" | "le" | "w" | "в" | "am") {
1267        tokens.remove(0);
1268    }
1269    if tokens.len() != 2 {
1270        return None;
1271    }
1272
1273    let (dir, target_tok) = if let Some(d) = classify_relative_modifier(tokens[0]) {
1274        (d, tokens[1])
1275    } else {
1276        let d = classify_relative_modifier(tokens[1])?;
1277        (d, tokens[0])
1278    };
1279
1280    let unit_opt = loc.units.get(target_tok).copied().or_else(|| {
1281        if normalize {
1282            loc.folded_units.get(target_tok).copied()
1283        } else {
1284            None
1285        }
1286    });
1287    if let Some(unit) = unit_opt {
1288        let period = period_for_unit(unit);
1289        if dir == 0 {
1290            return Some((base, period));
1291        }
1292        return apply_relative_offset(base, dir, 1.0, unit).map(|dt| (dt, period));
1293    }
1294
1295    let target_wd = loc
1296        .weekdays
1297        .get(target_tok)
1298        .copied()
1299        .or_else(|| {
1300            if normalize {
1301                loc.folded_weekdays.get(target_tok).copied()
1302            } else {
1303                None
1304            }
1305        })
1306        .or_else(|| {
1307            target_tok
1308                .strip_suffix("-feira")
1309                .and_then(|stem| loc.weekdays.get(stem).copied())
1310        })?;
1311
1312    let current_wd = base.weekday().num_days_from_monday() as i64;
1313    let delta_days = compute_weekday_delta(dir, current_wd, target_wd as i64);
1314
1315    base.checked_add_signed(Duration::days(delta_days))
1316        .map(|dt| (dt.date().and_hms_opt(0, 0, 0).unwrap_or(dt), Period::Day))
1317}
1318
1319/// Parse standalone fractional relative durations and conversational clock idioms
1320/// (e.g. "two and a half hours ago", "bir buçuk saat önce", "quarter past 3", "saat 3 buçuk").
1321pub fn try_conversational_clock_or_fraction(
1322    normalized: &str,
1323    settings: &Settings,
1324) -> Option<RelativeMatch> {
1325    let m = try_conversational_clock_or_fraction_inner(normalized, settings)?;
1326    if crate::locale::settings_allows_locale(settings, &m.locale) {
1327        Some(m)
1328    } else {
1329        None
1330    }
1331}
1332
1333fn try_conversational_clock_or_fraction_inner(
1334    normalized: &str,
1335    settings: &Settings,
1336) -> Option<RelativeMatch> {
1337    let base = settings.effective_base();
1338    let s = if settings.normalize {
1339        fold_diacritics(normalized)
1340    } else {
1341        Cow::Borrowed(normalized)
1342    };
1343    let s = s.trim();
1344
1345    if matches!(
1346        s,
1347        "just now"
1348            | "right now"
1349            | "hemen simdi"
1350            | "hemen şimdi"
1351            | "az once"
1352            | "az önce"
1353            | "gerade eben"
1354            | "a l'instant"
1355            | "à l'instant"
1356            | "ahora mismo"
1357    ) {
1358        let locale = if s.contains("simdi")
1359            || s.contains("şimdi")
1360            || s.contains("once")
1361            || s.contains("önce")
1362        {
1363            "tr"
1364        } else if s == "gerade eben" {
1365            "de"
1366        } else if s.contains("instant") {
1367            "fr"
1368        } else if s == "ahora mismo" {
1369            "es"
1370        } else {
1371            "en"
1372        };
1373        return Some(RelativeMatch {
1374            naive: base,
1375            period: Period::Day,
1376            locale: locale.to_string(),
1377            has_time: true,
1378            parts: vec!["year", "month", "day", "time"],
1379            part_of_day: None,
1380        });
1381    }
1382
1383    if matches!(
1384        s,
1385        "half an hour ago" | "half hour ago" | "yarım saat önce" | "yarim saat once"
1386    ) {
1387        let dt = apply_relative_offset(base, -1, 30.0, TimeUnit::Minute)?;
1388        return Some(RelativeMatch {
1389            naive: dt,
1390            period: Period::Day,
1391            locale: if s.contains("saat") { "tr" } else { "en" }.to_string(),
1392            has_time: true,
1393            parts: vec!["year", "month", "day", "time"],
1394            part_of_day: None,
1395        });
1396    }
1397    if matches!(
1398        s,
1399        "in half an hour" | "in half hour" | "yarım saat sonra" | "yarim saat sonra"
1400    ) {
1401        let dt = apply_relative_offset(base, 1, 30.0, TimeUnit::Minute)?;
1402        return Some(RelativeMatch {
1403            naive: dt,
1404            period: Period::Day,
1405            locale: if s.contains("saat") { "tr" } else { "en" }.to_string(),
1406            has_time: true,
1407            parts: vec!["year", "month", "day", "time"],
1408            part_of_day: None,
1409        });
1410    }
1411    if matches!(s, "half a day ago") {
1412        let dt = apply_relative_offset(base, -1, 12.0, TimeUnit::Hour)?;
1413        return Some(RelativeMatch {
1414            naive: dt,
1415            period: Period::Day,
1416            locale: "en".to_string(),
1417            has_time: true,
1418            parts: vec!["year", "month", "day", "time"],
1419            part_of_day: None,
1420        });
1421    }
1422
1423    // Half-unit idioms in Russian & Chinese/Japanese
1424    let half_spec: Option<(i8, f64, TimeUnit, &'static str)> = match s {
1425        "через полчаса" => Some((1, 30.0, TimeUnit::Minute, "ru")),
1426        "полчаса назад" => Some((-1, 30.0, TimeUnit::Minute, "ru")),
1427        "через полгода" => Some((1, 6.0, TimeUnit::Month, "ru")),
1428        "полгода назад" => Some((-1, 6.0, TimeUnit::Month, "ru")),
1429        "через полдня" => Some((1, 12.0, TimeUnit::Hour, "ru")),
1430        "полдня назад" => Some((-1, 12.0, TimeUnit::Hour, "ru")),
1431        "半小时前" | "半小時前" => Some((-1, 30.0, TimeUnit::Minute, "zh")),
1432        "半時間前" => Some((-1, 30.0, TimeUnit::Minute, "ja")),
1433        "半小时后" | "半小時後" | "半小时後" => Some((1, 30.0, TimeUnit::Minute, "zh")),
1434        "半年前" => Some((-1, 6.0, TimeUnit::Month, "zh")),
1435        "半年后" | "半年後" => Some((1, 6.0, TimeUnit::Month, "zh")),
1436        "半天前" => Some((-1, 12.0, TimeUnit::Hour, "zh")),
1437        "半天后" | "半天後" => Some((1, 12.0, TimeUnit::Hour, "zh")),
1438        _ => None,
1439    };
1440    if let Some((sign, amt, unit, loc_code)) = half_spec {
1441        let dt = apply_relative_offset(base, sign, amt, unit)?;
1442        let has_t = is_time_unit(unit);
1443        return Some(RelativeMatch {
1444            naive: dt,
1445            period: period_for_unit(unit),
1446            locale: loc_code.to_string(),
1447            has_time: has_t,
1448            parts: parts_for_relative(has_t, Some(unit)),
1449            part_of_day: None,
1450        });
1451    }
1452
1453    // Arabic dual/singular idioms with منذ / قبل / بعد / خلال
1454    let ar_pair: Option<(i8, &str)> = if let Some(rest) = s.strip_prefix("منذ ") {
1455        Some((-1, rest.trim()))
1456    } else if let Some(rest) = s.strip_prefix("قبل ") {
1457        Some((-1, rest.trim()))
1458    } else if let Some(rest) = s.strip_prefix("بعد ") {
1459        Some((1, rest.trim()))
1460    } else if let Some(rest) = s.strip_prefix("خلال ") {
1461        Some((1, rest.trim()))
1462    } else {
1463        None
1464    };
1465    if let Some((sign, noun)) = ar_pair {
1466        let ar_unit: Option<(f64, TimeUnit)> = match noun {
1467            "ثانيتين" | "ثانيتان" => Some((2.0, TimeUnit::Second)),
1468            "دقيقتين" | "دقيقتان" => Some((2.0, TimeUnit::Minute)),
1469            "ساعتين" | "ساعتان" => Some((2.0, TimeUnit::Hour)),
1470            "يومين" | "يومان" => Some((2.0, TimeUnit::Day)),
1471            "اسبوعين" | "أسبوعين" | "اسبوعان" | "أسبوعان" => Some((2.0, TimeUnit::Week)),
1472            "شهرين" | "شهران" => Some((2.0, TimeUnit::Month)),
1473            "سنتين" | "عامين" | "سنتان" | "عامان" => Some((2.0, TimeUnit::Year)),
1474            "ثانية" => Some((1.0, TimeUnit::Second)),
1475            "دقيقة" => Some((1.0, TimeUnit::Minute)),
1476            "ساعة" => Some((1.0, TimeUnit::Hour)),
1477            "يوم" => Some((1.0, TimeUnit::Day)),
1478            "اسبوع" | "أسبوع" => Some((1.0, TimeUnit::Week)),
1479            "شهر" => Some((1.0, TimeUnit::Month)),
1480            "سنة" | "عام" => Some((1.0, TimeUnit::Year)),
1481            _ => None,
1482        };
1483        if let Some((amt, unit)) = ar_unit {
1484            let dt = apply_relative_offset(base, sign, amt, unit)?;
1485            let has_t = is_time_unit(unit);
1486            return Some(RelativeMatch {
1487                naive: dt,
1488                period: period_for_unit(unit),
1489                locale: "ar".to_string(),
1490                has_time: has_t,
1491                parts: parts_for_relative(has_t, Some(unit)),
1492                part_of_day: None,
1493            });
1494        }
1495    }
1496
1497    // Hebrew dual idioms with לפני / בעוד / עוד
1498    let he_pair: Option<(i8, &str)> = if let Some(rest) = s.strip_prefix("לפני ") {
1499        Some((-1, rest.trim()))
1500    } else if let Some(rest) = s.strip_prefix("בעוד ").or_else(|| s.strip_prefix("עוד ")) {
1501        Some((1, rest.trim()))
1502    } else {
1503        None
1504    };
1505    if let Some((sign, noun)) = he_pair {
1506        let he_unit: Option<(f64, TimeUnit)> = match noun {
1507            "דקתיים" => Some((2.0, TimeUnit::Minute)),
1508            "שעתיים" => Some((2.0, TimeUnit::Hour)),
1509            "יומיים" => Some((2.0, TimeUnit::Day)),
1510            "שבועיים" => Some((2.0, TimeUnit::Week)),
1511            "חודשיים" => Some((2.0, TimeUnit::Month)),
1512            "שנתיים" => Some((2.0, TimeUnit::Year)),
1513            _ => None,
1514        };
1515        if let Some((amt, unit)) = he_unit {
1516            let dt = apply_relative_offset(base, sign, amt, unit)?;
1517            let has_t = is_time_unit(unit);
1518            return Some(RelativeMatch {
1519                naive: dt,
1520                period: period_for_unit(unit),
1521                locale: "he".to_string(),
1522                has_time: has_t,
1523                parts: parts_for_relative(has_t, Some(unit)),
1524                part_of_day: None,
1525            });
1526        }
1527    }
1528
1529    if let Some(m) = try_fractional_duration(s, base) {
1530        return Some(m);
1531    }
1532    if let Some(m) = try_conversational_clock(s, settings) {
1533        return Some(m);
1534    }
1535    None
1536}
1537
1538fn parse_small_num_or_word(tok: &str) -> Option<f64> {
1539    if let Ok(v) = tok.parse::<f64>() {
1540        if v.is_finite() && v >= 0.0 {
1541            return Some(v);
1542        }
1543    }
1544    match tok {
1545        "a" | "an" | "one" | "bir" | "ein" | "eine" | "un" | "une" | "uno" | "una" => Some(1.0),
1546        "two" | "iki" | "zwei" | "deux" | "dos" => Some(2.0),
1547        "three" | "üç" | "uc" | "drei" | "trois" | "tres" => Some(3.0),
1548        "four" | "dört" | "dort" | "vier" | "quatre" | "cuatro" => Some(4.0),
1549        "five" | "beş" | "bes" | "fünf" | "funf" | "cinq" | "cinco" => Some(5.0),
1550        "six" | "altı" | "alti" | "sechs" | "seis" => Some(6.0),
1551        "seven" | "yedi" | "sieben" | "sept" | "siete" => Some(7.0),
1552        "eight" | "sekiz" | "acht" | "huit" | "ocho" => Some(8.0),
1553        "nine" | "dokuz" | "neun" | "neuf" | "nueve" => Some(9.0),
1554        "ten" | "on" | "zehn" | "dix" | "diez" => Some(10.0),
1555        "eleven" | "on bir" => Some(11.0),
1556        "twelve" | "on iki" => Some(12.0),
1557        _ => None,
1558    }
1559}
1560
1561fn parse_unit_token(tok: &str) -> Option<TimeUnit> {
1562    match tok {
1563        "second" | "seconds" | "sec" | "secs" | "saniye" | "sekunde" | "sekunden" => Some(TimeUnit::Second),
1564        "minute" | "minutes" | "min" | "mins" | "dakika" | "dk" => Some(TimeUnit::Minute),
1565        "hour" | "hours" | "hr" | "hrs" | "saat" | "stunde" | "stunden" => Some(TimeUnit::Hour),
1566        "day" | "days" | "gün" | "gun" | "tag" | "tage" | "tagen" => Some(TimeUnit::Day),
1567        "week" | "weeks" | "hafta" | "woche" | "wochen" => Some(TimeUnit::Week),
1568        "month" | "months" | "ay" | "monat" | "monate" | "monaten" => Some(TimeUnit::Month),
1569        "year" | "years" | "yıl" | "yil" | "sene" | "jahr" | "jahre" | "jahren" => Some(TimeUnit::Year),
1570        _ => None,
1571    }
1572}
1573
1574fn apply_fractional_offset(base: NaiveDateTime, sign: i8, whole_and_half: f64, unit: TimeUnit) -> Option<NaiveDateTime> {
1575    match unit {
1576        TimeUnit::Month => {
1577            let days = (whole_and_half * 30.0).round();
1578            apply_relative_offset(base, sign, days, TimeUnit::Day)
1579        }
1580        TimeUnit::Year => {
1581            let months = (whole_and_half * 12.0).round();
1582            apply_relative_offset(base, sign, months, TimeUnit::Month)
1583        }
1584        _ => apply_relative_offset(base, sign, whole_and_half, unit),
1585    }
1586}
1587
1588fn try_fractional_duration(s: &str, base: NaiveDateTime) -> Option<RelativeMatch> {
1589    // English: "[in ]<n> and a half <unit>[ ago| from now]"
1590    let (sign_en, core_en): (i8, &str) = if let Some(rest) = s.strip_prefix("in ") {
1591        (1, rest.trim())
1592    } else if let Some(rest) = s.strip_suffix(" ago") {
1593        (-1, rest.trim())
1594    } else if let Some(rest) = s.strip_suffix(" from now") {
1595        (1, rest.trim())
1596    } else {
1597        (0, s)
1598    };
1599    if sign_en != 0 {
1600        if let Some((left, right)) = core_en.split_once(" and a half ") {
1601            if let (Some(n), Some(unit)) = (parse_small_num_or_word(left.trim()), parse_unit_token(right.trim())) {
1602                let dt = apply_fractional_offset(base, sign_en, n + 0.5, unit)?;
1603                let has_t = is_time_unit(unit);
1604                return Some(RelativeMatch {
1605                    naive: dt,
1606                    period: period_for_unit(unit),
1607                    locale: "en".to_string(),
1608                    has_time: has_t,
1609                    parts: parts_for_relative(has_t, Some(unit)),
1610                    part_of_day: None,
1611                });
1612            }
1613        }
1614    }
1615
1616    // Turkish: "<n> buçuk <unit> önce/sonra" (folded: "bucuk", "once")
1617    let (sign_tr, core_tr): (i8, &str) = if let Some(rest) = s.strip_suffix(" once").or_else(|| s.strip_suffix(" önce")) {
1618        (-1, rest.trim())
1619    } else if let Some(rest) = s.strip_suffix(" sonra") {
1620        (1, rest.trim())
1621    } else {
1622        (0, "")
1623    };
1624    if sign_tr != 0 {
1625        if let Some((left, right)) = core_tr.split_once(" bucuk ").or_else(|| core_tr.split_once(" buçuk ")) {
1626            if let (Some(n), Some(unit)) = (parse_small_num_or_word(left.trim()), parse_unit_token(right.trim())) {
1627                let dt = apply_fractional_offset(base, sign_tr, n + 0.5, unit)?;
1628                let has_t = is_time_unit(unit);
1629                return Some(RelativeMatch {
1630                    naive: dt,
1631                    period: period_for_unit(unit),
1632                    locale: "tr".to_string(),
1633                    has_time: has_t,
1634                    parts: parts_for_relative(has_t, Some(unit)),
1635                    part_of_day: None,
1636                });
1637            }
1638        }
1639    }
1640
1641    // German: "vor eineinhalb <unit>" / "in anderthalb <unit>"
1642    let (sign_de, core_de): (i8, &str) = if let Some(rest) = s.strip_prefix("vor ") {
1643        (-1, rest.trim())
1644    } else if let Some(rest) = s.strip_prefix("in ") {
1645        (1, rest.trim())
1646    } else {
1647        (0, "")
1648    };
1649    if sign_de != 0 {
1650        for kw in ["eineinhalb ", "anderthalb "] {
1651            if let Some(unit_str) = core_de.strip_prefix(kw) {
1652                if let Some(unit) = parse_unit_token(unit_str.trim()) {
1653                    let dt = apply_fractional_offset(base, sign_de, 1.5, unit)?;
1654                    let has_t = is_time_unit(unit);
1655                    return Some(RelativeMatch {
1656                        naive: dt,
1657                        period: period_for_unit(unit),
1658                        locale: "de".to_string(),
1659                        has_time: has_t,
1660                        parts: parts_for_relative(has_t, Some(unit)),
1661                        part_of_day: None,
1662                    });
1663                }
1664            }
1665        }
1666    }
1667
1668    None
1669}
1670
1671fn parse_clock_hour_spec(raw: &str) -> Option<u32> {
1672    let mut t = raw.trim().trim_end_matches('.');
1673    let mut is_pm = false;
1674    let mut is_am = false;
1675    for suf in ["p.m.", "p.m", "pm"] {
1676        if let Some(rest) = t.strip_suffix(suf) {
1677            t = rest.trim();
1678            is_pm = true;
1679            break;
1680        }
1681    }
1682    if !is_pm {
1683        for suf in ["a.m.", "a.m", "am"] {
1684            if let Some(rest) = t.strip_suffix(suf) {
1685                t = rest.trim();
1686                is_am = true;
1687                break;
1688            }
1689        }
1690    }
1691    let val = parse_small_num_or_word(t)?;
1692    let mut h = val as u32;
1693    if (h as f64 - val).abs() > 1e-6 || h > 23 {
1694        return None;
1695    }
1696    if is_pm {
1697        if h == 0 || h > 12 {
1698            return None;
1699        }
1700        if h < 12 {
1701            h += 12;
1702        }
1703    } else if is_am {
1704        if h == 0 || h > 12 {
1705            return None;
1706        }
1707        if h == 12 {
1708            h = 0;
1709        }
1710    }
1711    Some(h)
1712}
1713
1714fn try_conversational_clock(s: &str, settings: &Settings) -> Option<RelativeMatch> {
1715    // Explicit 12 noon / 12 midnight
1716    let noon_midnight: Option<(u32, u32)> = match s {
1717        "12 noon" | "12:00 noon" | "12 pm noon" | "12 p.m. noon" => Some((12, 0)),
1718        "12 midnight" | "12:00 midnight" | "12 am midnight" | "12 a.m. midnight" => Some((0, 0)),
1719        _ => None,
1720    };
1721    if let Some((hh, mm)) = noon_midnight {
1722        let nt = NaiveTime::from_hms_opt(hh, mm, 0)?;
1723        let nd = resolve_time_only_date(nt, settings);
1724        return Some(RelativeMatch {
1725            naive: nd.and_time(nt),
1726            period: Period::Day,
1727            locale: "en".to_string(),
1728            has_time: true,
1729            parts: vec!["time"],
1730            part_of_day: None,
1731        });
1732    }
1733
1734    // English: "[a ]quarter past <H>", "[a ]quarter to <H>", "half past <H>"
1735    let trimmed = s.strip_prefix("a ").unwrap_or(s);
1736    let en_clock: Option<(u32, u32)> = if let Some(rest) = trimmed.strip_prefix("quarter past ") {
1737        parse_clock_hour_spec(rest).map(|h| (h, 15))
1738    } else if let Some(rest) = trimmed.strip_prefix("quarter to ") {
1739        parse_clock_hour_spec(rest).map(|h| (if h == 0 { 23 } else { h - 1 }, 45))
1740    } else if let Some(rest) = trimmed.strip_prefix("half past ") {
1741        parse_clock_hour_spec(rest).map(|h| (h, 30))
1742    } else {
1743        None
1744    };
1745    if let Some((hh, mm)) = en_clock {
1746        let nt = NaiveTime::from_hms_opt(hh, mm, 0)?;
1747        let nd = resolve_time_only_date(nt, settings);
1748        return Some(RelativeMatch {
1749            naive: nd.and_time(nt),
1750            period: Period::Day,
1751            locale: "en".to_string(),
1752            has_time: true,
1753            parts: vec!["time"],
1754            part_of_day: None,
1755        });
1756    }
1757
1758    // Turkish: "[saat ]<H> bucuk" / "[saat ]<H> ceyrek gece" / "[saat ]<H> ceyrek kala"
1759    let tr_s = s.strip_prefix("saat ").unwrap_or(s).trim();
1760    let tr_clock: Option<(u32, u32)> = if let Some(rest) = tr_s.strip_suffix(" bucuk").or_else(|| tr_s.strip_suffix(" buçuk")) {
1761        parse_clock_hour_spec(rest).map(|h| (h, 30))
1762    } else if let Some(rest) = tr_s.strip_suffix(" ceyrek gece").or_else(|| tr_s.strip_suffix(" çeyrek geçe")) {
1763        let base_h = rest.trim().split(['\'', '’']).next().unwrap_or("").trim();
1764        parse_clock_hour_spec(base_h).map(|h| (h, 15))
1765    } else if let Some(rest) = tr_s.strip_suffix(" ceyrek kala").or_else(|| tr_s.strip_suffix(" çeyrek kala")) {
1766        let base_h = rest.trim().split(['\'', '’']).next().unwrap_or("").trim();
1767        parse_clock_hour_spec(base_h).map(|h| (if h == 0 { 23 } else { h - 1 }, 45))
1768    } else {
1769        None
1770    };
1771    if let Some((hh, mm)) = tr_clock {
1772        let nt = NaiveTime::from_hms_opt(hh, mm, 0)?;
1773        let nd = resolve_time_only_date(nt, settings);
1774        return Some(RelativeMatch {
1775            naive: nd.and_time(nt),
1776            period: Period::Day,
1777            locale: "tr".to_string(),
1778            has_time: true,
1779            parts: vec!["time"],
1780            part_of_day: None,
1781        });
1782    }
1783
1784    // English spelled-out clock times ("five thirty pm", "ten fifteen am")
1785    if let Some(nt) = try_english_spelled_clock(s) {
1786        let nd = resolve_time_only_date(nt, settings);
1787        return Some(RelativeMatch {
1788            naive: nd.and_time(nt),
1789            period: Period::Day,
1790            locale: "en".to_string(),
1791            has_time: true,
1792            parts: vec!["time"],
1793            part_of_day: None,
1794        });
1795    }
1796
1797    None
1798}
1799
1800fn try_english_spelled_clock(s: &str) -> Option<NaiveTime> {
1801    let mut t = s.trim();
1802    let mut is_pm = false;
1803    let mut is_am = false;
1804    for suf in ["p.m.", "p.m", "pm"] {
1805        if let Some(rest) = t.strip_suffix(suf) {
1806            t = rest.trim();
1807            is_pm = true;
1808            break;
1809        }
1810    }
1811    if !is_pm {
1812        for suf in ["a.m.", "a.m", "am"] {
1813            if let Some(rest) = t.strip_suffix(suf) {
1814                t = rest.trim();
1815                is_am = true;
1816                break;
1817            }
1818        }
1819    }
1820    if !is_am && !is_pm {
1821        return None;
1822    }
1823    let toks: Vec<&str> = t.split_whitespace().collect();
1824    if toks.len() < 2 || toks.len() > 3 {
1825        return None;
1826    }
1827    let mut h = parse_small_num_or_word(toks[0])? as u32;
1828    if !(1..=12).contains(&h) {
1829        return None;
1830    }
1831    let minute: u32 = match toks[1] {
1832        "o'clock" | "oclock" if toks.len() == 2 => 0,
1833        "oh" if toks.len() == 3 => {
1834            let m = parse_small_num_or_word(toks[2])? as u32;
1835            if m > 9 {
1836                return None;
1837            }
1838            m
1839        }
1840        _ => {
1841            let mut m_val = match toks[1] {
1842                "fifteen" => 15,
1843                "twenty" => 20,
1844                "thirty" => 30,
1845                "forty" => 40,
1846                "fifty" => 50,
1847                "ten" => 10,
1848                "twelve" => 12,
1849                "eleven" => 11,
1850                other => {
1851                    if let Some((l, r)) = other.split_once('-') {
1852                        let lv = match l {
1853                            "twenty" => 20,
1854                            "thirty" => 30,
1855                            "forty" => 40,
1856                            "fifty" => 50,
1857                            _ => return None,
1858                        };
1859                        let rv = parse_small_num_or_word(r)? as u32;
1860                        if rv >= 10 {
1861                            return None;
1862                        }
1863                        lv + rv
1864                    } else {
1865                        return None;
1866                    }
1867                }
1868            };
1869            if toks.len() == 3 {
1870                let ones = parse_small_num_or_word(toks[2])? as u32;
1871                if ones == 0 || ones > 9 || m_val % 10 != 0 || m_val < 20 {
1872                    return None;
1873                }
1874                m_val += ones;
1875            }
1876            m_val
1877        }
1878    };
1879    if is_pm && h < 12 {
1880        h += 12;
1881    } else if is_am && h == 12 {
1882        h = 0;
1883    }
1884    NaiveTime::from_hms_opt(h, minute, 0)
1885}
1886
1887/// Extract a trailing time from strings like "yesterday at 5pm", "hier à 14h30", "dün saat 15:30",
1888/// "어제 오후 2시 30분", "昨日の14:30", or "tomorrow at 5".
1889pub fn extract_trailing_or_leading_time(s: &str) -> (&str, Option<NaiveTime>) {
1890    // Track token (start, end) byte offsets safely inside `s`
1891    let mut ranges: Vec<(usize, usize)> = Vec::new();
1892    let mut in_tok = false;
1893    let mut tok_start = 0usize;
1894    for (idx, ch) in s.char_indices() {
1895        if ch.is_whitespace() {
1896            if in_tok {
1897                ranges.push((tok_start, idx));
1898                in_tok = false;
1899            }
1900        } else if !in_tok {
1901            tok_start = idx;
1902            in_tok = true;
1903        }
1904    }
1905    if in_tok {
1906        ranges.push((tok_start, s.len()));
1907    }
1908
1909    // 1. Multi-token trailing time suffixes (2..=4 tokens, e.g. "오후 2시 30분", "pm 2:26", "5:30 pm")
1910    if ranges.len() >= 3 {
1911        let max_k = (ranges.len() - 1).min(4);
1912        for k in (2..=max_k).rev() {
1913            let cut = ranges[ranges.len() - k].0;
1914            let cand = s[cut..].trim();
1915            if let Some(t) = parse_time_str(cand) {
1916                return (s[..cut].trim_end(), Some(t));
1917            }
1918        }
1919    }
1920
1921    // 2. Single trailing time token or bare hour after explicit time preposition ("tomorrow at 5")
1922    if ranges.len() >= 2 {
1923        let (last_s, last_e) = ranges[ranges.len() - 1];
1924        let last = &s[last_s..last_e];
1925        if last.contains(':')
1926            || last.contains('h')
1927            || last.contains('시')
1928            || last.contains('時')
1929            || last.contains('时')
1930            || last.contains('点')
1931            || last.ends_with("am")
1932            || last.ends_with("pm")
1933            || last.ends_with("a.m.")
1934            || last.ends_with("p.m.")
1935        {
1936            if let Some(t) = parse_time_str(last) {
1937                return (s[..last_s].trim_end(), Some(t));
1938            }
1939        }
1940
1941        if ranges.len() >= 3 {
1942            let (prev_s, prev_e) = ranges[ranges.len() - 2];
1943            let prev = &s[prev_s..prev_e];
1944            if matches!(
1945                prev,
1946                "at" | "um" | "à" | "saat" | "alle" | "kl" | "klo" | "las" | "às" | "в" | "o" | "om"
1947            ) && (1..=2).contains(&last.len())
1948                && last.bytes().all(|b| b.is_ascii_digit())
1949            {
1950                if let Ok(h) = last.parse::<u32>() {
1951                    if h <= 23 {
1952                        if let Some(t) = NaiveTime::from_hms_opt(h, 0, 0) {
1953                            return (s[..prev_s].trim_end(), Some(t));
1954                        }
1955                    }
1956                }
1957            }
1958        }
1959    }
1960
1961    // 3. Spaceless CJK / Korean relative + time ("昨日の14:30", "昨日14:30", "昨日の午後2時30分", "어제14:30")
1962    if let Some((left, right)) = s.rsplit_once('の') {
1963        if let Some(t) = parse_time_str(right.trim()) {
1964            let prefix = left.trim_end();
1965            if !prefix.is_empty() {
1966                return (prefix, Some(t));
1967            }
1968        }
1969    }
1970    if s.contains(':') || s.contains('時') || s.contains('点') || s.contains('시') {
1971        for marker in ["午前", "午後", "上午", "下午", "오전", "오후"] {
1972            if let Some(pos) = s.rfind(marker) {
1973                if pos > 0 {
1974                    if let Some(t) = parse_time_str(&s[pos..]) {
1975                        let prefix = s[..pos].trim_end_matches(|c: char| c.is_whitespace() || c == 'の');
1976                        if !prefix.is_empty() {
1977                            return (prefix, Some(t));
1978                        }
1979                    }
1980                }
1981            }
1982        }
1983        let mut prev_non_ascii = false;
1984        for (idx, ch) in s.char_indices() {
1985            if idx > 0 && ch.is_ascii_digit() && prev_non_ascii && s.len() - idx <= 32 {
1986                if let Some(t) = parse_time_str(&s[idx..]) {
1987                    let prefix = s[..idx].trim_end_matches(|c: char| c.is_whitespace() || c == 'の');
1988                    if !prefix.is_empty() {
1989                        return (prefix, Some(t));
1990                    }
1991                }
1992            }
1993            prev_non_ascii = !ch.is_ascii() && !ch.is_whitespace() && ch != 'の';
1994        }
1995    }
1996
1997    (s, None)
1998}
1999
2000fn strip_connector_words<'a>(s: &'a str, loc: &CompiledLocale) -> &'a str {
2001    let mut cur = s.trim();
2002    loop {
2003        let mut trimmed = false;
2004        if let Some(stripped) = cur.strip_suffix('の') {
2005            if !stripped.is_empty() {
2006                cur = stripped.trim_end();
2007                trimmed = true;
2008            }
2009        } else if let Some(sp) = cur.rfind(' ') {
2010            let tail = &cur[sp + 1..];
2011            if matches!(
2012                tail,
2013                "at" | "on" | "à" | "a" | "um" | "am" | "saat" | "las" | "às" | "в" | "о"
2014                    | "o" | "om" | "alle" | "kl" | "klo" | "la" | "pukul" | "lúc" | "στις"
2015                    | "בשעה" | "الساعة"
2016            ) || loc.skip.contains(tail)
2017            {
2018                cur = cur[..sp].trim_end();
2019                trimmed = true;
2020            }
2021        }
2022        if !trimmed {
2023            break;
2024        }
2025    }
2026    cur
2027}