import re

from django.utils.html import escape
from django.utils.safestring import mark_safe


def turn_snippet(text: str, query: str, radius: int = 120) -> str:
    """Return a short escaped HTML snippet around the first case-insensitive match."""
    text = escape(text or "")
    q = escape(query or "")
    lower = text.lower()
    idx = lower.find(q.lower())
    if idx == -1:
        snippet = text[: radius * 2]
    else:
        start = max(0, idx - radius)
        end = min(len(text), idx + len(q) + radius)
        snippet = text[start:end]
        if start > 0:
            snippet = "…" + snippet
        if end < len(text):
            snippet = snippet + "…"
    pattern = re.compile(re.escape(q), re.IGNORECASE)
    snippet = pattern.sub(lambda m: f"<mark>{m.group(0)}</mark>", snippet)
    return mark_safe(snippet)


def matching_turns(logdata, query: str) -> list[dict]:
    """Return a list of turns whose prompt or response matches the query."""
    if not logdata or not logdata.turns or not query:
        return []
    query_lower = query.lower()
    turns = []
    for i, turn in enumerate(logdata.turns, start=1):
        prompt = turn.get("prompt") or ""
        response = turn.get("response") or ""
        if query_lower in prompt.lower() or (
            response and query_lower in response.lower()
        ):
            turns.append(
                {
                    "number": i,
                    "prompt": turn_snippet(prompt, query),
                    "response": turn_snippet(response, query) if response else None,
                }
            )
    return turns
