"""Agent event logging helpers used by the Tools API."""

from typing import Any, Optional
from uuid import uuid4

from app.agent_names import normalize_agent_key
from app.db import execute_returning, json_param


def log_agent_event(
    *,
    agent_name: str,
    event_type: str,
    title: str,
    body: Optional[str] = None,
    agent_type: str = "openswarm",
    metadata: Optional[dict[str, Any]] = None,
    status: str = "completed",
    related_table: Optional[str] = None,
    related_id: Optional[int] = None,
    channel: str = "dashboard",
    correlation_id: Optional[str] = None,
    source_agent: Optional[str] = None,
    target_agent: Optional[str] = None,
) -> dict[str, Any]:
    meta = dict(metadata or {})
    if correlation_id:
        meta.setdefault("correlation_id", correlation_id)
    if source_agent:
        meta.setdefault("source_agent", normalize_agent_key(source_agent))
    if target_agent:
        meta.setdefault("target_agent", normalize_agent_key(target_agent))
    if "correlation_id" not in meta:
        meta.setdefault("correlation_id", str(uuid4()))

    normalized = normalize_agent_key(agent_name)
    row = execute_returning(
        """
        INSERT INTO agent_events (
            agent_name, agent_type, event_type, title, body, metadata,
            status, related_table, related_id, channel
        )
        VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
        RETURNING *
        """,
        (
            normalized,
            agent_type,
            event_type,
            title,
            body,
            json_param(meta),
            status,
            related_table,
            related_id,
            channel,
        ),
    )
    if row is None:
        raise RuntimeError("Failed to insert agent event")
    return row
