"""Evaluation target for AgentByte agents."""

from __future__ import annotations

import time

from agentbyte.agents import BaseAgent
from agentbyte.cancellation_token import CancellationToken
from agentbyte.messages import Usage

from agentbyte.eval.base import BaseEvalTarget
from agentbyte.eval.types import EvalTask, EvalTrajectory


class AgentEvalTarget(BaseEvalTarget):
    """Wrap an agent as an evaluation target."""

    def __init__(self, agent: BaseAgent, name: str | None = None) -> None:
        super().__init__(name=name or getattr(agent, "name", "Agent"))
        self.agent = agent

    async def run(
        self,
        task: EvalTask,
        cancellation_token: CancellationToken | None = None,
    ) -> EvalTrajectory:
        start_time = time.perf_counter()
        if cancellation_token and cancellation_token.is_cancelled():
            return self._build_failed_trajectory(
                task,
                start_time,
                error="Execution cancelled before agent run",
            )

        try:
            response = await self.agent.run(
                task.input,
                cancellation_token=cancellation_token,
            )
            elapsed_ms = int((time.perf_counter() - start_time) * 1000)
            return EvalTrajectory(
                task=task,
                messages=response.messages,
                success=True,
                error=None,
                usage=response.usage,
                metadata={
                    "target_type": "agent",
                    "target_name": self.name,
                    "execution_time_ms": elapsed_ms,
                },
            )
        except Exception as exc:
            return self._build_failed_trajectory(task, start_time, error=str(exc))

    def _build_failed_trajectory(
        self,
        task: EvalTask,
        start_time: float,
        *,
        error: str,
    ) -> EvalTrajectory:
        elapsed_ms = int((time.perf_counter() - start_time) * 1000)
        return EvalTrajectory(
            task=task,
            messages=[],
            success=False,
            error=error,
            usage=Usage(duration_ms=elapsed_ms),
            metadata={
                "target_type": "agent",
                "target_name": self.name,
                "execution_time_ms": elapsed_ms,
            },
        )


__all__ = ["AgentEvalTarget"]
