from __future__ import annotations

from django.utils.translation import gettext as _

from ..constants import MODE_ADMIN, MODE_CUSTOMER, SKILL_SITE_INFO
from .base import AiAssistantSkill, SkillContextResult, SkillMatch


class SiteInfoSkill(AiAssistantSkill):
    key = SKILL_SITE_INFO
    label = "Site info"
    allowed_modes = (MODE_CUSTOMER, MODE_ADMIN)
    public_safe = True

    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 not site:
            return SkillMatch(score=0, reason="missing_site")
        return SkillMatch(score=10, reason="baseline_site_context")

    def build_context(
        self, request_text: str, request, site, mode: str, settings_obj
    ) -> SkillContextResult:
        items: list[str] = []
        site_name = (getattr(site, "site_name", "") or "").strip()
        hostname = (getattr(site, "hostname", "") or "").strip()
        business_description = (settings_obj.business_description or "").strip()
        assistant_tone = (settings_obj.assistant_tone or "").strip()
        mode_instructions = settings_obj.safe_mode_instructions(mode)

        if site_name:
            items.append(_("Site name: %(value)s") % {"value": site_name})
        if hostname:
            items.append(_("Site hostname: %(value)s") % {"value": hostname})
        if business_description:
            items.append(
                _("Business description: %(value)s") % {"value": business_description}
            )
        if assistant_tone:
            items.append(
                _("Preferred assistant tone: %(value)s") % {"value": assistant_tone}
            )
        if mode_instructions:
            items.append(
                _("Mode-specific site instructions: %(value)s")
                % {"value": mode_instructions}
            )

        instruction = _(
            "Use this site information when it is relevant, but do not invent facts that are not present in the provided context."
        )
        return SkillContextResult.from_items(
            items,
            instruction=instruction,
            metadata={"skill": self.key},
        )
