import datetime

TIME_SLOTS = ['09:00 - 12:00', '12:00 - 15:00', '15:00 - 18:00']


def next_delivery_dates(count=3, start_offset_days=1):
    """The next `count` upcoming scheduled-delivery dates (admin-configured
    weekdays — see site_settings.get_delivery_weekdays(), defaults to
    Mon/Wed/Sat), starting `start_offset_days` from today (1 = tomorrow,
    the same-day cutoff every existing caller still gets by default). A far
    B2B order passes a larger offset here so the calendar reflects a real
    multi-day delivery estimate instead of always starting tomorrow — see
    market/b2b_delivery_estimate.py."""
    from .site_settings import get_delivery_weekdays

    weekdays = get_delivery_weekdays()
    today = datetime.date.today()
    dates = []
    d = today + datetime.timedelta(days=start_offset_days - 1)
    while len(dates) < count:
        d += datetime.timedelta(days=1)
        if d.weekday() in weekdays:
            dates.append(d)
    return dates


def next_delivery_dates_for_company(company_id, count=3, start_offset_days=1):
    """Same as next_delivery_dates, but sourced from a specific fleet
    company's own delivery-day calendar when it has one set (see
    market/fleet.py::get_company_delivery_weekdays) — falls back to the
    sitewide default when the company hasn't configured its own, so this
    is a pure additive override, never a required setting."""
    from .fleet import get_company_delivery_weekdays

    weekdays = get_company_delivery_weekdays(company_id)
    today = datetime.date.today()
    dates = []
    d = today + datetime.timedelta(days=start_offset_days - 1)
    while len(dates) < count:
        d += datetime.timedelta(days=1)
        if d.weekday() in weekdays:
            dates.append(d)
    return dates


def remaining_slots_today():
    """Of TIME_SLOTS, only the ones whose window hasn't fully ended yet —
    used by Quick Delivery so a customer can pick a specific later time
    today instead of only "right now"."""
    now = datetime.datetime.utcnow() + datetime.timedelta(hours=3)  # East Africa Time
    current_minutes = now.hour * 60 + now.minute
    remaining = []
    for slot in TIME_SLOTS:
        end_str = slot.split(' - ')[1]
        end_hour, end_minute = (int(x) for x in end_str.split(':'))
        if end_hour * 60 + end_minute > current_minutes:
            remaining.append(slot)
    return remaining


def quick_delivery_available():
    """Quick (same-day) delivery — including "Now" — stops being offered
    once the day's last time window (TIME_SLOTS' final end time, currently
    18:00 East Africa Time) has passed; pickers realistically aren't
    working a same-day rush after that. Reuses remaining_slots_today()'s
    cutoff so there's only one place that defines "today is over"."""
    return bool(remaining_slots_today())
