"""Escalation Engine global search integration."""

from __future__ import annotations

from typing import TYPE_CHECKING

from simorgh.core.search import SearchableSpec, SearchHit, register_searchable

if TYPE_CHECKING:
    from simorgh.core.context import RequestContext


def _search_escalation_rules(ctx: RequestContext, query: str, limit: int) -> list[SearchHit]:
    from django.db.models import Q

    from simorgh.apps.escalation_engine.models import EscalationRule

    if not ctx.tenant:
        return []

    qs = (
        EscalationRule.objects.filter(tenant_id=ctx.tenant.pk)
        .filter(Q(name__icontains=query) | Q(description__icontains=query))
        .distinct()
        .order_by("name")[:limit]
    )

    return [
        SearchHit(
            entity="escalation_engine.rule",
            id=str(r.public_id),
            title=r.name,
            subtitle=r.get_trigger_type_display(),
            url=f"/escalation/rules/{r.public_id}/",
            score=2.0 if query.lower() in r.name.lower() else 1.0,
        )
        for r in qs
    ]


register_searchable(
    SearchableSpec(
        entity="escalation_engine.rule",
        label_key="escalation_engine.rule",
        search=_search_escalation_rules,
    )
)
