Skip to main content

dateoxide_core/
relative.rs

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