"""Summarize session replay highlights."""

from __future__ import annotations

import os
import re
from typing import Dict, List

import httpx


async def summarize_highlights(highlights: List[Dict[str, str]]) -> List[Dict[str, str]]:
    """Optionally summarize highlights via LLM.

    If no API key or disabled, returns highlights unchanged.
    """
    if not highlights:
        return highlights

    if os.environ.get("HIKAFLOW_HIGHLIGHT_SUMMARY") != "1":
        return highlights

    base_url = os.environ.get("HIKAFLOW_LLM_BASE_URL")
    api_key = os.environ.get("HIKAFLOW_LLM_API_KEY") or os.environ.get("OPENAI_API_KEY")
    if not base_url and not api_key:
        return highlights

    prompt = "\n".join([f"- {_redact_text(h.get('summary', '') or '')}" for h in highlights])
    model = os.environ.get("HIKAFLOW_LLM_MODEL", "gpt-5-mini")
    payload = {
        "model": model,
        "messages": [
            {
                "role": "system",
                "content": "Summarize each bullet into a short, non-sensitive phrase. Preserve ordering.",
            },
            {"role": "user", "content": prompt},
        ],
        "max_tokens": 200,
    }

    try:
        url = "https://api.openai.com/v1/chat/completions"
        if base_url:
            url = base_url.rstrip("/") + "/v1/chat/completions"
        headers = {"Content-Type": "application/json"}
        if api_key:
            headers["Authorization"] = f"Bearer {api_key}"
        async with httpx.AsyncClient(timeout=20.0) as client:
            resp = await client.post(url, headers=headers, json=payload)
            resp.raise_for_status()
            content = resp.json()["choices"][0]["message"]["content"]
    except Exception:
        return highlights

    lines = [line.strip("- ") for line in content.split("\n") if line.strip()]
    if not lines:
        return highlights

    summarized: List[Dict[str, str]] = []
    for idx, highlight in enumerate(highlights):
        summary = lines[idx] if idx < len(lines) else highlight.get("summary", "")
        item = dict(highlight)
        item["summary"] = summary
        summarized.append(item)

    return summarized


def _redact_text(text: str) -> str:
    """Redact obvious PII from highlight summaries before sending to LLM."""
    patterns = [
        re.compile(r"[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}", re.IGNORECASE),
        re.compile(r"\b\d{3}-\d{2}-\d{4}\b"),  # SSN
        re.compile(r"\b(?:\d[ -]*?){13,19}\b"),  # credit card-ish
        re.compile(r"\b(?:sk|rk|pk)_[A-Za-z0-9]{16,}\b"),  # API tokens
    ]
    redacted = text
    for pattern in patterns:
        redacted = pattern.sub("[redacted]", redacted)
    return redacted
