import uuid
from decimal import Decimal
from typing import Literal

from pydantic import BaseModel, ConfigDict, field_validator, model_validator

from app.schemas.cart import CartOut
from app.utils.phone import InvalidPhoneNumber, normalize_ethiopian_phone

# Rough bounding box for Ethiopia — good enough to catch a recipient
# address that's obviously not in the country (e.g. entered while the
# app defaulted to some other location), not a precise border check.
# "Order for a Friend" exists specifically for a customer abroad
# sending a gift order to someone in Ethiopia, so the recipient's
# address is the one thing here that must actually be Ethiopian, even
# though the customer themselves may not be.
_ETHIOPIA_LAT_RANGE = (3.0, 15.0)
_ETHIOPIA_LNG_RANGE = (33.0, 48.0)


class CheckoutRequest(BaseModel):
    model_config = ConfigDict(
        json_schema_extra={
            "examples": [
                {
                    "delivery_mode": "delivery",
                    "delivery_address": "Bole, Addis Ababa",
                    "delivery_latitude": 9.010,
                    "delivery_longitude": 38.768,
                    "payment_method": "cash",
                },
                {
                    "delivery_mode": "delivery",
                    "delivery_address": "Kazanchis, Addis Ababa",
                    "delivery_latitude": 9.020,
                    "delivery_longitude": 38.760,
                    "payment_method": "chapa",
                    "recipient_name": "Marta",
                    "recipient_phone": "0911223344",
                },
            ]
        }
    )

    delivery_mode: Literal["takeaway", "delivery"]
    delivery_address: str | None = None
    # Required (checked in the endpoint, same as delivery_address) for
    # delivery_mode == "delivery" — used to compute a real distance-based
    # delivery fee, see app.services.pricing.compute_delivery_fee.
    delivery_latitude: float | None = None
    delivery_longitude: float | None = None
    payment_method: Literal["chapa", "cash"] = "chapa"
    # Validated against app.services.promo.validate_promo_code — a
    # bad/ineligible code is a checkout-time 422, not silently ignored.
    promo_code: str | None = None
    # "Order for a Friend" — set both to have this order delivered to
    # someone else, at delivery_address above (which becomes *their*
    # address, not the customer's own), with an SMS sent to
    # recipient_phone once the order is confirmed (see
    # app.services.order_notifications.notify_order_confirmed). Either
    # both are set or neither — see _recipient_fields_and_gift_rules
    # below.
    recipient_name: str | None = None
    recipient_phone: str | None = None

    @field_validator("delivery_address")
    @classmethod
    def _not_blank(cls, v: str | None) -> str | None:
        if v is not None:
            v = v.strip()
            if not v:
                raise ValueError("Delivery address can't be blank if provided.")
        return v

    @field_validator("promo_code")
    @classmethod
    def _clean_promo_code(cls, v: str | None) -> str | None:
        if v is not None:
            v = v.strip()
            if not v:
                return None
        return v

    @field_validator("delivery_latitude")
    @classmethod
    def _valid_lat(cls, v: float | None) -> float | None:
        if v is not None and not -90 <= v <= 90:
            raise ValueError("delivery_latitude must be between -90 and 90.")
        return v

    @field_validator("delivery_longitude")
    @classmethod
    def _valid_lng(cls, v: float | None) -> float | None:
        if v is not None and not -180 <= v <= 180:
            raise ValueError("delivery_longitude must be between -180 and 180.")
        return v

    @field_validator("recipient_name")
    @classmethod
    def _recipient_name_not_blank(cls, v: str | None) -> str | None:
        if v is not None:
            v = v.strip()
            if not v:
                raise ValueError("Recipient name can't be blank if provided.")
        return v

    @field_validator("recipient_phone")
    @classmethod
    def _valid_recipient_phone(cls, v: str | None) -> str | None:
        if v is None:
            return v
        try:
            return normalize_ethiopian_phone(v)
        except InvalidPhoneNumber as exc:
            raise ValueError(str(exc)) from exc

    @model_validator(mode="after")
    def _recipient_fields_and_gift_rules(self) -> "CheckoutRequest":
        has_recipient = (
            self.recipient_name is not None or self.recipient_phone is not None
        )
        if not has_recipient:
            return self
        if self.recipient_name is None or self.recipient_phone is None:
            raise ValueError(
                "recipient_name and recipient_phone must both be set for an "
                "order for a friend, or neither."
            )
        if self.delivery_mode != "delivery":
            raise ValueError(
                "An order for a friend requires delivery_mode='delivery' — "
                "there's no one there to hand a takeaway order to."
            )
        # delivery_mode == "delivery" already guarantees these two are
        # set (checked in the endpoint) by the time this matters, but
        # narrow the type before the range check regardless.
        if self.delivery_latitude is not None and self.delivery_longitude is not None:
            lat_ok = (
                _ETHIOPIA_LAT_RANGE[0]
                <= self.delivery_latitude
                <= _ETHIOPIA_LAT_RANGE[1]
            )
            lng_ok = (
                _ETHIOPIA_LNG_RANGE[0]
                <= self.delivery_longitude
                <= _ETHIOPIA_LNG_RANGE[1]
            )
            if not (lat_ok and lng_ok):
                raise ValueError(
                    "The recipient's address must be in Ethiopia for an "
                    "order for a friend."
                )
        return self


class OrderItemOptionOut(BaseModel):
    model_config = ConfigDict(from_attributes=True)

    id: uuid.UUID
    name_snapshot: str
    price_delta_snapshot: Decimal


class OrderItemOut(BaseModel):
    model_config = ConfigDict(from_attributes=True)

    id: uuid.UUID
    menu_item_id: uuid.UUID
    name_snapshot: str
    unit_price_snapshot: Decimal
    quantity: Decimal
    options: list[OrderItemOptionOut] = []
    special_instructions: str | None
    line_total: Decimal
    added_by_user_id: uuid.UUID


class OrderOut(BaseModel):
    model_config = ConfigDict(from_attributes=True)

    id: uuid.UUID
    customer_id: uuid.UUID
    branch_id: uuid.UUID
    status: str
    delivery_mode: str
    delivery_address: str | None
    delivery_latitude: float | None
    delivery_longitude: float | None
    recipient_name: str | None
    recipient_phone: str | None
    subtotal: Decimal
    delivery_fee: Decimal
    service_fee: Decimal
    vat: Decimal
    discount_amount: Decimal
    promo_code_id: uuid.UUID | None
    total: Decimal
    payment_status: str
    tx_ref: str
    chapa_checkout_url: str | None
    payment_method: str | None
    group_order_session_id: uuid.UUID | None


class OrderWithItemsOut(OrderOut):
    items: list[OrderItemOut] = []


class OrderStatusUpdateRequest(BaseModel):
    status: Literal["confirmed", "preparing", "ready", "completed", "cancelled"]


class ReorderSkippedItem(BaseModel):
    """One line from the original order that couldn't be added back —
    e.g. the item was removed from the menu, marked unavailable, or an
    option it used no longer exists. name is the original
    name_snapshot, not necessarily what the item is called now."""

    name: str
    reason: str


class ReorderResponse(BaseModel):
    """See app.api.v1.endpoints.orders.reorder_order. cart is the
    customer's cart *after* whatever could be added — always fetch
    this rather than assuming what was in it before the call, since
    reorder merges into any existing cart contents rather than
    replacing them."""

    cart: CartOut
    added_count: int
    skipped: list[ReorderSkippedItem] = []
