"""Orchestrator API client."""

from __future__ import annotations

import requests

from .resources import AgentsResource, ImagesResource, RunsResource
from .types import HealthResponse


class OrchestratorClient:
    """Synchronous client for the Agent Orchestration API.

    Usage::

        client = OrchestratorClient("http://localhost:8000")
        agents = client.agents.list()
        run = client.runs.create(agent_id="agt-...", prompt="hello")
    """

    def __init__(self, base_url: str, openai_api_key: str | None = None) -> None:
        self._base_url = base_url.rstrip("/")
        self._session = requests.Session()
        self._session.headers["Content-Type"] = "application/json"

        self.agents = AgentsResource(self._session, self._base_url)
        self.images = ImagesResource(self._session, self._base_url)
        self.runs = RunsResource(self._session, self._base_url, openai_api_key=openai_api_key)

    def health(self) -> HealthResponse:
        resp = self._session.get(f"{self._base_url}/health")
        if resp.status_code >= 400:
            resp.raise_for_status()
        return HealthResponse.model_validate(resp.json())

    def close(self) -> None:
        self._session.close()

    def __enter__(self) -> OrchestratorClient:
        return self

    def __exit__(self, *args: object) -> None:
        self.close()
