import uuid

import redis as redis_lib
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session

from app.api.v1.deps import require_role
from app.db.redis import get_redis
from app.db.session import get_db
from app.models.branch import Branch
from app.models.delivery import (
    CourierEarning,
    DeliveryAssignment,
    DeliveryAssignmentStatus,
)
from app.models.order import Order, OrderStatus, PaymentStatus
from app.models.user import User, UserRole
from app.schemas.delivery import (
    CourierEarningOut,
    CourierEarningsSummaryOut,
    CourierProfileOut,
    DeliveryAssignmentOut,
    DeliveryHistoryOut,
    DeliveryOfferOut,
    LocationUpdateRequest,
)
from app.services import dispatch as dispatch_service
from app.services import earnings as earnings_service
from app.services import order_notifications
from app.services import tracking as tracking_service
from app.utils.time import utcnow

router = APIRouter(prefix="/courier", tags=["courier"])

_ASSIGNMENT_NOT_FOUND = HTTPException(
    status_code=status.HTTP_404_NOT_FOUND, detail="Delivery assignment not found."
)

# A courier is actively working an order between accept and delivered
# — while in this range, their location posts get broadcast to
# whoever's watching that order.
_TRACKED_STATUSES = {
    DeliveryAssignmentStatus.ACCEPTED.value,
    DeliveryAssignmentStatus.PICKED_UP.value,
}


def _get_own_assignment(
    db: Session, assignment_id: uuid.UUID, courier_id: uuid.UUID
) -> DeliveryAssignment:
    assignment = (
        db.query(DeliveryAssignment)
        .filter(
            DeliveryAssignment.id == assignment_id,
            DeliveryAssignment.courier_id == courier_id,
        )
        .first()
    )
    if assignment is None:
        raise _ASSIGNMENT_NOT_FOUND
    return assignment


@router.get("/profile", response_model=CourierProfileOut)
def get_profile(
    db: Session = Depends(get_db),
    current_user: User = Depends(require_role(UserRole.COURIER)),
) -> CourierProfileOut:
    """Read-only for the courier themselves — shift hours and the
    online/offline switch are both set by an admin (see
    app.api.v1.endpoints.admin.update_courier_profile), since couriers
    here are full-time staff on a fixed schedule, not gig workers
    picking their own hours. This just lets a courier's app show what
    an admin has configured for them."""
    profile = dispatch_service.get_or_create_profile(db, current_user.id)
    return CourierProfileOut.model_validate(profile)


@router.post("/location")
def post_location(
    payload: LocationUpdateRequest,
    db: Session = Depends(get_db),
    current_user: User = Depends(require_role(UserRole.COURIER)),
    redis: redis_lib.Redis = Depends(get_redis),
) -> dict:
    profile = dispatch_service.get_or_create_profile(db, current_user.id)
    profile.last_latitude = payload.latitude
    profile.last_longitude = payload.longitude
    profile.last_location_at = utcnow()
    db.commit()

    active = (
        db.query(DeliveryAssignment)
        .filter(
            DeliveryAssignment.courier_id == current_user.id,
            DeliveryAssignment.status.in_(_TRACKED_STATUSES),
        )
        .first()
    )
    if active is not None:
        tracking_service.publish_location(
            redis, active.order_id, payload.latitude, payload.longitude
        )
    return {"status": "ok"}


@router.get("/offers/current", response_model=DeliveryOfferOut)
def get_current_offer(
    db: Session = Depends(get_db),
    current_user: User = Depends(require_role(UserRole.COURIER)),
) -> DeliveryOfferOut:
    assignment = (
        db.query(DeliveryAssignment)
        .filter(
            DeliveryAssignment.courier_id == current_user.id,
            DeliveryAssignment.status == DeliveryAssignmentStatus.OFFERED.value,
        )
        .order_by(DeliveryAssignment.offered_at.desc())
        .first()
    )
    if assignment is None:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND, detail="No pending offer."
        )
    order = db.query(Order).filter(Order.id == assignment.order_id).first()
    branch = db.query(Branch).filter(Branch.id == order.branch_id).first()
    return DeliveryOfferOut(
        **DeliveryAssignmentOut.model_validate(assignment).model_dump(),
        branch_name=branch.name,
        branch_address=branch.address,
        delivery_address=order.delivery_address,
        total=order.total,
    )


@router.post("/offers/{assignment_id}/accept", response_model=DeliveryAssignmentOut)
def accept_offer(
    assignment_id: uuid.UUID,
    db: Session = Depends(get_db),
    current_user: User = Depends(require_role(UserRole.COURIER)),
    redis: redis_lib.Redis = Depends(get_redis),
) -> DeliveryAssignmentOut:
    assignment = _get_own_assignment(db, assignment_id, current_user.id)
    if assignment.status != DeliveryAssignmentStatus.OFFERED.value:
        raise HTTPException(
            status_code=status.HTTP_409_CONFLICT,
            detail="This offer is no longer pending.",
        )

    assignment.status = DeliveryAssignmentStatus.ACCEPTED.value
    assignment.responded_at = utcnow()
    db.commit()
    db.refresh(assignment)
    tracking_service.publish_status(redis, assignment.order_id, assignment.status)
    order_notifications.notify_delivery_accepted(db, assignment)
    return DeliveryAssignmentOut.model_validate(assignment)


@router.post("/offers/{assignment_id}/reject", response_model=DeliveryAssignmentOut)
def reject_offer(
    assignment_id: uuid.UUID,
    db: Session = Depends(get_db),
    current_user: User = Depends(require_role(UserRole.COURIER)),
    redis: redis_lib.Redis = Depends(get_redis),
) -> DeliveryAssignmentOut:
    assignment = _get_own_assignment(db, assignment_id, current_user.id)
    if assignment.status != DeliveryAssignmentStatus.OFFERED.value:
        raise HTTPException(
            status_code=status.HTTP_409_CONFLICT,
            detail="This offer is no longer pending.",
        )

    assignment.status = DeliveryAssignmentStatus.REJECTED.value
    assignment.responded_at = utcnow()
    db.commit()
    db.refresh(assignment)

    order = db.query(Order).filter(Order.id == assignment.order_id).first()
    if order is not None:
        dispatch_service.dispatch_next_courier(db, redis, order)
    return DeliveryAssignmentOut.model_validate(assignment)


@router.post(
    "/deliveries/{assignment_id}/picked-up", response_model=DeliveryAssignmentOut
)
def mark_picked_up(
    assignment_id: uuid.UUID,
    db: Session = Depends(get_db),
    current_user: User = Depends(require_role(UserRole.COURIER)),
    redis: redis_lib.Redis = Depends(get_redis),
) -> DeliveryAssignmentOut:
    assignment = _get_own_assignment(db, assignment_id, current_user.id)
    if assignment.status != DeliveryAssignmentStatus.ACCEPTED.value:
        raise HTTPException(
            status_code=status.HTTP_409_CONFLICT,
            detail="This delivery hasn't been accepted yet.",
        )

    assignment.status = DeliveryAssignmentStatus.PICKED_UP.value
    assignment.picked_up_at = utcnow()
    db.commit()
    db.refresh(assignment)
    tracking_service.publish_status(redis, assignment.order_id, assignment.status)
    order_notifications.notify_delivery_picked_up(db, assignment)
    return DeliveryAssignmentOut.model_validate(assignment)


@router.post(
    "/deliveries/{assignment_id}/delivered", response_model=DeliveryAssignmentOut
)
def mark_delivered(
    assignment_id: uuid.UUID,
    db: Session = Depends(get_db),
    current_user: User = Depends(require_role(UserRole.COURIER)),
    redis: redis_lib.Redis = Depends(get_redis),
) -> DeliveryAssignmentOut:
    """Completes the order for delivery-mode orders — see the
    delivery-mode carve-out in
    app.api.v1.endpoints.orders.update_order_status, which refuses to
    let branch staff mark a delivery order COMPLETED directly. For a
    cash order, this is also the moment payment_status actually
    becomes PAID — cash is collected on handoff, not upfront."""
    assignment = _get_own_assignment(db, assignment_id, current_user.id)
    if assignment.status != DeliveryAssignmentStatus.PICKED_UP.value:
        raise HTTPException(
            status_code=status.HTTP_409_CONFLICT,
            detail="This delivery hasn't been picked up yet.",
        )

    assignment.status = DeliveryAssignmentStatus.DELIVERED.value
    assignment.delivered_at = utcnow()

    order = db.query(Order).filter(Order.id == assignment.order_id).first()
    order.status = OrderStatus.COMPLETED.value
    if order.payment_method == "cash":
        order.payment_status = PaymentStatus.PAID.value

    earnings_service.record_earning(
        db, assignment.id, assignment.courier_id, order.id, order.delivery_fee
    )

    db.commit()
    db.refresh(assignment)
    tracking_service.publish_status(redis, assignment.order_id, assignment.status)
    order_notifications.notify_delivery_completed(db, assignment)
    return DeliveryAssignmentOut.model_validate(assignment)


@router.get("/deliveries", response_model=list[DeliveryHistoryOut])
def list_deliveries(
    db: Session = Depends(get_db),
    current_user: User = Depends(require_role(UserRole.COURIER)),
) -> list[DeliveryHistoryOut]:
    """Every delivery assignment this courier has ever had, regardless
    of outcome (offered-then-rejected, accepted-then-cancelled, or
    fully delivered) — most recent first. Distinct from
    get_earnings_summary/list_earnings below, which only ever cover
    completed, paid-out deliveries."""
    rows = (
        db.query(DeliveryAssignment, Order, Branch)
        .join(Order, Order.id == DeliveryAssignment.order_id)
        .join(Branch, Branch.id == Order.branch_id)
        .filter(DeliveryAssignment.courier_id == current_user.id)
        .order_by(DeliveryAssignment.offered_at.desc())
        .all()
    )
    return [
        DeliveryHistoryOut(
            **DeliveryAssignmentOut.model_validate(assignment).model_dump(),
            branch_name=branch.name,
            delivery_address=order.delivery_address,
            total=order.total,
            order_status=order.status,
        )
        for assignment, order, branch in rows
    ]


@router.get("/earnings/summary", response_model=CourierEarningsSummaryOut)
def get_earnings_summary(
    db: Session = Depends(get_db),
    current_user: User = Depends(require_role(UserRole.COURIER)),
) -> CourierEarningsSummaryOut:
    total, count = earnings_service.get_summary(db, current_user.id)
    return CourierEarningsSummaryOut(total_earnings=total, delivery_count=count)


@router.get("/earnings", response_model=list[CourierEarningOut])
def list_earnings(
    db: Session = Depends(get_db),
    current_user: User = Depends(require_role(UserRole.COURIER)),
) -> list[CourierEarningOut]:
    rows = (
        db.query(CourierEarning)
        .filter(CourierEarning.courier_id == current_user.id)
        .order_by(CourierEarning.created_at.desc())
        .all()
    )
    return [CourierEarningOut.model_validate(r) for r in rows]
