from datetime import date, timedelta
import calendar

def get_dashboard_date_range(args):
    """
    Parses request arguments to return a standardized (start_date, end_date) tuple 
    for filtering dashboard queries.

    Supported 'period' values:
        - '1_month': Last 30 days
        - '3_months': Last 90 days
        - '6_months': Last 180 days
        - 'ytd' (DEFAULT): Year-to-Date (Jan 1st of current year to today)
        - 'last_year': Jan 1st to Dec 31st of the previous year
        - 'all_time': (None, None) or early dates
        - 'custom': Uses 'from_date' and 'to_date' parameters.

    Args:
        args (werkzeug.datastructures.MultiDict): request.args from Flask.

    Returns:
        tuple: (start_date: date|None, end_date: date|None, active_period_str: str)
    """
    today = date.today()
    period = args.get('period', 'ytd')  # Default to YTD
    
    start_date = None
    end_date = today

    if period == '1_month':
        start_date = today - timedelta(days=30)
    elif period == '3_months':
        start_date = today - timedelta(days=90)
    elif period == '6_months':
        start_date = today - timedelta(days=180)
    elif period == 'last_year':
        start_date = date(today.year - 1, 1, 1)
        end_date = date(today.year - 1, 12, 31)
    elif period == 'all_time':
        start_date = date(2000, 1, 1) # Arbitrary early date to capture all
        end_date = today
    elif period == 'custom':
        from_str = args.get('from_date')
        to_str = args.get('to_date')
        
        try:
            if from_str:
                start_date = date.fromisoformat(from_str)
            if to_str:
                end_date = date.fromisoformat(to_str)
        except ValueError:
            # Fallback if invalid format
            start_date = date(today.year, 1, 1)
            period = 'ytd'
            
    else:  # 'ytd' fallback
        period = 'ytd'
        start_date = date(today.year, 1, 1)

    return start_date, end_date, period
