from __future__ import annotations

from django import template
from django.urls import reverse
from wagtail.models import Site

from ..models import AiAssistantSiteSettings
from ..views import _customer_chat_strings

register = template.Library()

COMMERCE_PATH_FRAGMENTS = (
    "/basket",
    "/checkout",
    "/payment",
    "/order",
)
COMMERCE_NAMESPACES = {
    "basket",
    "checkout",
    "payment",
}


def _is_admin_request(request) -> bool:
    if not request:
        return False
    path = getattr(request, "path", "") or ""
    if path.startswith("/admin/"):
        return True
    resolver_match = getattr(request, "resolver_match", None)
    namespaces = set(getattr(resolver_match, "namespaces", []) or [])
    return "wagtailadmin" in namespaces or "admin" in namespaces


def _is_commerce_flow(request) -> bool:
    if not request:
        return False
    path = (getattr(request, "path", "") or "").lower()
    if any(fragment in path for fragment in COMMERCE_PATH_FRAGMENTS):
        return True
    resolver_match = getattr(request, "resolver_match", None)
    namespaces = set(getattr(resolver_match, "namespaces", []) or [])
    namespace = getattr(resolver_match, "namespace", None)
    if namespace:
        namespaces.add(namespace)
    return bool(COMMERCE_NAMESPACES.intersection(namespaces))


def _resolve_site(request):
    if request:
        site = Site.find_for_request(request)
        if site:
            return site
    return Site.objects.filter(is_default_site=True).first()


@register.inclusion_tag("ai_assistant/includes/chat_widget.html", takes_context=True)
def ai_assistant_widget(context):
    request = context.get("request")
    if _is_admin_request(request):
        return {"render_widget": False}

    site = _resolve_site(request)
    if not site:
        return {"render_widget": False}

    try:
        settings_obj = AiAssistantSiteSettings.for_site(site)
    except Exception:
        return {"render_widget": False}

    if not settings_obj.customer_widget_enabled():
        return {"render_widget": False}

    if settings_obj.hide_widget_on_checkout and _is_commerce_flow(request):
        return {"render_widget": False}

    chat_strings = _customer_chat_strings()
    chat_strings.update(
        {
            "launcherLabel": settings_obj.effective_widget_launcher_label(),
            "title": settings_obj.effective_widget_title(),
            "welcomeText": settings_obj.effective_widget_welcome_text(),
        }
    )
    return {
        "render_widget": True,
        "chat_api_url": reverse("ai_assistant:customer_chat_api"),
        "reset_api_url": reverse("ai_assistant:customer_chat_reset_api"),
        "widget_position": settings_obj.widget_position,
        "launcher_label": settings_obj.effective_widget_launcher_label(),
        "widget_title": settings_obj.effective_widget_title(),
        "widget_welcome_text": settings_obj.effective_widget_welcome_text(),
        "chat_strings": chat_strings,
    }
