"""Quality telemetry events written into StructuredAnswerContract.quality_meta."""

from __future__ import annotations

import uuid
from typing import Any

QUALITY_EVENT_NAMES = frozenset(
    {
        "duplicate_title_removed",
        "duplicate_first_sentence_removed",
        "fake_source_stripped",
        "semantic_blocks_merged",
        "level_mismatch_detected",
        "renderer_title_stripped",
        "prompt_duplicates_found",
        "correlation_id",
        "chunks_deduplicated",
        "sources_deduplicated",
        "prompt_titles_deduplicated",
    }
)


def new_correlation_id() -> str:
    return uuid.uuid4().hex[:16]


def ensure_quality_meta(meta: dict[str, Any] | None) -> dict[str, Any]:
    payload = dict(meta or {})
    events = payload.get("events")
    if not isinstance(events, list):
        payload["events"] = []
    return payload


def record_event(
    meta: dict[str, Any],
    event: str,
    *,
    count: int = 1,
    detail: str = "",
) -> dict[str, Any]:
    payload = ensure_quality_meta(meta)
    if event not in QUALITY_EVENT_NAMES and event != "correlation_id":
        return payload
    entry: dict[str, Any] = {"event": event, "count": max(int(count), 1)}
    if detail:
        entry["detail"] = str(detail)[:500]
    payload["events"].append(entry)
    return payload


def set_correlation_id(meta: dict[str, Any], correlation_id: str) -> dict[str, Any]:
    payload = ensure_quality_meta(meta)
    payload["correlation_id"] = str(correlation_id or "").strip()
    return payload


def event_count(meta: dict[str, Any], event: str) -> int:
    events = meta.get("events") if isinstance(meta, dict) else None
    if not isinstance(events, list):
        return 0
    total = 0
    for item in events:
        if isinstance(item, dict) and item.get("event") == event:
            total += int(item.get("count") or 1)
    return total
