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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
"""Russian calendar expressions anchored exclusively to call metadata.

Calendar periods describe uncertainty, NOT the lifetime of a fact. In particular,
``period_end`` must never be copied to ``valid_to`` automatically. The extractor
must associate each expression with a fact before choosing its start/end time.
"""

from __future__ import annotations

import argparse
import calendar
from dataclasses import asdict, dataclass, replace
from datetime import datetime, timedelta
import json
from pathlib import Path
import re
from typing import Literal

from .temporal import (
    FIRST_MONTH_DAY_PATTERN, NAMED_DAYS, QUANTITY_PATTERN, UNIT_FORMS, WEEKDAY_PATTERNS, normalize_time,
)

Direction = Literal["auto", "past", "future"]
WEEKDAYS = {
    "понедельник": 0, "понедельника": 0,
    "вторник": 1, "вторника": 1,
    "среда": 2, "среду": 2, "среды": 2,
    "четверг": 3, "четверга": 3,
    "пятница": 4, "пятницу": 4, "пятницы": 4,
    "суббота": 5, "субботу": 5, "субботы": 5,
    "воскресенье": 6, "воскресенья": 6,
}
MONTHS = {name: i + 1 for i, name in enumerate((
    "января", "февраля", "марта", "апреля", "мая", "июня", "июля",
    "августа", "сентября", "октября", "ноября", "декабря",
))}
NUMBERS = {
    "один": 1, "одного": 1, "одну": 1, "одна": 1,
    "два": 2, "две": 2, "двух": 2, "три": 3, "трех": 3,
    "четыре": 4, "четырех": 4, "пять": 5, "пяти": 5,
    "шесть": 6, "шести": 6, "семь": 7, "семи": 7,
    "восемь": 8, "восьми": 8, "девять": 9, "девяти": 9,
    "десять": 10, "десяти": 10, "одиннадцать": 11, "одиннадцати": 11,
    "двенадцать": 12, "двенадцати": 12, "тринадцать": 13,
    "четырнадцать": 14, "пятнадцать": 15, "шестнадцать": 16,
    "семнадцать": 17, "восемнадцать": 18, "девятнадцать": 19,
    "двадцать": 20, "двадцать один": 21, "двадцать два": 22,
    "двадцать три": 23, "тридцать": 30,
}


def alternatives(items) -> str:
    return "(?:" + "|".join(map(re.escape, sorted(items, key=len, reverse=True))) + ")"


NUMBER = rf"(?:\d{{1,3}}|{alternatives(NUMBERS)})"
WEEKDAY = alternatives(WEEKDAYS)
MONTH = alternatives(MONTHS)
DATE_PATTERN = re.compile(
    rf"(?<!\w)(?:"
    rf"(?:(?:с|со|до|после|на|к|в)\s+)?(?:"
    rf"(?P<numeric>\d{{1,2}}[./]\d{{1,2}}(?:[./]\d{{4}})?)|"
    rf"(?P<named>\d{{1,2}}\s+{MONTH}(?:\s+\d{{4}}(?:\s+года)?)?))|"
    rf"(?P<relative>(?:с|со|до|на|за)\s+)?(?P<day>позавчера|послезавтра|вчера|сегодня|завтра)|"
    rf"(?P<duration>(?:через\s+(?:{NUMBER}\s+)?(?:день|дня|дней|сутки|неделю|недели|недель|месяц|месяца|месяцев|год|года|лет|час|часа|часов|минуту|минуты|минут)|"
    rf"(?:{NUMBER}\s+)?(?:день|дня|дней|сутки|неделю|недели|недель|месяц|месяца|месяцев|год|года|лет|час|часа|часов|минуту|минуты|минут)\s+назад))|"
    rf"(?P<weekday>(?:(?:в|во|с|со|до|на)\s+)?(?:(?:прошл\w*|следующ\w*|ближайш\w*|этот|эту|это)\s+)?{WEEKDAY}(?:\s+на\s+(?:прошлой|следующей|этой)\s+неделе)?)|"
    rf"(?P<period>(?:в|на)\s+(?:прошлом|прошлой|следующем|следующей|этом|этой)\s+(?:месяце|неделе|году))"
    rf")(?!\w)", re.IGNORECASE,
)
TIME_PATTERN = re.compile(
    rf"(?<!\w)(?:(?P<prefix>в|после|до|к)\s+(?P<hour>{NUMBER})(?::(?P<minute>\d{{2}}))?"
    rf"|(?P<clock>\d{{1,2}}):(?P<clock_minute>\d{{2}}))"
    rf"(?:\s+час(?:а|ов)?)?(?:\s+(?P<part>утра|дня|вечера|ночи))?(?!\w)",
    re.IGNORECASE,
)


@dataclass(frozen=True)
class TemporalMatch:
    text: str
    span: tuple[int, int]
    value: str | None
    precision: str
    rule: str
    relation: str = "at"
    period_end: str | None = None
    candidates: tuple[str, ...] = ()
    note: str | None = None


def parse_anchor(started_at: str) -> datetime:
    if not isinstance(started_at, str) or not started_at.strip():
        raise ValueError("Call metadata must contain a nonempty started_at")
    if "T" not in started_at and " " not in started_at:
        raise ValueError("started_at must include a date and time")
    try:
        return datetime.fromisoformat(started_at.replace("Z", "+00:00"))
    except ValueError as exc:
        raise ValueError(f"Invalid call started_at: {started_at!r}") from exc


def _iso(value: datetime) -> str:
    return value.isoformat(timespec="seconds")


def _midnight(value: datetime) -> datetime:
    return value.replace(hour=0, minute=0, second=0, microsecond=0)


def _month_shift(value: datetime, months: int) -> datetime:
    year, month = divmod(value.year * 12 + value.month - 1 + months, 12)
    month += 1
    day = min(value.day, calendar.monthrange(year, month)[1])
    return value.replace(year=year, month=month, day=day)


def _number(value: str) -> int:
    return int(value) if value.isdigit() else NUMBERS[value]


def _relation(text: str) -> str:
    if re.match(r"с(?:о)?\s", text):
        return "since"
    if text.startswith("до "):
        return "before"
    if text.startswith("после "):
        return "after"
    return "at"


def _date_match(match: re.Match, anchor: datetime, direction: Direction) -> TemporalMatch:
    phrase = match.group()
    base = _midnight(anchor)
    value = None
    end = None
    precision = "day"
    candidates = ()
    note = None
    rule = next(name for name in ("numeric", "named", "day", "duration", "weekday", "period")
                if match.group(name))
    try:
        if rule in ("numeric", "named"):
            if rule == "numeric":
                parts = re.split(r"[./]", match.group("numeric"))
                day, month = map(int, parts[:2])
                year = int(parts[2]) if len(parts) == 3 else None
            else:
                parts = match.group("named").split()
                day, month = int(parts[0]), MONTHS[parts[1]]
                year = int(parts[2]) if len(parts) >= 3 else None
            if year is not None:
                value = base.replace(year=year, month=month, day=day)
            else:
                # Search adjacent years also handles Feb 29 without inventing Feb 28.
                valid = []
                for candidate_year in range(anchor.year - 4, anchor.year + 5):
                    try:
                        valid.append(base.replace(year=candidate_year, month=month, day=day))
                    except ValueError:
                        continue
                if direction == "past":
                    value = max((v for v in valid if v <= base), default=None)
                elif direction == "future":
                    value = min((v for v in valid if v >= base), default=None)
                else:
                    value = next((v for v in valid if v.year == anchor.year), None)
                    note = "Year taken from started_at; specify direction for a year boundary"
                if value is None:
                    raise ValueError("No valid calendar date")
        elif rule == "day":
            offset = {"позавчера": -2, "вчера": -1, "сегодня": 0, "завтра": 1, "послезавтра": 2}
            value = base + timedelta(days=offset[match.group("day")])
        elif rule == "duration":
            future = phrase.startswith("через ")
            body = phrase.removeprefix("через ").removesuffix(" назад")
            unit = body.split()[-1]
            count_text = body[:-(len(unit))].strip()
            count = _number(count_text) if count_text else 1
            count *= 1 if future else -1
            if unit.startswith("месяц"):
                value = _month_shift(base, count)
            elif unit in ("год", "года", "лет"):
                value = _month_shift(base, count * 12)
            elif unit.startswith("недел"):
                value = base + timedelta(weeks=count)
            elif unit.startswith("час") or unit.startswith("минут"):
                value = anchor + timedelta(minutes=count * (60 if unit.startswith("час") else 1))
                precision = "minute"
            else:
                value = base + timedelta(days=count)
        elif rule == "weekday":
            weekday = next(WEEKDAYS[w] for w in re.findall(r"\w+", phrase) if w in WEEKDAYS)
            past = base - timedelta(days=(base.weekday() - weekday) % 7)
            future = base + timedelta(days=(weekday - base.weekday()) % 7)
            if "неделе" in phrase:
                offset = -1 if "прошлой" in phrase else 1 if "следующей" in phrase else 0
                value = base - timedelta(days=base.weekday()) + timedelta(days=7 * offset + weekday)
            elif re.search(r"\bпрошл", phrase):
                value = past if past < base else past - timedelta(days=7)
            elif re.search(r"\bследующ", phrase):
                value = future if future > base else future + timedelta(days=7)
                note = "Next weekday means the next strictly later occurrence"
            elif re.search(r"\b(?:этот|эту|это)\b", phrase):
                value = base - timedelta(days=base.weekday()) + timedelta(days=weekday)
            elif _relation(phrase) == "since" or direction == "past":
                value = past
            elif direction == "future" or "ближайш" in phrase:
                value = future
            elif past == future:
                value = base
            else:
                candidates = (_iso(past), _iso(future))
                note = "Weekday needs past/future context"
        elif rule == "period":
            offset = -1 if "прошл" in phrase else 1 if "следующ" in phrase else 0
            if "месяце" in phrase:
                precision = "month"
                value = _month_shift(base.replace(day=1), offset)
                end = _month_shift(value, 1)
            elif "неделе" in phrase:
                precision = "week"
                value = base - timedelta(days=base.weekday()) + timedelta(weeks=offset)
                end = value + timedelta(days=7)
            else:
                precision = "year"
                value = base.replace(year=base.year + offset, month=1, day=1)
                end = value.replace(year=value.year + 1)
            note = "Calendar period; exact day is unknown"
    except (ValueError, OverflowError):
        note = "Invalid or unsupported calendar date"
        value = None
    if value is not None and end is None and precision == "day":
        end = value + timedelta(days=1)
    return TemporalMatch(phrase, match.span(), _iso(value) if value else None, precision,
                         rule, _relation(phrase), _iso(end) if end else None, candidates, note)


def normalize_dates(text: str, started_at: str, *, direction: Direction = "auto",
                    business_hours: bool = False) -> list[TemporalMatch]:
    """Find dates without rewriting text; offsets always refer to the original.

    ``direction`` resolves unqualified weekdays and yearless dates. Explicit
    yesterday/tomorrow or past/next modifiers override it. Naive metadata stays
    naive; an explicit UTC offset is preserved. No host date/time is consulted.
    ``business_hours`` explicitly interprets 1..7 without AM/PM as 13..19.
    """
    if direction not in ("auto", "past", "future"):
        raise ValueError("direction must be auto, past or future")
    anchor = parse_anchor(started_at)
    normalized = text.lower().replace("ё", "е")
    dates = [_date_match(m, anchor, direction) for m in DATE_PATTERN.finditer(normalized)]
    dates = [replace(m, text=text[m.span[0]:m.span[1]]) for m in dates]
    for time_match in TIME_PATTERN.finditer(normalized):
        if any(a.span[0] < time_match.end() and time_match.start() < a.span[1] for a in dates):
            continue
        # Avoid treating 'в 3 дня' and 'в 2026 году' as a clock time.
        if re.match(r"\s+(?:дн|день|недел|месяц|год|лет)", normalized[time_match.end():]):
            continue
        hour = _number(time_match.group("hour") or time_match.group("clock"))
        minute = int(time_match.group("minute") or time_match.group("clock_minute") or 0)
        if hour > 23 or minute > 59:
            continue
        part = time_match.group("part")
        note = None
        if part in ("дня", "вечера") and 1 <= hour < 12:
            hour += 12
        elif part == "ночи" and hour == 12:
            hour = 0
        elif business_hours and not part and 1 <= hour <= 7:
            hour += 12
            note = "Afternoon assumed by explicit business_hours policy"
        unqualified = not part and not business_hours and 1 <= hour < 12 and not (
            time_match.group("minute") or time_match.group("clock"))
        previous = next((m for m in reversed(dates) if m.span[1] <= time_match.start()
                         and not normalized[m.span[1]:time_match.start()].strip(" ,")), None)
        day_value = datetime.fromisoformat(previous.value) if previous and previous.value else _midnight(anchor)
        value = day_value.replace(hour=hour, minute=minute, second=0, microsecond=0)
        candidates = ()
        if previous and previous.precision in ("week", "month", "year"):
            resolved = None
            note = "Clock time does not identify a day within the calendar period"
        elif previous and previous.value is None:
            hours = (hour, hour + 12) if unqualified else (hour,)
            candidates = tuple(_iso(datetime.fromisoformat(c).replace(hour=h, minute=minute))
                               for c in previous.candidates for h in hours)
            resolved = None
            note = (previous.note or "Date is ambiguous") + ("; hour also needs context" if unqualified else "")
        elif unqualified:
            candidates = (_iso(value), _iso(value.replace(hour=hour + 12)))
            resolved = None
            note = "Hour needs morning/afternoon context"
        else:
            resolved = _iso(value)
        start = previous.span[0] if previous else time_match.start()
        relation = _relation(time_match.group())
        if previous and relation == "at":
            relation = previous.relation
        if previous:
            dates.remove(previous)
        dates.append(TemporalMatch(text[start:time_match.end()], (start, time_match.end()),
                                   resolved, "minute", "date_and_time" if previous else "time",
                                   relation, candidates=candidates, note=note))
    return sorted(dates, key=lambda m: m.span)


def normalize_call_dates(call: dict, *, direction: Direction = "auto",
                         business_hours: bool = False) -> dict:
    """Return temporal mentions per turn, without reading or modifying gold facts."""
    anchor = parse_anchor(call.get("started_at"))
    return {"call_id": call["call_id"], "started_at": _iso(anchor),
            "weekday": anchor.weekday(), "turns": [
                {"turn_idx": turn["idx"], "speaker": turn["speaker"],
                 "dates": [asdict(m) for m in normalize_dates(
                     turn["text"], call["started_at"], direction=direction,
                     business_hours=business_hours)]}
                for turn in call["turns"]]}


_UNITS = {form: unit for unit, forms in UNIT_FORMS.items() for form in forms}
_UNIT_PATTERN = "(?:" + "|".join(_UNITS) + ")"
_PATTERNS = (
    (FIRST_MONTH_DAY_PATTERN, "first_month_day"),
    (re.compile(r"\b(?P<name>" + "|".join(NAMED_DAYS) + r")\b", re.I), None),
    (re.compile(rf"\b(?:через|спустя)\s+(?:{QUANTITY_PATTERN}\s+)?(?P<unit>{_UNIT_PATTERN})\b", re.I), "after"),
    (re.compile(rf"\b(?:{QUANTITY_PATTERN}\s+)?(?P<unit>{_UNIT_PATTERN})\s+назад\b", re.I), "before"),
    (re.compile(r"\b[0-9]{1,2}\s+(?:января|февраля|марта|апреля|мая|июня|июля|"
                r"августа|сентября|октября|ноября|декабря)(?:\s+[0-9]{4})?\b", re.I), "date"),
)
_ADJACENT_CLOCK = re.compile(r"\s+(?:в|к)\s+[0-9]{1,2}:[0-9]{2}(?![0-9:])", re.I)
_NEGATED = re.compile(r"\bне\s+$", re.I)


def source_candidates(anchor, text):
    for pattern, mode in _PATTERNS:
        for match in pattern.finditer(text):
            if mode is None:
                kind = NAMED_DAYS[match["name"].lower()][0]
            elif mode == "date":
                kind = mode
            elif mode == "first_month_day":
                kind = "months_before" if match["relation"].lower() == "прошлого" else "months_after"
            else:
                kind = f"{_UNITS[match['unit'].lower()]}_{mode}"
            left, right = match.span()
            if _NEGATED.search(text[:left]):
                continue
            clock = _ADJACENT_CLOCK.match(text, right)
            if clock:
                right = clock.end()
            quote = text[left:right]
            value = normalize_time(anchor, quote, kind)
            if value is None and clock:
                right = match.end()
                quote = text[left:right]
                value = normalize_time(anchor, quote, kind)
            if value is not None:
                yield value, kind, left, right, quote


_WEEKDAY = re.compile(r"\b(?:" + "|".join(WEEKDAY_PATTERNS) + r")\b", re.I)
_WEEKDAY_MODIFIER = re.compile(r"\b(прошл\w*|следующ\w*|ближайш\w*)\s*$", re.I)
_CLOCK_PHRASE = re.compile(r"\b(?:в|к)\s+([0-9]{1,2})(?::([0-9]{2})|\s+час\w*)\b", re.I)
_AFTER_TWO = re.compile(r"\bпосле двух\b", re.I)


def _weekday_options(anchor, text):
    for match in _WEEKDAY.finditer(text):
        modifier = _WEEKDAY_MODIFIER.search(text[:match.start()])
        kinds = ("weekday_before", "weekday_after")
        left = match.start()
        if modifier:
            left = modifier.start()
            kinds = ("weekday_before",) if modifier[1].lower().startswith("прошл") else ("weekday_after",)
        if _NEGATED.search(text[:left]):
            continue
        for kind in kinds:
            value = normalize_time(anchor, match.group(), kind)
            if value is not None:
                yield value, left, match.end()
        if modifier is None and re.fullmatch(WEEKDAY_PATTERNS[anchor.weekday()], match.group(), re.I):
            yield anchor, left, match.end()


def temporal_candidates(call):
    """Return timestamp candidates with source positions, without reading gold."""
    anchor = datetime.fromisoformat(call["started_at"])
    midnight = anchor.replace(hour=0, minute=0, second=0, microsecond=0)
    candidates = [(None, -1), (midnight.isoformat(), -1), (anchor.isoformat(), -1)]
    for position, turn in enumerate(call["turns"]):
        text = turn["text"]
        mentions = [(value, left, right) for value, _, left, right, _ in source_candidates(anchor, text)]
        mentions.extend(_weekday_options(midnight, text))
        for value, left, right in mentions:
            candidates.append((value.isoformat(), position))
            # The evaluator uses day granularity, and some annotations omit spoken hours.
            if value.hour or value.minute:
                candidates.append((value.replace(hour=0, minute=0).isoformat(), position))
        clocks = [(match.start(), match.end(), int(match[1]), int(match[2] or 0))
                  for match in _CLOCK_PHRASE.finditer(text)]
        clocks.extend((match.start(), match.end(), 14, 0) for match in _AFTER_TWO.finditer(text))
        for start, end, hour, minute in clocks:
            if hour >= 24 or minute >= 60 or any(left <= start < right for _, left, right in mentions):
                continue
            neighbors = [value for value, left, right in mentions
                         if 0 <= start - right <= 2 or 0 <= left - end <= 2]
            if not neighbors and not mentions:
                neighbors = [midnight]
            for value in neighbors:
                candidates.append((value.replace(hour=hour, minute=minute).isoformat(), position))
    return [{"value": value, "turn": position} for value, position in dict.fromkeys(candidates)]


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("input", type=Path, help="Calls JSONL")
    parser.add_argument("output", type=Path, help="New temporal-mentions JSONL")
    parser.add_argument("--direction", choices=("auto", "past", "future"), default="auto")
    parser.add_argument("--business-hours", action="store_true")
    args = parser.parse_args()
    from compact_fact_extraction.data import read_calls
    args.output.parent.mkdir(parents=True, exist_ok=True)
    with args.input.open(encoding="utf-8") as src, args.output.open("x", encoding="utf-8") as dst:
        for call in read_calls(src):
            result = normalize_call_dates(call, direction=args.direction, business_hours=args.business_hours)
            dst.write(json.dumps(result, ensure_ascii=False) + "\n")


if __name__ == "__main__":
    main()