import uuid
from datetime import datetime, time
from decimal import Decimal
from enum import Enum

from sqlalchemy import (
    JSON,
    Boolean,
    DateTime,
    Float,
    ForeignKey,
    Numeric,
    String,
    Time,
    Uuid,
    func,
)
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.orm import Mapped, mapped_column

from app.db.session import Base

# Native JSONB on Postgres, plain JSON (TEXT-backed) on SQLite — same
# portability pattern as app.models.menu._JSON_TYPE.
_JSON_TYPE = JSON().with_variant(JSONB(), "postgresql")

# Monday=0 .. Sunday=6, matching Python's date.weekday() — what
# app.services.dispatch actually compares working_days against.
_ALL_WEEKDAYS = [0, 1, 2, 3, 4, 5, 6]


class DeliveryAssignmentStatus(str, Enum):
    OFFERED = "offered"
    ACCEPTED = "accepted"
    REJECTED = "rejected"
    PICKED_UP = "picked_up"
    DELIVERED = "delivered"
    CANCELLED = "cancelled"


class CourierProfile(Base):
    """Delivery-specific state for a courier account, kept off of User
    itself the same way BranchManager keeps branch assignment off of
    it — this is role-specific, not identity.

    Couriers work fixed shift hours (shift_start/shift_end,
    wall-clock time-of-day, Africa/Addis_Ababa) on a recurring set of
    working_days (0=Monday..6=Sunday), and app.services.dispatch only
    offers orders to a courier when the current day is in
    working_days and the current time falls in the shift window —
    see _is_on_shift there for how an overnight window (e.g.
    20:00-04:00) is handled. shift_start/shift_end/is_online/
    working_days are all set by an admin, not the courier themselves
    (see app.api.v1.endpoints.admin.update_courier_profile) —
    couriers here are full-time staff on a schedule the business
    sets, not gig workers picking their own hours. The courier can
    only read this back (app.api.v1.endpoints.courier.get_profile),
    not change it.

    shift_start/shift_end are nullable: a courier with no shift set
    yet is simply never dispatched to, same as a menu item with no
    option groups just has none. working_days defaults to every day
    (_ALL_WEEKDAYS) rather than none, so it stays a no-op restriction
    until an admin actually narrows it — e.g. down to weekdays only —
    and doesn't regress a courier who only ever had shift hours set.
    is_online defaults to False: a newly invited courier doesn't
    start receiving orders until an admin turns them on.

    last_latitude/last_longitude/last_location_at are the courier's
    most recent posted position (see
    app.api.v1.endpoints.courier.post_location) — plain floats, not a
    mapped PostGIS column, same reasoning as Branch.latitude/longitude.
    Dispatch also checks last_location_at isn't stale (see
    app.services.dispatch._LOCATION_FRESHNESS) so a courier whose app
    has been closed for hours doesn't get orders offered to them.
    """

    __tablename__ = "courier_profiles"

    id: Mapped[uuid.UUID] = mapped_column(Uuid, primary_key=True, default=uuid.uuid4)
    user_id: Mapped[uuid.UUID] = mapped_column(
        Uuid, ForeignKey("users.id", ondelete="CASCADE"), unique=True, nullable=False
    )
    shift_start: Mapped[time | None] = mapped_column(Time, nullable=True)
    shift_end: Mapped[time | None] = mapped_column(Time, nullable=True)
    working_days: Mapped[list[int]] = mapped_column(
        _JSON_TYPE, nullable=False, default=lambda: list(_ALL_WEEKDAYS)
    )
    is_online: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)

    last_latitude: Mapped[float | None] = mapped_column(Float, nullable=True)
    last_longitude: Mapped[float | None] = mapped_column(Float, nullable=True)
    last_location_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)

    created_at: Mapped[datetime] = mapped_column(
        DateTime, server_default=func.now(), nullable=False
    )
    updated_at: Mapped[datetime] = mapped_column(
        DateTime, server_default=func.now(), onupdate=func.now(), nullable=False
    )


class CourierEarning(Base):
    """One row per completed delivery, created the moment
    app.api.v1.endpoints.courier.mark_delivered transitions a
    DeliveryAssignment to DELIVERED (see
    app.services.earnings.record_earning). amount is a snapshot of
    Order.delivery_fee at that moment, not a live reference — same
    snapshot reasoning as OrderItem.unit_price_snapshot — so a later
    change to how delivery_fee is computed never rewrites a courier's
    already-earned history.

    Couriers keep 100% of delivery_fee; Yeneb's own cut comes from
    service_fee alone, the same subtotal/service_fee/delivery_fee
    revenue-split reasoning already used for the discount funding
    source in app.api.v1.endpoints.orders.checkout."""

    __tablename__ = "courier_earnings"

    id: Mapped[uuid.UUID] = mapped_column(Uuid, primary_key=True, default=uuid.uuid4)
    delivery_assignment_id: Mapped[uuid.UUID] = mapped_column(
        Uuid,
        ForeignKey("delivery_assignments.id", ondelete="CASCADE"),
        unique=True,
        nullable=False,
    )
    courier_id: Mapped[uuid.UUID] = mapped_column(
        Uuid, ForeignKey("users.id"), nullable=False, index=True
    )
    order_id: Mapped[uuid.UUID] = mapped_column(
        Uuid, ForeignKey("orders.id"), nullable=False, index=True
    )
    amount: Mapped[Decimal] = mapped_column(Numeric(10, 2), nullable=False)

    created_at: Mapped[datetime] = mapped_column(
        DateTime, server_default=func.now(), nullable=False
    )


class DeliveryAssignment(Base):
    """One dispatch attempt: order X offered to courier Y. A rejected
    order gets a fresh row per re-dispatch (see
    app.services.dispatch.dispatch_next_courier) rather than reusing
    the row, so the full offer history for an order is visible — who
    was asked, in what order, and who said no. Only one row per order
    should be in a non-terminal state (offered/accepted/picked_up) at
    a time; that's enforced in the dispatch/accept/reject endpoint
    code, not the DB, same as every other business rule in this
    codebase.

    picked_up_at/delivered_at drive the courier's own side of the
    order lifecycle. delivered_at is also what completes the order
    itself for delivery-mode orders — see
    app.api.v1.endpoints.courier.mark_delivered and the
    delivery-mode carve-out in
    app.api.v1.endpoints.orders.update_order_status.
    """

    __tablename__ = "delivery_assignments"

    id: Mapped[uuid.UUID] = mapped_column(Uuid, primary_key=True, default=uuid.uuid4)
    order_id: Mapped[uuid.UUID] = mapped_column(
        Uuid, ForeignKey("orders.id", ondelete="CASCADE"), nullable=False, index=True
    )
    courier_id: Mapped[uuid.UUID] = mapped_column(
        Uuid, ForeignKey("users.id"), nullable=False, index=True
    )
    status: Mapped[str] = mapped_column(
        String(20), nullable=False, default=DeliveryAssignmentStatus.OFFERED.value
    )

    offered_at: Mapped[datetime] = mapped_column(
        DateTime, server_default=func.now(), nullable=False
    )
    responded_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
    picked_up_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
    delivered_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)

    created_at: Mapped[datetime] = mapped_column(
        DateTime, server_default=func.now(), nullable=False
    )
