from __future__ import annotations

import httpx

from .models import (
    ChatMessageCreate,
    ChatMessageCreateRequest,
    ChatSession,
    ChatSessionCreate,
    ChatSessionCreateRequest,
    PaginatedChatMessageList,
    PaginatedChatSessionList,
)


class SyncKnowbaseChatKnowbaseChatAPI:
    """Synchronous API endpoints for Knowbase Chat."""

    def __init__(self, client: httpx.Client):
        """Initialize sync sub-client with shared httpx client."""
        self._client = client

    def projects_sessions_list(
        self,
        project_slug: str,
        ordering: str | None = None,
        page: int | None = None,
        page_size: int | None = None,
        search: str | None = None,
    ) -> list[PaginatedChatSessionList]:
        """
        Chat session management. POST
        /api/knowbase_chat/projects/{slug}/sessions/ — create session GET
        /api/knowbase_chat/projects/{slug}/sessions/ — list sessions GET
        /api/knowbase_chat/projects/{slug}/sessions/{id}/ — retrieve session
        """
        url = f"/api/knowbase_chat/projects/{project_slug}/sessions/"
        _params = {
            k: v for k, v in {
                "ordering": ordering,
                "page": page,
                "page_size": page_size,
                "search": search,
            }.items() if v is not None
        }
        response = self._client.get(url, params=_params)
        if not response.is_success:
            try:
                error_body = response.json()
            except Exception:
                error_body = response.text
            msg = f"{response.status_code}: {error_body}"
            raise httpx.HTTPStatusError(
                msg, request=response.request, response=response
            )
        return PaginatedChatSessionList.model_validate(response.json())


    def projects_sessions_create(
        self,
        project_slug: str,
        data: ChatSessionCreateRequest,
    ) -> ChatSessionCreate:
        """
        Chat session management. POST
        /api/knowbase_chat/projects/{slug}/sessions/ — create session GET
        /api/knowbase_chat/projects/{slug}/sessions/ — list sessions GET
        /api/knowbase_chat/projects/{slug}/sessions/{id}/ — retrieve session
        """
        url = f"/api/knowbase_chat/projects/{project_slug}/sessions/"
        response = self._client.post(url, json=data.model_dump(mode="json", exclude_unset=True, exclude_none=True))
        if not response.is_success:
            try:
                error_body = response.json()
            except Exception:
                error_body = response.text
            msg = f"{response.status_code}: {error_body}"
            raise httpx.HTTPStatusError(
                msg, request=response.request, response=response
            )
        return ChatSessionCreate.model_validate(response.json())


    def projects_sessions_retrieve(self, id: str, project_slug: str) -> ChatSession:
        """
        Chat session management. POST
        /api/knowbase_chat/projects/{slug}/sessions/ — create session GET
        /api/knowbase_chat/projects/{slug}/sessions/ — list sessions GET
        /api/knowbase_chat/projects/{slug}/sessions/{id}/ — retrieve session
        """
        url = f"/api/knowbase_chat/projects/{project_slug}/sessions/{id}/"
        response = self._client.get(url)
        if not response.is_success:
            try:
                error_body = response.json()
            except Exception:
                error_body = response.text
            msg = f"{response.status_code}: {error_body}"
            raise httpx.HTTPStatusError(
                msg, request=response.request, response=response
            )
        return ChatSession.model_validate(response.json())


    def sessions_messages_list(
        self,
        session_id: str,
        ordering: str | None = None,
        page: int | None = None,
        page_size: int | None = None,
        search: str | None = None,
    ) -> list[PaginatedChatMessageList]:
        """
        Chat message storage (used internally by knowbase_server chat module).
        POST /api/knowbase_chat/sessions/{session_id}/messages/ — save message
        GET /api/knowbase_chat/sessions/{session_id}/messages/ — list messages
        """
        url = f"/api/knowbase_chat/sessions/{session_id}/messages/"
        _params = {
            k: v for k, v in {
                "ordering": ordering,
                "page": page,
                "page_size": page_size,
                "search": search,
            }.items() if v is not None
        }
        response = self._client.get(url, params=_params)
        if not response.is_success:
            try:
                error_body = response.json()
            except Exception:
                error_body = response.text
            msg = f"{response.status_code}: {error_body}"
            raise httpx.HTTPStatusError(
                msg, request=response.request, response=response
            )
        return PaginatedChatMessageList.model_validate(response.json())


    def sessions_messages_create(
        self,
        session_id: str,
        data: ChatMessageCreateRequest,
    ) -> ChatMessageCreate:
        """
        Chat message storage (used internally by knowbase_server chat module).
        POST /api/knowbase_chat/sessions/{session_id}/messages/ — save message
        GET /api/knowbase_chat/sessions/{session_id}/messages/ — list messages
        """
        url = f"/api/knowbase_chat/sessions/{session_id}/messages/"
        response = self._client.post(url, json=data.model_dump(mode="json", exclude_unset=True, exclude_none=True))
        if not response.is_success:
            try:
                error_body = response.json()
            except Exception:
                error_body = response.text
            msg = f"{response.status_code}: {error_body}"
            raise httpx.HTTPStatusError(
                msg, request=response.request, response=response
            )
        return ChatMessageCreate.model_validate(response.json())


