from __future__ import annotations

import re

from django.utils.translation import gettext as _

from ..constants import (
    MODE_ADMIN,
    MODE_CUSTOMER,
    SKILL_PRODUCT_DETAIL,
)
from .base import SkillContextResult, SkillMatch
from .product_search import ProductSearchSkill


class ProductDetailSkill(ProductSearchSkill):
    key = SKILL_PRODUCT_DETAIL
    label = "Product detail"
    allowed_modes = (MODE_CUSTOMER, MODE_ADMIN)
    public_safe = True

    _DETAIL_PATTERNS = (
        r"\bcompare\b",
        r"\bspec(?:ification|ifications|s)?\b",
        r"\bdetails?\b",
        r"\bmore about\b",
        r"\bwhich product\b",
        r"\bbetter for\b",
        r"\bproduct category\b",
        r"\bproduct description\b",
        r"\brelated product\b",
        r"\bvariant\b",
    )

    def is_enabled(self, site, settings_obj, mode: str) -> bool:
        return self.key in settings_obj.enabled_skill_keys(mode)

    def match(
        self, request_text: str, request, site, mode: str, settings_obj
    ) -> SkillMatch:
        if self._load_product_model() is None:
            return SkillMatch(score=0, reason="catalogue_unavailable")

        text = (request_text or "").lower()
        if any(re.search(pattern, text) for pattern in self._DETAIL_PATTERNS):
            return SkillMatch(score=45, reason="product_detail_intent")
        if self._keywords(request_text):
            return SkillMatch(score=18, reason="product_lookup_fallback")
        return SkillMatch(score=0, reason="no_product_detail_intent")

    def build_context(
        self, request_text: str, request, site, mode: str, settings_obj
    ) -> SkillContextResult:
        results = self._search_products(
            request_text=request_text,
            request=request,
            max_items=max(int(settings_obj.max_skill_context_items or 1), 1),
        )
        if not results:
            return SkillContextResult()

        items = []
        for index, result in enumerate(results, start=1):
            product = result["product"]
            lines = [
                _("%(index)s. Product: %(name)s")
                % {"index": index, "name": result["name"]},
                _("   URL: %(url)s") % {"url": result["url"]},
            ]
            if result["category"]:
                lines.append(_("   Category: %(category)s") % result)
            if result["description"]:
                lines.append(_("   Description: %(description)s") % result)

            relation_summary = self._parent_child_summary(product)
            if relation_summary:
                lines.append(
                    _("   Product relation: %(value)s") % {"value": relation_summary}
                )

            for attribute in self._product_attributes(product):
                lines.append(_("   Specification: %(value)s") % {"value": attribute})

            items.append("\n".join(lines))

        instruction = _(
            "Relevant public product detail context may be provided below. Use it to explain product descriptions, categories, specifications, variants, and basic comparison guidance only when that context is present. Recommend only products from the provided context. Do not invent prices, availability, discounts, delivery times, basket actions, checkout actions, or customer-specific product data."
        )
        return SkillContextResult.from_items(
            items,
            instruction=instruction,
            metadata={"skill": self.key, "result_count": len(results)},
        )
