"""Fire-and-forget LLM call and error recording."""

from __future__ import annotations

import logging
import uuid
from typing import TYPE_CHECKING, Any

if TYPE_CHECKING:
    from codeflash_api.llm._client import LLMResponse

log = logging.getLogger(__name__)


async def record_llm_call(
    trace_id: str,
    call_type: str,
    model_name: str,
    messages: list[dict[str, Any]],
    latency_ms: int,
    *,
    user_id: str | None = None,
    result: LLMResponse | None = None,
    error: Exception | None = None,
    llm_cost: float | None = None,
) -> str:
    """
    Record an LLM call.  Returns the generated ``llm_call_id``.

    Currently logs only — database persistence will be added when
    the ``llm_calls`` table is wired up.
    """
    llm_call_id = str(uuid.uuid4())
    status = "success" if result else "failed"

    input_tokens = result.usage.input_tokens if result else 0
    output_tokens = result.usage.output_tokens if result else 0

    log.info(
        "LLM call recorded: id=%s trace=%s type=%s model=%s"
        " status=%s tokens=%d/%d cost=%.6f latency=%dms",
        llm_call_id,
        trace_id,
        call_type,
        model_name,
        status,
        input_tokens,
        output_tokens,
        llm_cost or 0.0,
        latency_ms,
    )

    if error:
        log.info(
            "LLM call error: id=%s error_type=%s error=%s",
            llm_call_id,
            type(error).__name__,
            error,
        )

    return llm_call_id


async def record_error(
    trace_id: str,
    error_type: str,
    error_message: str,
    *,
    error_category: str = "llm_error",
    severity: str = "error",
    error_code: str | None = None,
    context: dict[str, Any] | None = None,
) -> str:
    """
    Record an error.  Returns the generated ``error_id``.

    Currently logs only — database persistence will be added when
    the ``optimization_errors`` table is wired up.
    """
    error_id = str(uuid.uuid4())

    log.warning(
        "Error recorded: id=%s trace=%s type=%s category=%s"
        " severity=%s message=%s",
        error_id,
        trace_id,
        error_type,
        error_category,
        severity,
        error_message,
    )

    return error_id
