import uuid

import redis as redis_lib
from fastapi import (
    APIRouter,
    Depends,
    HTTPException,
    Query,
    WebSocket,
    WebSocketDisconnect,
    status,
)
from sqlalchemy.orm import Session

from app.api.v1.deps import get_current_user
from app.api.v1.endpoints.orders import _is_branch_staff
from app.db.redis import get_async_redis, get_redis
from app.db.session import get_db
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
from app.schemas.delivery import OrderTrackingOut
from app.services import tracking as tracking_service
from app.services.tracking import channel

router = APIRouter(prefix="/orders", tags=["tracking"])

# The WebSocket route lives on its own router, mounted separately in
# app.main (without the global per-IP rate-limit dependency applied to
# `router` above): that dependency is typed to take a `Request`, which
# doesn't exist on a websocket ASGI scope, so attaching it to a
# websocket route raises at connection time instead of at import time.
# The REST ws-ticket mint above is already rate-limited, which is the
# part actually worth capping.
ws_router = APIRouter(prefix="/orders", tags=["tracking"])

_ORDER_NOT_FOUND = HTTPException(
    status_code=status.HTTP_404_NOT_FOUND, detail="Order not found."
)


def _get_snapshot(db: Session, order: Order) -> OrderTrackingOut:
    """The most recent delivery assignment for this order, if any. A
    REJECTED most-recent row means dispatch found nobody else
    available right now (a fresh row is created immediately on
    reject — see app.api.v1.endpoints.courier.reject_offer), so it's
    treated the same as no assignment at all rather than showing the
    courier who turned it down."""
    assignment = (
        db.query(DeliveryAssignment)
        .filter(DeliveryAssignment.order_id == order.id)
        .order_by(DeliveryAssignment.offered_at.desc())
        .first()
    )
    if (
        assignment is None
        or assignment.status == DeliveryAssignmentStatus.REJECTED.value
    ):
        return OrderTrackingOut(order_id=order.id, order_status=order.status)

    courier = db.query(User).filter(User.id == assignment.courier_id).first()
    profile = (
        db.query(CourierProfile)
        .filter(CourierProfile.user_id == assignment.courier_id)
        .first()
    )
    return OrderTrackingOut(
        order_id=order.id,
        order_status=order.status,
        assignment_status=assignment.status,
        courier_name=courier.name if courier else None,
        courier_phone=courier.phone if courier else None,
        last_latitude=profile.last_latitude if profile else None,
        last_longitude=profile.last_longitude if profile else None,
        last_location_at=profile.last_location_at if profile else None,
    )


def _get_authorized_order(db: Session, order_id: uuid.UUID, user: User) -> Order | None:
    order = db.query(Order).filter(Order.id == order_id).first()
    if order is None:
        return None
    branch = db.query(Branch).filter(Branch.id == order.branch_id).first()
    is_customer = order.customer_id == user.id
    is_staff = branch is not None and _is_branch_staff(db, branch, user)
    if not (is_customer or is_staff):
        return None
    return order


@router.get("/{order_id}/tracking", response_model=OrderTrackingOut)
def get_tracking(
    order_id: uuid.UUID,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
) -> OrderTrackingOut:
    """REST snapshot — the initial load for a tracking screen before
    it opens the WebSocket below for live updates."""
    order = _get_authorized_order(db, order_id, current_user)
    if order is None:
        raise _ORDER_NOT_FOUND
    return _get_snapshot(db, order)


@router.post("/{order_id}/tracking/ws-ticket")
def create_tracking_ws_ticket(
    order_id: uuid.UUID,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
    redis: redis_lib.Redis = Depends(get_redis),
) -> dict:
    """Mints a short-lived, single-use ticket for the WebSocket
    handshake below — call this first, over a normal authenticated
    HTTPS request (so the real access token never leaves an
    Authorization header), then open the WebSocket with
    `?ticket=...`. Checks the caller can actually see this order right
    now, same as get_tracking — belt-and-suspenders with the identical
    check the WebSocket itself repeats on connect, so a ticket can't
    even be minted for an order the caller has no business watching."""
    order = _get_authorized_order(db, order_id, current_user)
    if order is None:
        raise _ORDER_NOT_FOUND
    ticket = tracking_service.mint_ws_ticket(redis, current_user.id)
    return {
        "ticket": ticket,
        "expires_in_seconds": tracking_service.WS_TICKET_TTL_SECONDS,
    }


@ws_router.websocket("/{order_id}/tracking/ws")
async def tracking_ws(
    websocket: WebSocket,
    order_id: uuid.UUID,
    ticket: str = Query(...),
    db: Session = Depends(get_db),
) -> None:
    """Live push of courier location/status while a delivery is in
    progress. Browsers can't set an Authorization header on a
    WebSocket handshake, so auth comes from a `ticket` query param
    instead — minted just beforehand by
    POST /{order_id}/tracking/ws-ticket, a short-lived (60s),
    single-use stand-in for the real access token. A query-string
    value is more likely to end up in a proxy/access log than a
    header, so this bounds what a leaked one is actually worth,
    unlike the real access token it replaces (valid up to
    access_token_expire_minutes and usable against any endpoint).

    Backed by Redis pub/sub (see app.services.tracking) rather than
    polling the DB, so it fans out cheaply across however many
    uvicorn workers are running and however many people are watching
    the same order (customer + branch staff can both be connected at
    once)."""
    redis = get_async_redis()
    user_id = await tracking_service.redeem_ws_ticket(redis, ticket)
    if user_id is None:
        await websocket.close(code=4401)
        return

    user = db.get(User, user_id)
    if user is None or not user.is_active:
        await websocket.close(code=4401)
        return

    order = _get_authorized_order(db, order_id, user)
    if order is None:
        await websocket.close(code=4404)
        return

    snapshot = _get_snapshot(db, order)
    await websocket.accept()
    await websocket.send_json(snapshot.model_dump(mode="json"))

    pubsub = redis.pubsub()
    await pubsub.subscribe(channel(order_id))
    try:
        async for message in pubsub.listen():
            if message["type"] != "message":
                continue
            await websocket.send_text(message["data"])
    except WebSocketDisconnect:
        pass
    finally:
        await pubsub.unsubscribe(channel(order_id))
        await pubsub.aclose()
