from __future__ import annotations

import re

from django.utils.translation import gettext as _

from ..constants import MODE_ADMIN, MODE_CUSTOMER, SKILL_QUOTE
from ..service_router import route_service_category
from .base import AiAssistantSkill, SkillContextResult, SkillMatch


class QuoteSkill(AiAssistantSkill):
    key = SKILL_QUOTE
    label = "Quote and project intake routing"
    allowed_modes = (MODE_CUSTOMER, MODE_ADMIN)
    public_safe = True

    _QUOTE_PATTERNS = (
        r"\bquote\b",
        r"\bproposal\b",
        r"\bestimate\b",
        r"\bprice estimate\b",
        r"\bproject\b",
        r"\bwebsite project\b",
        r"\bwebshop project\b",
        r"\bcustom work\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:
        text = (request_text or "").lower()
        if any(re.search(pattern, text) for pattern in self._QUOTE_PATTERNS):
            return SkillMatch(score=40, reason="quote_intent")
        return SkillMatch(score=0, reason="no_quote_intent")

    def build_context(
        self, request_text: str, request, site, mode: str, settings_obj
    ) -> SkillContextResult:
        items: list[str] = []
        route_match = route_service_category(request_text, site, request=request)

        quote_page_url = self._clean_value(getattr(settings_obj, "quote_page_url", ""))
        contact_page_url = self._clean_value(
            getattr(settings_obj, "contact_page_url", "")
        )
        contact_instructions = self._clean_value(
            getattr(settings_obj, "contact_instructions", "")
        )

        if route_match is not None:
            items.extend(
                [
                    _("Detected service category: %(value)s")
                    % {"value": route_match.category},
                    _("Relevant service page: %(value)s")
                    % {"value": route_match.page_title},
                    _("Relevant service URL: %(value)s")
                    % {"value": route_match.page_url},
                    _("Matched keywords: %(value)s")
                    % {"value": ", ".join(route_match.matched_keywords)},
                ]
            )

        if quote_page_url:
            items.append(_("Quote request page: %(value)s") % {"value": quote_page_url})
        if contact_page_url:
            items.append(_("Contact page: %(value)s") % {"value": contact_page_url})
        if contact_instructions:
            items.append(
                _("Project intake instructions: %(value)s")
                % {"value": contact_instructions}
            )

        items.extend(
            [
                _(
                    "Suggested intake details: project type (website, webshop, support, or custom work)"
                ),
                _("Suggested intake details: business name or industry"),
                _("Suggested intake details: preferred deadline"),
                _("Suggested intake details: existing website URL if available"),
                _("Suggested intake details: desired features or scope"),
                _("Suggested intake details: preferred contact route"),
                _(
                    "Suggested intake details: budget range only if the user volunteers it"
                ),
            ]
        )

        if not items:
            return SkillContextResult()

        instruction = _(
            "Quote and project intake routing context may be provided below. Use it to guide the user to the correct quote or contact route. Do not claim that a quote, estimate, proposal, ticket, or project request has already been created or sent. Do not invent prices, timelines, or delivery commitments. Ask only for safe non-sensitive project details when useful, and never request passwords, API keys, payment details, or other secrets."
        )
        return SkillContextResult.from_items(
            items,
            instruction=instruction,
            metadata={
                "skill": self.key,
                "result_count": len(items),
                "service_category": route_match.category if route_match else "",
            },
        )

    def _clean_value(self, value) -> str:
        return (value or "").strip()
