| 1 | """Date utilities for last30days skill.""" |
| 2 | |
| 3 | from datetime import date, datetime, timedelta, timezone |
| 4 | import math |
| 5 | import re |
| 6 | from typing import Optional, Tuple |
| 7 | |
| 8 | |
| 9 | def x_date_filters(from_date: str, to_date: str) -> str: |
| 10 | """Translate an inclusive research window to X search operators.""" |
| 11 | filters = f"since:{from_date}" |
| 12 | end = date.fromisoformat(to_date) |
| 13 | if end != date.max: |
| 14 | filters += f" until:{(end + timedelta(days=1)).isoformat()}" |
| 15 | return filters |
| 16 | |
| 17 | |
| 18 | def parse_as_of_date(as_of_date: Optional[str]) -> Optional[str]: |
| 19 | """Validate and normalize an --as-of date. |
| 20 | |
| 21 | Args: |
| 22 | as_of_date: Date string in YYYY-MM-DD format. |
| 23 | |
| 24 | Returns: |
| 25 | Normalized YYYY-MM-DD string, or None when no date was provided. |
| 26 | |
| 27 | Raises: |
| 28 | ValueError: If the date is not in YYYY-MM-DD format. |
| 29 | """ |
| 30 | if as_of_date is None: |
| 31 | return None |
| 32 | |
| 33 | if not as_of_date.strip(): |
| 34 | raise ValueError("--as-of must be in YYYY-MM-DD format.") |
| 35 | |
| 36 | try: |
| 37 | parsed = datetime.strptime(as_of_date, "%Y-%m-%d").date() |
| 38 | except ValueError as exc: |
| 39 | raise ValueError( |
| 40 | f"Invalid --as-of date: {as_of_date}. Expected YYYY-MM-DD." |
| 41 | ) from exc |
| 42 | |
| 43 | return parsed.isoformat() |
| 44 | |
| 45 | |
| 46 | def get_date_range(days: int = 30, as_of_date: Optional[str] = None) -> Tuple[str, str]: |
| 47 | """Get the date range for the last N days. |
| 48 | |
| 49 | When as_of_date is provided, the range ends at that date instead of today. |
| 50 | |
| 51 | Args: |
| 52 | days: Number of days to look back. |
| 53 | as_of_date: Optional end date in YYYY-MM-DD format. |
| 54 | |
| 55 | Returns: |
| 56 | Tuple of (from_date, to_date) as YYYY-MM-DD strings. |
| 57 | """ |
| 58 | if days < 0: |
| 59 | raise ValueError("Lookback days must be non-negative.") |
| 60 | normalized_as_of = parse_as_of_date(as_of_date) |
| 61 | |
| 62 | if normalized_as_of: |
| 63 | to_date = datetime.strptime(normalized_as_of, "%Y-%m-%d").date() |
| 64 | else: |
| 65 | to_date = datetime.now(timezone.utc).date() |
| 66 | |
| 67 | if days > (to_date - date.min).days: |
| 68 | raise ValueError("The lookback window starts before 0001-01-01. Use fewer days or a later --as-of date.") |
| 69 | from_date = to_date - timedelta(days=days) |
| 70 | return from_date.isoformat(), to_date.isoformat() |
| 71 | |
| 72 | |
| 73 | def _local_now() -> datetime: |
| 74 | """The reader's clock, with its UTC offset.""" |
| 75 | return datetime.now().astimezone() |
| 76 | |
| 77 | |
| 78 | def reader_end_date(to_date: str, now: Optional[datetime] = None) -> date: |
| 79 | """A window's end date as the reader's calendar has it. |
| 80 | |
| 81 | The window ends on the UTC date so queries and item filters lose no |
| 82 | post. West of UTC that date is tomorrow for part of every day (5pm in |
| 83 | Los Angeles on Nov 10 is already Nov 11 in UTC), and "to Nov 11" reads |
| 84 | as a window that runs into the future. A window that ends on today's UTC |
| 85 | date is shown ending on the reader's own date when that is earlier. A |
| 86 | window that ends on any other day (``--as-of``) is shown as it is. |
| 87 | ``now`` is an aware datetime; tests pass one. |
| 88 | """ |
| 89 | end = date.fromisoformat(to_date) |
| 90 | now = now or _local_now() |
| 91 | try: |
| 92 | utc_date = now.astimezone(timezone.utc).date() |
| 93 | except OverflowError: |
| 94 | return end |
| 95 | if end == utc_date and now.date() < end: |
| 96 | return now.date() |
| 97 | return end |
| 98 | |
| 99 | |
| 100 | def is_today(value: str, now: Optional[datetime] = None) -> bool: |
| 101 | """Whether a YYYY-MM-DD date is today in UTC or on the reader's calendar. |
| 102 | |
| 103 | West of UTC the two calendars differ for part of every day, and a date |
| 104 | that is today on either one is a live window. ``now`` is an aware |
| 105 | datetime. |
| 106 | """ |
| 107 | day = date.fromisoformat(value) |
| 108 | now = now or _local_now() |
| 109 | try: |
| 110 | utc_date = now.astimezone(timezone.utc).date() |
| 111 | except OverflowError: |
| 112 | return day == now.date() |
| 113 | return day in (utc_date, now.date()) |
| 114 | |
| 115 | |
| 116 | def format_window(from_date: str, to_date: str, now: Optional[datetime] = None) -> str: |
| 117 | """Render an ISO date window for readers, e.g. ``Oct 11 to Nov 10, 2026``. |
| 118 | |
| 119 | The year is printed once when both dates share it and on both dates when |
| 120 | the window crosses a year boundary. The end is the reader's date |
| 121 | (``reader_end_date``), never tomorrow. |
| 122 | """ |
| 123 | end = reader_end_date(to_date, now) |
| 124 | start = min(date.fromisoformat(from_date), end) |
| 125 | start_text = f"{start:%b} {start.day}" |
| 126 | if start.year != end.year: |
| 127 | start_text += f", {start.year}" |
| 128 | return f"{start_text} to {end:%b} {end.day}, {end.year}" |
| 129 | |
| 130 | |
| 131 | # Epoch-second guard for ambiguous string parsing: 9-10 integer digits |
| 132 | # (1973-03-03 to 2286-11-20), so compact YYYYMMDD dates (8 digits), bare |
| 133 | # 4-digit years, "0", and huge numeric IDs are never misread as 1970 epochs. |
| 134 | _UNIX_SECONDS_RE = re.compile(r"^\d{9,10}(?:\.\d+)?$") |
| 135 | _MIN_UNIX_SECONDS = 100_000_000.0 |
| 136 | _MAX_UNIX_SECONDS = 10_000_000_000.0 |
| 137 | |
| 138 | |
| 139 | def parse_date(date_str: Optional[str]) -> Optional[datetime]: |
| 140 | """Parse a date string in various formats. |
| 141 | |
| 142 | Supports: YYYY-MM-DD, YYYYMMDD, ISO 8601 (with Z, offsets, fractional |
| 143 | seconds, or space separator), and plausible Unix epoch-second timestamps. |
| 144 | """ |
| 145 | if date_str is None or isinstance(date_str, bool): |
| 146 | return None |
| 147 | |
| 148 | if isinstance(date_str, (int, float)): |
| 149 | try: |
| 150 | ts = float(date_str) |
| 151 | if not math.isfinite(ts) or not (_MIN_UNIX_SECONDS <= ts < _MAX_UNIX_SECONDS): |
| 152 | return None |
| 153 | return datetime.fromtimestamp(ts, tz=timezone.utc) |
| 154 | except (ValueError, TypeError, OverflowError, OSError): |
| 155 | return None |
| 156 | |
| 157 | if not isinstance(date_str, str): |
| 158 | return None |
| 159 | |
| 160 | cleaned = date_str.strip() |
| 161 | if not cleaned: |
| 162 | return None |
| 163 | |
| 164 | # Plausible Unix epoch seconds (e.g. Reddit created_utc as string) |
| 165 | if _UNIX_SECONDS_RE.match(cleaned): |
| 166 | try: |
| 167 | ts = float(cleaned) |
| 168 | if math.isfinite(ts) and _MIN_UNIX_SECONDS <= ts < _MAX_UNIX_SECONDS: |
| 169 | return datetime.fromtimestamp(ts, tz=timezone.utc) |
| 170 | except (ValueError, TypeError, OverflowError, OSError): |
| 171 | return None |
| 172 | |
| 173 | # ISO 8601 (Python 3.12 handles YYYY-MM-DD, YYYYMMDD, Z, ±HH:MM, ±HHMM, |
| 174 | # naive/aware fractional seconds, and space-separated date/time) |
| 175 | try: |
| 176 | dt = datetime.fromisoformat(cleaned) |
| 177 | if dt.tzinfo is not None: |
| 178 | return dt.astimezone(timezone.utc) |
| 179 | return dt.replace(tzinfo=timezone.utc) |
| 180 | except (ValueError, OverflowError): |
| 181 | return None |
| 182 | |
| 183 | |
| 184 | def timestamp_to_date(ts: Optional[float]) -> Optional[str]: |
| 185 | """Convert Unix timestamp to YYYY-MM-DD string.""" |
| 186 | if ts is None or isinstance(ts, bool): |
| 187 | return None |
| 188 | if not isinstance(ts, (int, float)): |
| 189 | return None |
| 190 | try: |
| 191 | ts_f = float(ts) |
| 192 | if not math.isfinite(ts_f): |
| 193 | return None |
| 194 | dt = datetime.fromtimestamp(ts_f, tz=timezone.utc) |
| 195 | return dt.date().isoformat() |
| 196 | except (ValueError, TypeError, OverflowError, OSError): |
| 197 | return None |
| 198 | |
| 199 | |
| 200 | def get_date_confidence(date_str: Optional[str], from_date: str, to_date: str) -> str: |
| 201 | """Determine confidence level for a date. |
| 202 | |
| 203 | Args: |
| 204 | date_str: The date to check (YYYY-MM-DD or None) |
| 205 | from_date: Start of valid range (YYYY-MM-DD) |
| 206 | to_date: End of valid range (YYYY-MM-DD) |
| 207 | |
| 208 | Returns: |
| 209 | 'high', 'med', or 'low' |
| 210 | """ |
| 211 | if not date_str: |
| 212 | return 'low' |
| 213 | |
| 214 | try: |
| 215 | dt = datetime.strptime(date_str, "%Y-%m-%d").date() |
| 216 | start = datetime.strptime(from_date, "%Y-%m-%d").date() |
| 217 | end = datetime.strptime(to_date, "%Y-%m-%d").date() |
| 218 | |
| 219 | return 'high' if start <= dt <= end else 'low' |
| 220 | except ValueError: |
| 221 | return 'low' |
| 222 | |
| 223 | |
| 224 | def days_ago(date_str: Optional[str], reference_date: Optional[str] = None) -> Optional[int]: |
| 225 | """Calculate how many days before the reference date a date is. |
| 226 | |
| 227 | If reference_date is None, use real today for backward compatibility. |
| 228 | Returns None if date is invalid or missing. |
| 229 | """ |
| 230 | if not date_str: |
| 231 | return None |
| 232 | |
| 233 | try: |
| 234 | dt = datetime.strptime(date_str, "%Y-%m-%d").date() |
| 235 | if reference_date: |
| 236 | today = datetime.strptime(reference_date, "%Y-%m-%d").date() |
| 237 | else: |
| 238 | today = datetime.now(timezone.utc).date() |
| 239 | delta = today - dt |
| 240 | return delta.days |
| 241 | except ValueError: |
| 242 | return None |
| 243 | |
| 244 | |
| 245 | def recency_score( |
| 246 | date_str: Optional[str], |
| 247 | max_days: int = 30, |
| 248 | reference_date: Optional[str] = None, |
| 249 | ) -> int: |
| 250 | """Calculate recency score (0-100). |
| 251 | |
| 252 | 0 days before reference_date = 100, max_days before reference_date = 0. |
| 253 | If reference_date is None, use real today for backward compatibility. |
| 254 | """ |
| 255 | age = days_ago(date_str, reference_date=reference_date) |
| 256 | if age is None: |
| 257 | return 0 |
| 258 | |
| 259 | if age < 0: |
| 260 | return 100 |
| 261 | if age >= max_days: |
| 262 | return 0 |
| 263 | |
| 264 | return int(100 * (1 - age / max_days)) |
| 265 |