"""
Query parameter parsing utilities for memo routes.
Extracted from route handlers to keep routes thin.
"""

import re
from datetime import datetime, timedelta, timezone
from typing import Tuple


def parse_date_range(
    start_date: str | None = None,
    end_date: str | None = None,
    filter_str: str | None = None,
) -> Tuple[datetime | None, datetime | None]:
    """
    Parse date range from query parameters or filter string.
    
    Supports:
    - ISO format dates (start_date/end_date params)
    - Timestamp filter: "created_ts >= 1234567890 && created_ts < 1234567890"
    - DisplayTime filter: "displayTime:2026-01-24"
    
    Returns:
        Tuple of (start_datetime, end_datetime) or (None, None)
    """
    dt_start = None
    dt_end = None
    
    # Parse ISO format dates
    if start_date:
        try:
            dt_start = datetime.fromisoformat(start_date.replace("Z", "+00:00"))
        except ValueError:
            pass
    
    if end_date:
        try:
            dt_end = datetime.fromisoformat(end_date.replace("Z", "+00:00"))
        except ValueError:
            pass
    
    # Parse filter string (overrides start/end if present)
    if filter_str:
        # Case 1: Timestamp filter (created_ts >= ... && created_ts < ...)
        pattern_ts = r"(?:created_ts|updated_ts)\s*>=\s*([\d\.]+)\s*&&\s*(?:created_ts|updated_ts)\s*<\s*([\d\.]+)"
        match_ts = re.search(pattern_ts, filter_str)
        
        if match_ts:
            try:
                ts_start = float(match_ts.group(1))
                ts_end = float(match_ts.group(2))
                dt_start = datetime.fromtimestamp(ts_start, tz=timezone.utc)
                dt_end = datetime.fromtimestamp(ts_end, tz=timezone.utc)
            except (ValueError, TypeError):
                pass
        else:
            # Case 2: DisplayTime filter (displayTime:YYYY-MM-DD)
            pattern_dt = r"displayTime:(\d{4}-\d{2}-\d{2})"
            match_dt = re.search(pattern_dt, filter_str)
            
            if match_dt:
                try:
                    date_str = match_dt.group(1)
                    dt = datetime.strptime(date_str, "%Y-%m-%d").replace(tzinfo=timezone.utc)
                    dt_start = dt
                    dt_end = dt + timedelta(days=1)
                except ValueError:
                    pass
    
    return dt_start, dt_end

