"""Async Planka API client for connection testing and board/card listing."""

from __future__ import annotations

import logging
from typing import Any

import aiohttp

_LOGGER = logging.getLogger(__name__)


class PlankaClient:
    """Async client for the Planka REST API."""

    def __init__(
        self,
        session: aiohttp.ClientSession,
        url: str,
        api_key: str,
    ) -> None:
        self._session = session
        self._url = url.rstrip("/")
        self._api_key = api_key

    @property
    def url(self) -> str:
        return self._url

    @property
    def _headers(self) -> dict[str, str]:
        return {"Authorization": f"Bearer {self._api_key}"}

    async def ping(self) -> bool:
        """Check connectivity via GET /api/boards."""
        try:
            async with self._session.get(
                f"{self._url}/api/boards",
                headers=self._headers,
            ) as response:
                return response.status == 200
        except aiohttp.ClientError:
            return False

    async def get_boards(self) -> list[dict[str, Any]]:
        """List all boards accessible to the authenticated user."""
        try:
            async with self._session.get(
                f"{self._url}/api/boards",
                headers=self._headers,
            ) as response:
                if response.status != 200:
                    _LOGGER.warning("Failed to fetch boards: HTTP %s", response.status)
                    return []
                data = await response.json()
                # Planka returns {"items": [...]} or a list directly
                if isinstance(data, dict):
                    return data.get("items", data.get("boards", []))
                return data if isinstance(data, list) else []
        except aiohttp.ClientError as err:
            _LOGGER.warning("Failed to fetch boards: %s", err)
            return []

    async def get_board_lists(self, board_id: str) -> list[dict[str, Any]]:
        """Fetch lists for a board."""
        try:
            async with self._session.get(
                f"{self._url}/api/boards/{board_id}",
                headers=self._headers,
            ) as response:
                if response.status != 200:
                    _LOGGER.warning("Failed to fetch board %s: HTTP %s", board_id, response.status)
                    return []
                data = await response.json()
                included = data.get("included", {})
                return included.get("lists", [])
        except aiohttp.ClientError as err:
            _LOGGER.warning("Failed to fetch board %s: %s", board_id, err)
            return []

    async def get_board_cards(self, board_id: str, limit: int = 20) -> list[dict[str, Any]]:
        """Fetch cards for a board."""
        try:
            async with self._session.get(
                f"{self._url}/api/boards/{board_id}",
                headers=self._headers,
            ) as response:
                if response.status != 200:
                    _LOGGER.warning("Failed to fetch board %s: HTTP %s", board_id, response.status)
                    return []
                data = await response.json()
                included = data.get("included", {})
                cards = included.get("cards", [])
                return cards[:limit]
        except aiohttp.ClientError as err:
            _LOGGER.warning("Failed to fetch board %s cards: %s", board_id, err)
            return []


class PlankaApiError(Exception):
    """Raised when a Planka API call fails."""
