from __future__ import annotations

import json

from .models import LogEvent
from .normalization import FIELD_ALIASES, canonical_value


def _quote(value: str) -> str:
    escaped = value.replace("\\", "\\\\").replace('"', '\\"')
    return f'"{escaped}"'


def _field_group(canonical: str, value: str, *, limit: int = 6) -> str:
    aliases = FIELD_ALIASES.get(canonical, (canonical,))[:limit]
    return "(" + " OR ".join(f"{field}:{_quote(value)}" for field in aliases) + ")"


def event_query_details(event: LogEvent) -> dict[str, str]:
    """Build a copyable Graylog query for an event without assuming one vendor schema."""
    terms: list[str] = []
    for canonical in ("srcip", "dstip", "action", "dns_query"):
        value = canonical_value(event.fields, canonical)
        if value:
            terms.append(_field_group(canonical, value))
    timestamp = event.fields.get("eventtime", event.fields.get("timestamp", ""))
    if not terms:
        context = canonical_value(event.fields, "context")
        if context:
            terms.append(_field_group("context", context, limit=4))
    return {
        "stream": event.fields.get("fgai_stream", ""),
        "stream_id": event.fields.get("fgai_stream_id", ""),
        "timestamp": timestamp,
        "query": " AND ".join(terms) if terms else "*",
        "raw": event.raw if event.raw.startswith("{") else json.dumps(event.fields, sort_keys=True),
    }
