"""Log agent activity to agent_events for terminals and audit."""
from __future__ import annotations

import json
from typing import Any, Optional

from app.db import fetch_one
from app.services.agent_names import normalize_agent_key


def log_agent_event(
    agent_name: str,
    event_type: str,
    title: str,
    body: str = "",
    *,
    agent_type: Optional[str] = None,
    status: str = "completed",
    channel: str = "cockpit",
    metadata: Optional[dict[str, Any]] = None,
) -> Optional[dict[str, Any]]:
    key = normalize_agent_key(agent_name)
    if not key:
        return None
    meta = json.dumps(metadata or {})
    row = fetch_one(
        """
        INSERT INTO agent_events (agent_name, agent_type, event_type, title, body, status, channel, metadata)
        VALUES (%s, %s, %s, %s, %s, %s, %s, %s::jsonb)
        RETURNING id, agent_name, event_type, title, body, status, channel, metadata, created_at
        """,
        (
            key,
            agent_type or key,
            event_type,
            title[:255],
            (body or "")[:8000],
            status,
            channel,
            meta,
        ),
    )
    if not row:
        return None
    out = dict(row)
    if out.get("created_at") and hasattr(out["created_at"], "isoformat"):
        out["created_at"] = out["created_at"].isoformat()
    return out
