"""Public /v1 sessions."""

from __future__ import annotations

from typing import TYPE_CHECKING, Any

from ...models.v1.common import WriteResult
from ...models.v1.pagination import Page
from ...models.v1.sessions import (
    BatchUpsertSessionsRequest,
    CreateSessionRequest,
    SessionDetail,
    SessionSummary,
)
from ...models.v1.streams import StreamSummary
from ._helpers import dump_model, parse_detail, parse_page

if TYPE_CHECKING:
    from ..._http import HttpTransport


class SessionsResource:
    """client.sessions — /v1/sessions."""

    def __init__(self, http: HttpTransport) -> None:
        self._http = http

    def list(
        self,
        *,
        worker_id: str | None = None,
        factory_id: str | None = None,
        started_at_from: str | None = None,
        started_at_to: str | None = None,
        page_size: int = 50,
        cursor: str | None = None,
    ) -> Page[SessionSummary]:
        params: dict[str, Any] = {"page_size": page_size}
        for key, value in {
            "cursor": cursor,
            "worker_id": worker_id,
            "factory_id": factory_id,
            "started_at_from": started_at_from,
            "started_at_to": started_at_to,
        }.items():
            if value is not None:
                params[key] = value

        return parse_page(self._http.get("/sessions", params=params), SessionSummary)

    def get(self, session_id: str) -> SessionDetail:
        return parse_detail(self._http.get(f"/sessions/{session_id}"), SessionDetail)

    def streams(
        self,
        session_id: str,
        *,
        modality: str | None = None,
        stream_role: str | None = None,
        page_size: int = 50,
        cursor: str | None = None,
    ) -> Page[StreamSummary]:
        params: dict[str, Any] = {"page_size": page_size}
        for key, value in {
            "cursor": cursor,
            "modality": modality,
            "stream_role": stream_role,
        }.items():
            if value is not None:
                params[key] = value
        return parse_page(
            self._http.get(f"/sessions/{session_id}/streams", params=params),
            StreamSummary,
        )

    def create(self, body: CreateSessionRequest) -> SessionDetail:
        return parse_detail(
            self._http.post("/sessions", json=dump_model(body)),
            SessionDetail,
        )

    def batch(self, body: BatchUpsertSessionsRequest) -> WriteResult:
        return parse_detail(
            self._http.post("/sessions/batch", json=dump_model(body)),
            WriteResult,
        )
