from datetime import time
from typing import Protocol

from app.utils.time import addis_local_time, addis_local_weekday, utcnow


class _HasHours(Protocol):
    """Structural type, not app.models.branch.Branch specifically — is_
    branch_open is also called against a cached app.schemas.branch.
    BranchOut (see app.api.v1.endpoints.merchants.list_branches),
    since is_open_now is time-dependent and must be computed fresh on
    every call, cache hit or not, never itself cached."""

    is_active: bool
    opens_at: time | None
    closes_at: time | None
    working_days: list[int]


def is_branch_open(branch: _HasHours) -> bool:
    """A branch accepts orders right now only when BOTH is_active is
    true AND (no hours are set, or the current Addis Ababa wall-clock
    time falls inside opens_at/closes_at on today's working_days) —
    see the Branch model docstring. opens_at/closes_at being null
    means no hour restriction at all, so a branch that's never had
    hours configured behaves exactly as it did before this feature
    existed.

    Mirrors app.services.dispatch._is_on_shift's overnight-window
    handling (e.g. 20:00-04:00) — an overnight window on a working day
    still ends at closes_at even though that's technically "the next
    day" locally.
    """
    if not branch.is_active:
        return False
    if branch.opens_at is None or branch.closes_at is None:
        return True

    now_utc = utcnow()
    now_local = addis_local_time(now_utc)
    now_weekday = addis_local_weekday(now_utc)

    if now_weekday not in branch.working_days:
        return False
    if branch.opens_at <= branch.closes_at:
        return branch.opens_at <= now_local <= branch.closes_at
    return now_local >= branch.opens_at or now_local <= branch.closes_at
