"""
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:
                from common.timezone_config import VIETNAM_TZ
                ts_start = float(match_ts.group(1))
                ts_end = float(match_ts.group(2))
                # Frontend sends UTC midnight timestamps, but user is in Vietnam (UTC+7).
                # Shift by -7h so "Feb 5" means Feb 5 00:00 VN (= Feb 4 17:00 UTC)
                # instead of Feb 5 00:00 UTC (= Feb 5 07:00 VN).
                utc_offset_seconds = VIETNAM_TZ.utcoffset(None).total_seconds()
                dt_start = datetime.fromtimestamp(ts_start - utc_offset_seconds, tz=timezone.utc)
                dt_end = datetime.fromtimestamp(ts_end - utc_offset_seconds, tz=timezone.utc)
            except (ValueError, TypeError):
                pass
        else:
            # Case 2: DisplayTime filter (displayTime:YYYY-MM-DD)
            # Dates are interpreted as Vietnam time (UTC+7), then converted to UTC for MongoDB
            pattern_dt = r"displayTime:(\d{4}-\d{2}-\d{2})"
            match_dt = re.search(pattern_dt, filter_str)
            
            if match_dt:
                try:
                    from common.timezone_config import VIETNAM_TZ
                    date_str = match_dt.group(1)
                    dt = datetime.strptime(date_str, "%Y-%m-%d").replace(tzinfo=VIETNAM_TZ)
                    dt_start = dt.astimezone(timezone.utc)
                    dt_end = (dt + timedelta(days=1)).astimezone(timezone.utc)
                except ValueError:
                    pass
    
    return dt_start, dt_end

