from __future__ import annotations

from typing import TYPE_CHECKING

from ..objects.agent_run import AgentRun
from ..objects.list_response import ListResponse

if TYPE_CHECKING:
    from ..client import WhatsrbCloud
    from ..connection import Connection


class AgentRuns:
    def __init__(self, *, client: WhatsrbCloud, connection: Connection, agent_id: str):
        self._client = client
        self._connection = connection
        self._agent_id = agent_id

    def list(self) -> ListResponse[AgentRun]:
        response = self._connection.get(self._base_path)
        data = [AgentRun(r, client=self._client) for r in (response.get("data") or [])]
        return ListResponse(data=data, meta=response.get("meta", {}))

    def create(self, *, input, metadata: dict | None = None) -> AgentRun:
        body = {"input": input}
        if metadata:
            body["metadata"] = metadata
        response = self._connection.post(self._base_path, {"run": body})
        return AgentRun(response["data"], client=self._client)

    def retrieve(self, id: str) -> AgentRun:
        response = self._connection.get(f"{self._base_path}/{id}")
        return AgentRun(response["data"], client=self._client)

    @property
    def _base_path(self) -> str:
        return f"/agents/{self._agent_id}/runs"
