"""
PowerPath Transport Layer

HTTP transport for PowerPath API communication.
Uses body-based pagination (totalCount, pageNumber, pageCount in response body).
"""

from __future__ import annotations

from dataclasses import dataclass
from typing import TYPE_CHECKING, Any

from timeback_common import BaseTransport, PowerPathPaths, TokenManager

if TYPE_CHECKING:
    import httpx


@dataclass
class PaginatedResponse:
    """Normalized paginated response."""

    data: dict[str, Any]
    has_more: bool
    total: int | None = None


class Transport(BaseTransport):
    """HTTP transport layer for PowerPath API communication."""

    def __init__(
        self,
        *,
        base_url: str,
        token_manager: TokenManager | None = None,
        paths: PowerPathPaths,
        timeout: float = 30.0,
        http_client: httpx.AsyncClient | None = None,
        no_auth: bool = False,
    ) -> None:
        super().__init__(
            base_url=base_url,
            timeout=timeout,
            token_manager=token_manager,
            http_client=http_client,
            no_auth=no_auth,
        )
        self.paths = paths

    async def request_paginated(
        self,
        path: str,
        *,
        params: dict[str, Any] | None = None,
    ) -> PaginatedResponse:
        """
        Make a paginated request using PowerPath's body pagination format.

        PowerPath list endpoints return pagination metadata in the response body:
        - totalCount: Total items across all pages
        - pageCount: Total number of pages
        - pageNumber: Current page (1-indexed)
        - offset: Current offset
        - limit: Items per page
        """
        body = await self.get(path, params=params)

        total_count: int | None = None
        raw_total = body.get("totalCount")
        if isinstance(raw_total, int):
            total_count = raw_total

        page_count: int | None = None
        raw_page_count = body.get("pageCount")
        if isinstance(raw_page_count, int):
            page_count = raw_page_count

        page_number: int | None = None
        raw_page_number = body.get("pageNumber")
        if isinstance(raw_page_number, int):
            page_number = raw_page_number

        has_more = False
        if page_count is not None and page_number is not None:
            has_more = page_number < page_count

        return PaginatedResponse(data=body, has_more=has_more, total=total_count)


__all__ = ["PaginatedResponse", "Transport"]
