from __future__ import annotations

import re

from django.utils.translation import gettext as _

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


class BookingSkill(AiAssistantSkill):
    key = SKILL_BOOKING
    label = "Booking routing"
    allowed_modes = (MODE_CUSTOMER, MODE_ADMIN)
    public_safe = True

    _BOOKING_PATTERNS = (
        r"\bbook(?:ing)?\b",
        r"\bschedule\b",
        r"\bappointment\b",
        r"\bconsult(?:ation)?\b",
        r"\bdemo\b",
        r"\breservation\b",
        r"\barrange a call\b",
        r"\bbook a call\b",
        r"\bbook a service\b",
        r"\bschedule a call\b",
        r"\bschedule a demo\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._BOOKING_PATTERNS):
            return SkillMatch(score=40, reason="booking_intent")
        return SkillMatch(score=0, reason="no_booking_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)

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

        if not items:
            return SkillContextResult()

        instruction = _(
            "Booking routing context may be provided below. Use it to guide the user to the correct booking or contact route. Do not claim that a booking, reservation, appointment, consultation, demo, email, or calendar entry has already been created. Ask only for minimal non-sensitive details when useful, direct the user to complete the booking manually, 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()
