from __future__ import annotations

import re

from django.utils.translation import gettext as _

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


class ContactSkill(AiAssistantSkill):
    key = SKILL_CONTACT
    label = "Contact routing"
    allowed_modes = (MODE_CUSTOMER, MODE_ADMIN)
    public_safe = True

    _CONTACT_PATTERNS = (
        r"\bcontact\b",
        r"\bemail\b",
        r"\bcall\b",
        r"\bhuman\b",
        r"\bsupport\b",
        r"\bhelp\b",
        r"\breach\b",
        r"\btalk\b",
        r"\bspeak\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._CONTACT_PATTERNS):
            return SkillMatch(score=35, reason="contact_intent")
        return SkillMatch(score=0, reason="no_contact_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)

        contact_page_url = self._clean_value(settings_obj.contact_page_url)
        booking_page_url = self._clean_value(settings_obj.booking_page_url)
        public_support_email = self._clean_value(settings_obj.public_support_email)
        contact_instructions = self._clean_value(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 contact_page_url:
            items.append(_("Contact page: %(value)s") % {"value": contact_page_url})
        if booking_page_url:
            items.append(_("Booking page: %(value)s") % {"value": booking_page_url})
        if public_support_email:
            items.append(
                _("Public support email: %(value)s") % {"value": public_support_email}
            )
        if contact_instructions:
            items.append(
                _("Contact instructions: %(value)s") % {"value": contact_instructions}
            )

        escalation_email = self._clean_value(
            getattr(settings_obj, "escalation_email", "")
        )
        if mode == MODE_ADMIN and escalation_email:
            items.append(
                _("Internal escalation email: %(value)s") % {"value": escalation_email}
            )

        if not items:
            return SkillContextResult()

        instruction = _(
            "Contact routing context may be provided below. Use it to guide the user to the correct page or public support route. Do not claim that an email, ticket, callback, or booking has already been sent or created. Ask only for minimal non-sensitive details when appropriate, and never ask for passwords, API keys, or 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()
