"""Clusters resource."""

from __future__ import annotations

import builtins

from .._client import AplikuClient
from .._models import App, Cluster, ClusterCreate, ServiceLogsResponse

_list = builtins.list


class ClustersResource:
    def __init__(self, client: AplikuClient) -> None:
        self._client = client

    def _base(self, team: str) -> str:
        return f"/api/team/{team}/clusters"

    def list(self, team: str) -> _list[Cluster]:
        """List clusters for a team."""
        data = self._client.get(self._base(team))
        return [Cluster.model_validate(item) for item in data]

    def get(self, team: str, cluster_id: int) -> Cluster:
        """Get a single cluster."""
        data = self._client.get(f"{self._base(team)}/{cluster_id}")
        return Cluster.model_validate(data)

    def create(self, team: str, name: str) -> Cluster:
        """Create a cluster."""
        body = ClusterCreate(name=name)
        data = self._client.post(f"{self._base(team)}/create", json=body.model_dump())
        return Cluster.model_validate(data)

    def delete(self, team: str, cluster_id: int) -> None:
        """Delete a cluster."""
        self._client._request("POST", f"{self._base(team)}/{cluster_id}/delete")

    def service_logs(
        self, team: str, cluster_id: int, service: str, tail: int = 100
    ) -> _list[tuple[App, ServiceLogsResponse]]:
        """Get service logs for all apps in a cluster.

        Lists apps filtered by cluster_id, then fetches service_logs per app.
        Returns a list of (app, logs) tuples.
        """
        from .apps import AppsResource

        apps_resource = AppsResource(self._client)
        results: _list[tuple[App, ServiceLogsResponse]] = []
        for app in apps_resource.list(team):
            if app.cluster_id == cluster_id:
                logs = apps_resource.service_logs(team, app.id, service, tail)
                results.append((app, logs))
        return results
