import re
from dataclasses import dataclass
from decimal import Decimal
from typing import Optional

from django.conf import settings
from django.utils import timezone

from .models import Coupon, Variant

PRODUCT_ID_RE = re.compile(r"^[A-Za-z0-9._-]{1,200}$")
COUPON_RE = re.compile(r"^[A-Za-z0-9_-]{2,64}$")


class CartError(ValueError):
    pass


@dataclass(frozen=True)
class CartLine:
    variant: Variant
    quantity: int

    @property
    def total(self):
        return self.variant.price * self.quantity


@dataclass(frozen=True)
class Cart:
    lines: list
    coupon: Optional[Coupon]
    subtotal: Decimal
    discount: Decimal
    shipping: Decimal
    tax: Decimal
    total: Decimal


def parse_products(raw):
    if not raw:
        raise CartError("No products were supplied by Meta.")
    quantities = {}
    for entry in raw.split(","):
        parts = entry.split(":")
        if len(parts) != 2:
            raise CartError("One or more product entries are malformed.")
        product_id, raw_quantity = (part.strip() for part in parts)
        if not PRODUCT_ID_RE.fullmatch(product_id):
            raise CartError("A product ID contains unsupported characters.")
        try:
            quantity = int(raw_quantity)
        except ValueError as exc:
            raise CartError("A product quantity is not a whole number.") from exc
        if quantity < 1 or quantity > settings.CHECKOUT_MAX_LINE_QUANTITY:
            raise CartError(f"Each quantity must be between 1 and {settings.CHECKOUT_MAX_LINE_QUANTITY}.")
        quantities[product_id] = quantities.get(product_id, 0) + quantity
        if quantities[product_id] > settings.CHECKOUT_MAX_LINE_QUANTITY:
            raise CartError(f"Each quantity must be between 1 and {settings.CHECKOUT_MAX_LINE_QUANTITY}.")
    if sum(quantities.values()) > settings.CHECKOUT_MAX_CART_QUANTITY:
        raise CartError("The cart exceeds the maximum item quantity.")
    return quantities


def build_cart(products_raw, coupon_raw=""):
    requested = parse_products(products_raw)
    variants = {
        item.meta_product_id: item
        for item in Variant.objects.select_related("product").filter(
            meta_product_id__in=requested, active=True, product__active=True
        )
    }
    if any(item not in variants for item in requested):
        raise CartError("One or more selected products are no longer available.")
    lines = []
    for product_id, quantity in requested.items():
        variant = variants[product_id]
        if variant.stock_quantity < quantity:
            raise CartError(f"Only {variant.stock_quantity} of {variant.name} are currently available.")
        lines.append(CartLine(variant, quantity))
    subtotal = sum((line.total for line in lines), Decimal("0.00"))
    coupon = None
    discount = Decimal("0.00")
    if coupon_raw:
        code = coupon_raw.strip().upper()
        if not COUPON_RE.fullmatch(code):
            raise CartError("The promo code format is invalid.")
        now = timezone.now()
        coupon = Coupon.objects.filter(code__iexact=code, active=True).first()
        invalid = (
            coupon is None
            or (coupon.starts_at and coupon.starts_at > now)
            or (coupon.ends_at and coupon.ends_at < now)
            or (coupon.max_uses is not None and coupon.use_count >= coupon.max_uses)
            or (coupon.minimum_subtotal > subtotal)
        )
        if invalid:
            raise CartError("That promo code is invalid, expired, or does not apply to this cart.")
        discount = coupon.calculate_discount(subtotal)
    item_count = sum(line.quantity for line in lines)
    shipping = Decimal(settings.SHIPPING_MULTI_ITEM_RATE if item_count >= 2 else settings.SHIPPING_FLAT_RATE)
    taxable = subtotal - discount
    tax = (taxable * Decimal(settings.TAX_RATE_PERCENT) / Decimal("100")).quantize(Decimal("0.01"))
    return Cart(lines, coupon, subtotal, discount, shipping, tax, taxable + shipping + tax)
