"""Shared date-range resolution for dashboard, contacts, and companies pages."""

from datetime import date, timedelta

PERIOD_PRESETS = [
    ("all",          "All time"),
    ("this_week",    "This week"),
    ("7d",           "Last 7 days"),
    ("30d",          "Last 30 days"),
    ("this_month",   "This month"),
    ("last_month",   "Last month"),
    ("this_quarter", "This quarter"),
]

DEFAULT_PERIOD = "all"


def resolve_date_range(period, date_from_str=None, date_to_str=None):
    """Resolve a period code (or custom dates) into concrete date boundaries.

    Returns (date_from, date_to, active_period_code).
    When active_period_code is "all", both dates are None (no filtering).
    """
    today = date.today()

    if not period or period == "all":
        return None, None, "all"

    if period == "custom":
        try:
            df = date.fromisoformat(date_from_str) if date_from_str else None
            dt = date.fromisoformat(date_to_str) if date_to_str else None
        except (ValueError, TypeError):
            return None, None, "all"
        if df and dt:
            return df, dt, "custom"
        return None, None, "all"

    if period == "this_week":
        # Monday of current week
        monday = today - timedelta(days=today.weekday())
        return monday, today, "this_week"

    if period == "7d":
        return today - timedelta(days=7), today, "7d"

    if period == "30d":
        return today - timedelta(days=30), today, "30d"

    if period == "this_month":
        return today.replace(day=1), today, "this_month"

    if period == "last_month":
        first_of_this = today.replace(day=1)
        last_of_prev = first_of_this - timedelta(days=1)
        first_of_prev = last_of_prev.replace(day=1)
        return first_of_prev, last_of_prev, "last_month"

    if period == "this_quarter":
        q_month = ((today.month - 1) // 3) * 3 + 1
        return today.replace(month=q_month, day=1), today, "this_quarter"

    # Unknown period — treat as all
    return None, None, "all"


def period_label(code):
    """Return the human-readable label for a period code."""
    for c, label in PERIOD_PRESETS:
        if c == code:
            return label
    if code == "custom":
        return "Custom range"
    return "All time"
