from __future__ import annotations

from typing import Any


def _require_fields(event: dict[str, Any], *, kind: str, required: list[str]) -> None:
    missing = [field for field in required if field not in event]
    if missing:
        raise ValueError(f"Missing fields for {kind}: {missing}")


def map_internal_event(event: dict[str, Any]) -> dict[str, Any]:
    kind = event.get("kind")

    if kind == "run_started":
        _require_fields(event, kind=kind, required=["session_id"])
        return {
            "type": "run.started",
            "run_id": event["session_id"],
        }

    if kind == "message_delta":
        _require_fields(event, kind=kind, required=["message_id", "delta"])
        return {
            "type": "message.delta",
            "message_id": event["message_id"],
            "delta": event["delta"],
        }

    if kind == "tool_started":
        _require_fields(event, kind=kind, required=["message_id", "tool_name"])
        return {
            "type": "tool.started",
            "message_id": event["message_id"],
            "tool_name": event["tool_name"],
        }

    if kind == "tool_completed":
        _require_fields(event, kind=kind, required=["message_id", "tool_name"])
        return {
            "type": "tool.completed",
            "message_id": event["message_id"],
            "tool_name": event["tool_name"],
            "result": event.get("result"),
        }

    if kind == "run_completed":
        _require_fields(event, kind=kind, required=["session_id"])
        return {
            "type": "run.completed",
            "run_id": event["session_id"],
            "output": event.get("output", ""),
        }

    if kind == "run_failed":
        _require_fields(event, kind=kind, required=["session_id"])
        return {
            "type": "run.failed",
            "run_id": event["session_id"],
            "error": event.get("error", ""),
        }

    raise ValueError(f"Unsupported event kind: {kind}")
