from django.db import models
from django.core.validators import URLValidator


class StoreRegistry(models.Model):
    """
    Each record represents an independent eCommerce store whose product API
    ACA can query.  Stores are added/removed entirely through Django admin —
    no code changes required.
    """

    AUTH_METHOD_CHOICES = [
        ("api_key_header", "API Key in Header"),
        ("bearer_token", "Bearer Token"),
        ("query_param", "API Key as Query Param"),
        ("none", "No Authentication"),
    ]

    name = models.CharField(max_length=200)
    slug = models.SlugField(max_length=200, unique=True)
    base_api_url = models.URLField(
        help_text="Root URL of the store API, e.g. https://store.example.com/api"
    )
    api_key = models.CharField(max_length=500, blank=True, default="")
    auth_method = models.CharField(
        max_length=20, choices=AUTH_METHOD_CHOICES, default="api_key_header"
    )
    auth_header_name = models.CharField(
        max_length=100,
        default="X-Api-Key",
        help_text="Header name when using API Key in Header auth method",
    )
    search_endpoint = models.CharField(
        max_length=300,
        default="products/search/",
        help_text="Path appended to base URL for product search",
    )
    detail_endpoint = models.CharField(
        max_length=300,
        default="products/",
        help_text="Path appended to base URL for product detail (ID appended at end)",
    )
    response_mapping = models.JSONField(
        default=dict,
        blank=True,
        help_text=(
            "JSON mapping from store field names to ACA's normalized names. "
            'Example: {"img": "image_url", "title": "name"}'
        ),
    )
    logo = models.URLField(blank=True, default="")
    is_active = models.BooleanField(default=True, db_index=True)
    priority = models.IntegerField(
        default=0,
        help_text="Higher value = higher priority in result ranking",
    )
    added_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        verbose_name = "Store"
        verbose_name_plural = "Store Registry"
        ordering = ["-priority", "name"]

    def __str__(self):
        status = "active" if self.is_active else "inactive"
        return f"{self.name} ({status})"


class ACASettings(models.Model):
    """
    Singleton-style model for storing ACA platform configuration.
    Only one row should exist — use ACASettings.load() to get it.
    """

    # ── LLM Provider ─────────────────────────────────────────────
    LLM_PROVIDER_CLAUDE = "claude"
    LLM_PROVIDER_OPENAI = "openai"
    LLM_PROVIDER_CHOICES = [
        (LLM_PROVIDER_CLAUDE, "Anthropic Claude"),
        (LLM_PROVIDER_OPENAI, "OpenAI ChatGPT"),
    ]

    llm_provider = models.CharField(
        max_length=20,
        choices=LLM_PROVIDER_CHOICES,
        default=LLM_PROVIDER_CLAUDE,
        help_text="Which AI provider powers the shopping assistant",
    )

    # ── Anthropic / Claude ────────────────────────────────────────
    anthropic_api_key = models.CharField(
        max_length=500, blank=True, default="",
        help_text="Anthropic API key for Claude",
    )
    llm_model = models.CharField(
        max_length=100, blank=True, default="claude-haiku-4-5-20251001",
        help_text="Claude model identifier",
    )
    llm_max_tokens = models.IntegerField(default=1024)

    # ── OpenAI / ChatGPT ──────────────────────────────────────────
    openai_api_key = models.CharField(
        max_length=500, blank=True, default="",
        help_text="OpenAI API key for ChatGPT",
    )
    openai_model = models.CharField(
        max_length=100, blank=True, default="gpt-4o-mini",
        help_text="OpenAI model (e.g. gpt-4o, gpt-4o-mini, gpt-3.5-turbo)",
    )

    # ── Vendor Subscription ───────────────────────────────────────
    vendor_registration_fee = models.DecimalField(
        max_digits=10, decimal_places=2, default="3500.00",
        help_text="Annual subscription fee (GHS) charged to new vendors at registration",
    )
    vendor_subscription_months = models.PositiveIntegerField(
        default=12,
        help_text="How many months one paid subscription covers",
    )
    vendor_registration_free = models.BooleanField(
        default=False,
        help_text="When enabled, new vendors register for free for the duration below",
    )
    vendor_free_duration_months = models.PositiveIntegerField(
        default=1,
        help_text="How many months the free subscription lasts when free mode is on",
    )

    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        verbose_name = "ACA Settings"
        verbose_name_plural = "ACA Settings"

    def __str__(self):
        has_key = "configured" if self.anthropic_api_key or self.openai_api_key else "not set"
        return f"ACA Settings (AI: {self.get_llm_provider_display()}, key: {has_key})"

    @classmethod
    def load(cls):
        obj, _ = cls.objects.get_or_create(pk=1)
        return obj

    @property
    def masked_key(self):
        """Masked Anthropic key."""
        k = self.anthropic_api_key
        if not k:
            return ""
        if len(k) <= 12:
            return "****"
        return k[:8] + "****" + k[-4:]

    @property
    def masked_openai_key(self):
        """Masked OpenAI key."""
        k = self.openai_api_key
        if not k:
            return ""
        if len(k) <= 12:
            return "****"
        return k[:8] + "****" + k[-4:]

    @property
    def active_provider(self) -> str:
        """Returns the currently active provider string."""
        return self.llm_provider

    @property
    def active_key_configured(self) -> bool:
        """True if the currently selected provider has an API key set."""
        if self.llm_provider == self.LLM_PROVIDER_OPENAI:
            return bool(self.openai_api_key)
        return bool(self.anthropic_api_key)


class StoreHealthLog(models.Model):
    """Tracks API health per store for monitoring and adaptive routing."""

    store = models.ForeignKey(
        StoreRegistry, on_delete=models.CASCADE, related_name="health_logs"
    )
    checked_at = models.DateTimeField(auto_now_add=True)
    response_time_ms = models.IntegerField(null=True, blank=True)
    status_code = models.IntegerField(null=True, blank=True)
    success = models.BooleanField(default=True)
    error_message = models.TextField(blank=True, default="")

    class Meta:
        ordering = ["-checked_at"]
        indexes = [
            models.Index(fields=["store", "-checked_at"]),
        ]

    def __str__(self):
        return f"{self.store.name} — {self.checked_at:%Y-%m-%d %H:%M} — {'OK' if self.success else 'FAIL'}"