"""Execution utilities for agent forward() calls.

Provides response finalization logic as a standalone function, so any
agent implementation can reuse it.
"""

from __future__ import annotations

from typing import TYPE_CHECKING, Any

from fluxibly.agent.utils.monitoring import (
    AgentMonitoringSetup,
    finalize_agent_monitoring,
)

if TYPE_CHECKING:
    from fluxibly.agent.base import AgentConfig, AgentResponse
    from fluxibly.logging import Logger


async def finalize_response(
    llm_response: Any,
    mon: AgentMonitoringSetup | None,
    config: AgentConfig,
    context: dict[str, Any],
    messages: list[dict[str, Any]],
    iteration: int,
    llm_call_count: int,
    logger: Logger,
    tool_names: list[dict[str, Any]] | None = None,
    tool_interactions: list[dict[str, Any]] | None = None,
) -> AgentResponse:
    """Log output and finalize monitoring, return AgentResponse."""
    from fluxibly.agent.base import AgentResponse

    logger.log_output(llm_response)
    result = AgentResponse(content=llm_response)

    if tool_interactions:
        result.metadata["tool_interactions"] = tool_interactions

    if mon:
        await finalize_agent_monitoring(
            mon,
            result,
            config,
            context,
            messages,
            iteration,
            llm_call_count,
            tool_names=tool_names,
            tool_interactions=tool_interactions,
        )

    return result
