"""
Date and time utilities for pygndc.
"""

import re
from datetime import datetime


def extract_date_from_filename(filename):
    """
    Extract datetime from filename.
    
    Supports multiple formats:
    1. _D20240112T103000_ (with time, second precision)
    2. _D20240112_ (date only, defaults to 10:30:00)
    3. YYYY-MM-DD format (e.g., MCD43A4_2019_2019-08-13.tif)
    4. YYYYMMDD compact format
    
    Args:
        filename: Name of the file
        
    Returns:
        datetime object or None if not found
    """
    # 1. Match format with time: _D20240112T103000_
    match_full = re.search(r"_D(\d{8})T(\d{6})_", filename)
    if match_full:
        date_str = match_full.group(1)
        time_str = match_full.group(2)
        return datetime.strptime(f"{date_str}{time_str}", "%Y%m%d%H%M%S")
    
    # 2. Match date only format: _D20240112_
    match_date = re.search(r"_D(\d{8})_", filename)
    if match_date:
        date_str = match_date.group(1)
        return datetime.strptime(date_str, "%Y%m%d").replace(hour=10, minute=30, second=0)
    
    # 3. Match YYYY-MM-DD format
    match_iso = re.search(r"(\d{4})-(\d{2})-(\d{2})", filename)
    if match_iso:
        date_str = match_iso.group(0)
        return datetime.strptime(date_str, "%Y-%m-%d").replace(hour=10, minute=30, second=0)
    
    # 4. Match compact YYYYMMDD format
    match_compact = re.search(r"(\d{4})(\d{2})(\d{2})", filename)
    if match_compact:
        date_str = match_compact.group(0)
        return datetime.strptime(date_str, "%Y%m%d").replace(hour=10, minute=30, second=0)
    
    return None


def normalize_time(dt, global_start_date=None, global_end_date=None):
    """
    Normalize datetime to [0, 1] range.
    
    Args:
        dt: datetime object to normalize
        global_start_date: Start date of the global range
        global_end_date: End date of the global range
        
    Returns:
        Normalized time value in [0, 1]
    """
    if global_start_date is None:
        global_start_date = datetime(2024, 1, 1, 10, 30, 0)
    if global_end_date is None:
        global_end_date = datetime(2025, 1, 1, 10, 30, 0)
    
    if dt < global_start_date or dt > global_end_date:
        print(f"Warning: Date {dt} is out of global bounds. Clamping.")
    
    delta = (dt - global_start_date).total_seconds()
    total_seconds = (global_end_date - global_start_date).total_seconds()
    t_norm = delta / total_seconds
    
    return max(0.0, min(1.0, t_norm))


def denormalize_time_to_year_fraction(t_val, global_start_date, global_end_date):
    """
    Convert normalized time to approximate year fraction for visualization.
    
    Args:
        t_val: Normalized time value [0, 1]
        global_start_date: Start date
        global_end_date: End date
        
    Returns:
        Approximate year fraction (e.g., 2024.5)
    """
    total_seconds = (global_end_date - global_start_date).total_seconds()
    seconds = t_val * total_seconds
    return 2000 + seconds / (365.25 * 24 * 3600)
