from django.db import models
from shop_management.models.data.shop import Shop
from shop_management.models.base import DataRoot

AFN_CURRENCY_KEYS = {"afn", "afghani", "afgani", "afg", "af"}
USD_CURRENCY_KEYS = {"usd", "usdollar", "usddollar", "unitedstatesdollar", "dollar"}


def classify_currency_code(currency_or_title):
    """
    Classify a Currency instance or currency title string into 'AFN', 'USD', or None.
    """
    if currency_or_title is None:
        return None
    if isinstance(currency_or_title, str):
        raw = currency_or_title.strip()
    elif hasattr(currency_or_title, "title"):
        raw = str(currency_or_title.title or "").strip()
    else:
        raw = str(currency_or_title or "").strip()
    if not raw:
        return None
    normalized = "".join(ch for ch in raw.lower() if ch.isalnum())
    if normalized in AFN_CURRENCY_KEYS or "افغ" in raw or "؋" in raw:
        return "AFN"
    if normalized in USD_CURRENCY_KEYS or "دالر" in raw or "$" in raw:
        return "USD"
    return None


def resolve_shop_currency(shop_or_id, code):
    """
    Return the shop's Currency instance matching 'AFN' or 'USD', or None if not found.
    """
    target_code = str(code or "").strip().upper()
    if target_code not in ("AFN", "USD") or not shop_or_id:
        return None
    shop_id = getattr(shop_or_id, "pk", shop_or_id)
    for curr in Currency.objects.filter(shop_id=shop_id).order_by("id"):
        if classify_currency_code(curr.title) == target_code:
            return curr
    return None


def resolve_shop_currency_title(shop_or_id, code):
    """
    Return the shop's configured Currency title for 'AFN' or 'USD' (e.g. 'AFN' or 'Afghani'),
    falling back to the canonical code ('AFN' / 'USD').
    """
    curr = resolve_shop_currency(shop_or_id, code)
    if curr and curr.title:
        return curr.title
    return str(code or "").strip().upper()


class Unit(DataRoot):
    title = models.CharField(max_length=200)
    description = models.CharField(max_length=200, null=True, blank=True)
    shop = models.ForeignKey(Shop, on_delete=models.CASCADE, related_name='unit')

    def __str__(self):
        return self.title


class Currency(DataRoot):
    title = models.CharField(max_length=200)
    description = models.CharField(max_length=200, null=True, blank=True)
    shop = models.ForeignKey(Shop, on_delete=models.CASCADE, related_name='currency')

    def __str__(self):
        return self.title


class ExchangeRate(models.Model):
    from_currency = models.ForeignKey(
        Currency,
        on_delete=models.CASCADE,
        related_name="exchange_rates_from",
    )
    to_currency = models.ForeignKey(
        Currency,
        on_delete=models.CASCADE,
        related_name="exchange_rates_to",
    )
    rate = models.DecimalField(max_digits=20, decimal_places=6)
    rate_date = models.DateField()
    shop = models.ForeignKey(
        Shop, on_delete=models.CASCADE, related_name="exchange_rates"
    )

    class Meta:
        constraints = [
            models.UniqueConstraint(
                fields=["shop", "from_currency", "to_currency", "rate_date"],
                name="unique_exchange_rate_per_day",
            )
        ]

    def __str__(self):
        return (
            f"{self.from_currency} -> {self.to_currency} = "
            f"{self.rate} ({self.rate_date})"
        )


class PaymentStatus(models.IntegerChoices):
    PENDING = 1, 'Pending'
    COMPLETED = 2, 'Completed'
    FAILED = 3, 'Failed'
