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
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
"""
Temporal data parsing and normalization.

Handles inconsistent date/time formats across 20 years of data,
including filename dates, timestamp strings, and timezone handling.
"""

from pathlib import Path
from typing import Optional, List, Tuple
from datetime import datetime
import re
import pytz
from dateutil import parser as dateutil_parser

from ..core.base_classes import BaseCleaner
from ..core.config import Config
from ..core.errata_logger import ErrataLogger
from ..core.exceptions import TemporalError


class TemporalParser(BaseCleaner):
    """
    Parses and normalizes temporal data.

    Handles:
    - Multiple date/time formats
    - Timezone normalization
    - Filename date extraction
    - Validation against reasonable date ranges
    """

    def __init__(self, config: Config, errata_logger: Optional[ErrataLogger] = None):
        """
        Initialize temporal parser.

        Args:
            config: Configuration object
            errata_logger: Optional errata logger for error tracking
        """
        super().__init__(config, errata_logger)

        # Get configuration
        self.date_formats: List[str] = config.get(
            'temporal.date_formats',
            [
                '%a %b %d %H:%M:%S %Y',
                '%Y-%m-%d %H:%M:%S',
                '%m/%d/%Y %H:%M:%S',
                '%Y%m%d'
            ]
        )
        from datetime import datetime as _dt
        self.min_year: int = config.get('temporal.min_year', 2000)
        self.max_year: int = config.get('temporal.max_year', _dt.now().year)
        self.timezone_name: str = config.get('temporal.timezone', 'America/Los_Angeles')

        try:
            self.timezone = pytz.timezone(self.timezone_name)
        except pytz.exceptions.UnknownTimeZoneError:
            self.timezone = pytz.UTC

    def parse_date(
        self,
        date_string: str,
        file_path: Optional[str] = None
    ) -> Optional[datetime]:
        """
        Parse date string into datetime object.

        Tries multiple formats in sequence.

        Args:
            date_string: Date string to parse
            file_path: Optional file path for error logging

        Returns:
            datetime object or None if parsing fails
        """
        if not date_string or not isinstance(date_string, str):
            return None

        date_string = date_string.strip()

        # Handle empty/null strings
        if date_string.lower() in ('nan', 'none', 'null', ''):
            return None

        # Reject values too short to be a date (e.g. "1", "0", "+2.24")
        if len(date_string) < 6:
            return None

        # Skip obvious non-date values (file paths, URLs, etc.)
        if any(indicator in date_string.lower() for indicator in ['.jpg', '.png', '.gif', '.dat', '/', '\\']):
            # Check if it contains common path separators or file extensions
            if '/' in date_string or '\\' in date_string or date_string.lower().endswith(('.jpg', '.png', '.gif', '.dat', '.txt', '.csv')):
                return None

        # Convert underscores to spaces (Thu_Dec_20_00:13:03_2018 -> Thu Dec 20 00:13:03 2018)
        date_string = date_string.replace('_', ' ')

        # Apply year correction patterns before parsing
        date_string = self._correct_year_typos(date_string, file_path)

        # Try configured formats first
        for fmt in self.date_formats:
            try:
                dt = datetime.strptime(date_string, fmt)
                return self._validate_and_localize(dt, file_path)
            except (ValueError, TemporalError):
                continue

        # Try dateutil parser as fallback (more flexible)
        # Use a fixed default date so we can detect when dateutil guessed the year
        _sentinel = datetime(1, 1, 1)
        try:
            dt = dateutil_parser.parse(date_string, default=_sentinel)
            if dt.year == 1:
                # dateutil filled in the sentinel year — input had no year
                self.log_error(
                    'date_parse_failed',
                    f"Incomplete date (no year): '{date_string}'",
                    file_path=file_path
                )
                return None
            return self._validate_and_localize(dt, file_path)
        except (ValueError, TemporalError, dateutil_parser.ParserError):
            pass

        # All parsing attempts failed
        self.log_error(
            'date_parse_failed',
            f"Could not parse date: '{date_string}'",
            file_path=file_path
        )
        return None

    def _correct_year_typos(
        self,
        date_string: str,
        file_path: Optional[str] = None
    ) -> str:
        """
        Correct common year typos in date strings.

        Common patterns:
        - 0202 -> 2002 (leading 2 dropped)

        Args:
            date_string: Date string to correct
            file_path: Optional file path for error logging

        Returns:
            Corrected date string
        """
        # Pattern: Year 0202 -> 2002 (leading 2 dropped)
        # Anchor to word boundary so we only match standalone year tokens,
        # not substrings inside coordinates or other numeric fields.
        year_pattern = r'\b0(20[0-2])\b'
        if re.search(year_pattern, date_string):
            original = date_string
            date_string = re.sub(year_pattern, r'2\1', date_string)
            self.log_error(
                'year_corrected',
                f"Corrected year 0xxx -> 2xxx: '{original}' -> '{date_string}'",
                file_path=file_path
            )

        # Pattern: Year in format like "Sep 04 0202"
        # Only replace when the typo year appears at the END of the string
        # (i.e. in year position), not in the middle of other data.
        end_year_match = re.search(r'\b(0202|0201|0200)$', date_string)
        if end_year_match:
            year_corrections = {
                '0202': '2002',
                '0201': '2001',
                '0200': '2000',
            }
            typo = end_year_match.group(1)
            correct = year_corrections[typo]
            original = date_string
            date_string = date_string[:end_year_match.start()] + correct + date_string[end_year_match.end():]
            self.log_error(
                'year_corrected',
                f"Corrected trailing year {typo} -> {correct}: '{original}' -> '{date_string}'",
                file_path=file_path
            )

        return date_string

    def _validate_and_localize(
        self,
        dt: datetime,
        file_path: Optional[str] = None
    ) -> datetime:
        """
        Validate datetime is in reasonable range and localize to timezone.

        Args:
            dt: datetime to validate
            file_path: Optional file path for error logging

        Returns:
            Validated and localized datetime

        Raises:
            TemporalError: If date is out of valid range
        """
        # Check year range
        if dt.year < self.min_year or dt.year > self.max_year:
            self.log_error(
                'date_out_of_range',
                f"Date {dt} outside valid range ({self.min_year}-{self.max_year})",
                file_path=file_path
            )
            raise TemporalError(f"Date out of range: {dt}")

        # Localize to timezone if naive
        if dt.tzinfo is None:
            dt = self.timezone.localize(dt)
        else:
            # Convert to target timezone
            dt = dt.astimezone(self.timezone)

        return dt

    def parse_dates_vectorized(
        self,
        series: 'pd.Series',
        file_path: Optional[str] = None
    ) -> 'pd.Series':
        """
        Parse a Series of date strings vectorized, with per-row fallback.

        Uses pd.to_datetime with the primary format first (5x faster than
        per-row .apply), then falls back to parse_date() for any failures.

        Args:
            series: Series of date strings
            file_path: Optional file path for error logging

        Returns:
            Series of parsed datetime objects (timezone-aware)
        """
        import pandas as pd

        # Strip whitespace
        cleaned = series.astype(str).str.strip()

        # Replace underscores (Thu_Dec_20_00:13:03_2018 -> Thu Dec 20 00:13:03 2018)
        cleaned = cleaned.str.replace('_', ' ', regex=False)

        # Try primary format vectorized (covers ~99% of timestamps)
        primary_fmt = self.date_formats[0] if self.date_formats else '%a %b %d %H:%M:%S %Y'
        result = pd.to_datetime(cleaned, format=primary_fmt, errors='coerce')

        # Localize to timezone (always, so result dtype is tz-aware for fallback assignment)
        successful = result.notna()
        # ambiguous=False: during DST fall-back, pick standard time rather than
        # nulling the timestamp (the old 'NaT' policy silently dropped ~1 hour of
        # data per year). nonexistent='shift_forward': spring-forward gaps get
        # shifted to the next valid instant instead of becoming NaT.
        result = result.dt.tz_localize(self.timezone, ambiguous=False, nonexistent='shift_forward')

        # Validate year range on successful parses
        if successful.any():
            out_of_range = successful & (
                (result.dt.year < self.min_year) | (result.dt.year > self.max_year)
            )
            if out_of_range.any():
                result[out_of_range] = pd.NaT

        # Fall back to per-row parsing for failures
        failed = result.isna() & cleaned.notna() & (cleaned != 'nan') & (cleaned != '')
        if failed.any():
            import warnings
            with warnings.catch_warnings():
                warnings.simplefilter('ignore')
                fallback = cleaned[failed].apply(
                    lambda x: self.parse_date(x, file_path=file_path)
                )
                fallback = pd.to_datetime(fallback, utc=True).dt.tz_convert(self.timezone)
                result = result.copy()
                result.loc[failed] = fallback

        return result

    def extract_date_from_filename(
        self,
        filename: str,
        pattern: Optional[str] = None
    ) -> Optional[datetime]:
        """
        Extract date from filename using pattern.

        Default pattern matches formats like: cardD010102.dat (YYMMDD)

        Args:
            filename: Filename to extract date from
            pattern: Optional regex pattern (defaults to YYMMDD)

        Returns:
            datetime object or None if extraction fails
        """
        if pattern is None:
            # Default pattern: 6 digits representing YYMMDD
            pattern = r'(\d{6})'

        match = re.search(pattern, filename)
        if not match:
            return None

        date_str = match.group(1)

        # Parse YYMMDD format
        if len(date_str) == 6:
            try:
                yy = int(date_str[0:2])
                mm = int(date_str[2:4])
                dd = int(date_str[4:6])

                # Assume 20xx for YY
                year = 2000 + yy

                dt = datetime(year, mm, dd)
                return self._validate_and_localize(dt)

            except (ValueError, TemporalError):
                return None

        # Try other date string parsing
        return self.parse_date(date_str)

    def clean(
        self,
        data: str,
        file_path: Optional[str] = None,
        **kwargs
    ) -> Optional[datetime]:
        """
        Parse date string into normalized datetime.

        Args:
            data: Date string to parse
            file_path: Optional file path for error logging
            **kwargs: Additional parameters

        Returns:
            datetime object or None if parsing fails
        """
        return self.parse_date(data, file_path=file_path)

    def parse_batch(
        self,
        date_strings: List[str],
        file_path: Optional[str] = None
    ) -> List[Optional[datetime]]:
        """
        Parse a batch of date strings.

        Args:
            date_strings: List of date strings
            file_path: Optional file path for error logging

        Returns:
            List of datetime objects (None for failed parses)
        """
        return [
            self.parse_date(ds, file_path=file_path)
            for ds in date_strings
        ]

    def format_datetime(
        self,
        dt: datetime,
        format_str: str = '%Y-%m-%d %H:%M:%S'
    ) -> str:
        """
        Format datetime to string.

        Args:
            dt: datetime object
            format_str: Output format string

        Returns:
            Formatted date string
        """
        return dt.strftime(format_str)

    def get_date_range(
        self,
        datetimes: List[datetime]
    ) -> Tuple[datetime, datetime]:
        """
        Get min and max dates from list of datetimes.

        Args:
            datetimes: List of datetime objects

        Returns:
            Tuple of (min_date, max_date)

        Raises:
            TemporalError: If list is empty
        """
        valid_dts = [dt for dt in datetimes if dt is not None]

        if not valid_dts:
            raise TemporalError("No valid datetimes in list")

        return min(valid_dts), max(valid_dts)