import time as time_module
import uuid
from datetime import time, timedelta

import redis as redis_lib
from geoalchemy2 import Geography
from sqlalchemy import cast, func
from sqlalchemy.orm import Session

from app.models.branch import Branch
from app.models.delivery import (
    CourierProfile,
    DeliveryAssignment,
    DeliveryAssignmentStatus,
)
from app.models.order import Order
from app.models.user import User, UserRole
from app.services import order_notifications
from app.utils.time import addis_local_time, addis_local_weekday, utcnow

# A courier whose app hasn't posted a location in this long is treated
# as unreachable, even if they're inside their shift window — no point
# offering an order to someone who may have force-closed the app.
_LOCATION_FRESHNESS = timedelta(minutes=10)

# Serializes dispatch_next_courier calls across every worker process.
# Without this, two concurrent checkouts (or a checkout racing a
# reject-triggered re-dispatch) can both read "courier X is free"
# before either commits its new DeliveryAssignment row, and both
# assign X to two different orders at once — busy_courier_ids below is
# a plain read, not a row lock, so nothing in the query itself
# prevents that. A single global lock, not a per-courier one: dispatch
# calls are a handful of fast queries each, so serializing all of them
# is simpler than fine-grained per-courier locking and the throughput
# cost is negligible at this scale.
_DISPATCH_LOCK_KEY = "lock:dispatch_courier"
_LOCK_TTL_SECONDS = 5
_LOCK_MAX_WAIT_SECONDS = 2.0
_LOCK_RETRY_INTERVAL_SECONDS = 0.05


def _acquire_dispatch_lock(redis: redis_lib.Redis) -> bool:
    deadline = time_module.monotonic() + _LOCK_MAX_WAIT_SECONDS
    while time_module.monotonic() < deadline:
        if redis.set(_DISPATCH_LOCK_KEY, "1", nx=True, ex=_LOCK_TTL_SECONDS):
            return True
        time_module.sleep(_LOCK_RETRY_INTERVAL_SECONDS)
    return False


def _release_dispatch_lock(redis: redis_lib.Redis) -> None:
    redis.delete(_DISPATCH_LOCK_KEY)


def get_or_create_profile(db: Session, courier_id: uuid.UUID) -> CourierProfile:
    """Shared by app.api.v1.endpoints.courier (self-service shift/
    location) and app.api.v1.endpoints.admin (online/offline toggle)
    — either side may be the first to touch a given courier's
    profile, so both need to be able to lazily create it."""
    profile = (
        db.query(CourierProfile).filter(CourierProfile.user_id == courier_id).first()
    )
    if profile is None:
        profile = CourierProfile(user_id=courier_id)
        db.add(profile)
        db.commit()
        db.refresh(profile)
    return profile


_ACTIVE_STATUSES = {
    DeliveryAssignmentStatus.OFFERED.value,
    DeliveryAssignmentStatus.ACCEPTED.value,
    DeliveryAssignmentStatus.PICKED_UP.value,
}


def _is_on_shift(profile: CourierProfile, now_local: time, now_weekday: int) -> bool:
    """shift_start/shift_end are wall-clock Africa/Addis_Ababa
    time-of-day; working_days is 0=Monday..6=Sunday. Handles an
    overnight window (e.g. 20:00-04:00) by checking whether it wraps
    past midnight — note that doesn't cross working_days, so an
    overnight shift on a working day still ends at shift_end even if
    that's technically "the next day" locally."""
    if now_weekday not in profile.working_days:
        return False
    if profile.shift_start is None or profile.shift_end is None:
        return False
    if profile.shift_start <= profile.shift_end:
        return profile.shift_start <= now_local <= profile.shift_end
    return now_local >= profile.shift_start or now_local <= profile.shift_end


def _distance_expr(branch: Branch):
    branch_point = func.ST_SetSRID(
        func.ST_MakePoint(branch.longitude, branch.latitude), 4326
    )
    courier_point = func.ST_SetSRID(
        func.ST_MakePoint(CourierProfile.last_longitude, CourierProfile.last_latitude),
        4326,
    )
    return func.ST_Distance(
        cast(courier_point, Geography), cast(branch_point, Geography)
    ).label("distance_meters")


def dispatch_next_courier(
    db: Session, redis: redis_lib.Redis, order: Order
) -> DeliveryAssignment | None:
    """Finds the nearest available courier and creates an `offered`
    DeliveryAssignment for them. "Available" means: toggled online by
    an admin, scheduled to work today and on shift right now, posted
    a location recently, and not already juggling another active
    (offered/accepted/picked_up) delivery. Returns None if
    nobody currently qualifies — the order simply stays unassigned
    until this is called again (a courier coming on shift doesn't
    trigger anything by itself in this pass; see the courier reject
    endpoint for the one place re-dispatch is actually wired up).
    Couriers who already rejected this specific order are excluded by
    the query itself (rejected_courier_ids below), so calling this
    again after a reject naturally skips them without needing to pass
    anything in.

    Wrapped in a global Redis lock (see _acquire_dispatch_lock above)
    for the whole candidate-selection-through-assignment-creation
    critical section — also returns None if the lock can't be
    acquired in time, which is fine: that's operationally identical to
    "nobody qualifies right now," and this function is always safe to
    call again later.

    Only called for delivery_mode == "delivery" orders — see call
    sites in app.api.v1.endpoints.orders.checkout and
    app.api.v1.endpoints.payments.chapa_webhook.
    """
    branch = db.query(Branch).filter(Branch.id == order.branch_id).first()
    if branch is None:
        return None

    if not _acquire_dispatch_lock(redis):
        return None
    try:
        return _select_and_assign_courier(db, order, branch)
    finally:
        _release_dispatch_lock(redis)


def _select_and_assign_courier(
    db: Session, order: Order, branch: Branch
) -> DeliveryAssignment | None:
    now_utc = utcnow()
    now_local = addis_local_time(now_utc)
    now_weekday = addis_local_weekday(now_utc)
    freshness_cutoff = now_utc - _LOCATION_FRESHNESS

    busy_courier_ids = db.query(DeliveryAssignment.courier_id).filter(
        DeliveryAssignment.status.in_(_ACTIVE_STATUSES)
    )
    rejected_courier_ids = db.query(DeliveryAssignment.courier_id).filter(
        DeliveryAssignment.order_id == order.id,
        DeliveryAssignment.status == DeliveryAssignmentStatus.REJECTED.value,
    )

    # Plain SQL, no PostGIS — every filter here works on SQLite too, so
    # the common one-or-zero-candidate case (most of what the pytest
    # suite exercises) never touches a function SQLite doesn't know.
    candidates = (
        db.query(CourierProfile)
        .join(User, User.id == CourierProfile.user_id)
        .filter(
            User.role == UserRole.COURIER.value,
            User.is_active.is_(True),
            CourierProfile.is_online.is_(True),
            CourierProfile.last_latitude.is_not(None),
            CourierProfile.last_longitude.is_not(None),
            CourierProfile.last_location_at >= freshness_cutoff,
            CourierProfile.user_id.not_in(busy_courier_ids),
            CourierProfile.user_id.not_in(rejected_courier_ids),
        )
        .all()
    )
    on_shift = [p for p in candidates if _is_on_shift(p, now_local, now_weekday)]
    if not on_shift:
        return None

    if len(on_shift) == 1:
        nearest = on_shift[0]
    else:
        # Only reached with real ambiguity to break — see
        # app.api.v1.endpoints.merchants._distance_expr for the same
        # PostGIS-cast-at-query-time pattern. Requires the postgis
        # extension, so this branch is exercised by the live smoke
        # test rather than the (SQLite-backed) pytest suite.
        distance = _distance_expr(branch)
        nearest, _distance_meters = (
            db.query(CourierProfile, distance)
            .filter(CourierProfile.user_id.in_([p.user_id for p in on_shift]))
            .order_by(distance)
            .first()
        )

    assignment = DeliveryAssignment(order_id=order.id, courier_id=nearest.user_id)
    db.add(assignment)
    db.commit()
    db.refresh(assignment)
    order_notifications.notify_delivery_offered(db, assignment)
    return assignment
