"""Sandboxes resource."""

from __future__ import annotations

from typing import TYPE_CHECKING

from .._base import BaseResource
from ..exceptions import NotFoundError
from ..types import Agent, AgentCreate

if TYPE_CHECKING:
    from .._auth import Authenticator


class SandboxesResource(BaseResource):

    def __init__(self, session: object, base_url: str, authenticator: Authenticator | None = None) -> None:
        super().__init__(session, base_url, authenticator)  # type: ignore[arg-type]
        self._agent_id_cache: dict[str, str] = {}

    def _to_sandbox(self, agent: Agent) -> str:
        return agent.image

    def list(self) -> list[str]:
        resp = self._get("/agents")
        agents = [Agent.model_validate(a) for a in resp.json()]
        for agent in agents:
            self._agent_id_cache[agent.image] = agent.id
        return [agent.image for agent in agents]

    def register(self, sandbox: str) -> str:
        body = AgentCreate(image=sandbox)
        resp = self._post("/agents", data=body.model_dump_json())
        agent = Agent.model_validate(resp.json())
        self._agent_id_cache[agent.image] = agent.id
        return agent.image

    def get(self, sandbox: str) -> str:
        agent_id = self._resolve_agent_id(sandbox)
        if agent_id is None:
            raise NotFoundError(f"Sandbox not found: {sandbox}")
        return sandbox

    def _resolve_agent_id(self, sandbox: str) -> str | None:
        cached = self._agent_id_cache.get(sandbox)
        if cached is not None:
            return cached

        resp = self._get("/agents", params={"image": sandbox})
        agents = [Agent.model_validate(a) for a in resp.json()]
        if not agents:
            return None

        agent = agents[0]
        self._agent_id_cache[agent.image] = agent.id
        self._agent_id_cache[sandbox] = agent.id
        return agent.id
