from abc import ABC, abstractmethod
from typing import TYPE_CHECKING, List, cast

from lightning_sdk.api import TeamspaceApi
from lightning_sdk.utils.logging import TrackCallsABCMeta

if TYPE_CHECKING:
    from lightning_sdk.organization import Organization
    from lightning_sdk.teamspace import Teamspace


class Owner(ABC, metaclass=TrackCallsABCMeta):
    """Represents an owner of teamspaces and studios."""

    def __init__(self) -> None:
        self._teamspace_api = TeamspaceApi()

    @property
    @abstractmethod
    def name(self) -> str:
        """The owner's name."""

    @property
    @abstractmethod
    def id(self) -> str:
        """The owner's ID."""

    @abstractmethod
    def create_teamspace(self, name: str) -> "Teamspace":
        """Creates a new teamspace.

        Args:
            name: The display name for the new teamspace.

        Returns:
            Teamspace: The newly created teamspace.
        """

    @property
    def teamspaces(self) -> List["Teamspace"]:
        """All teamspaces owned by this owner.

        Returns:
            List[Teamspace]: Every teamspace belonging to this user or organisation.
        """
        from lightning_sdk.teamspace import Teamspace
        from lightning_sdk.user import User

        if isinstance(self, User):
            user = self
            org = None
        else:
            user = None
            org = cast("Organization", self)

        _teamspaces = self._teamspace_api.list_teamspaces(owner_id=self.id, name=None) or []
        return [Teamspace(name=t.name, user=user, org=org) for t in _teamspaces]

    def __eq__(self, o: object) -> bool:
        """Checks for equality with provided object."""
        return isinstance(o, Owner) and type(o) is type(self) and self.id == o.id and self.name == o.name

    def __str__(self) -> str:
        """Returns reader friendly representation."""
        return repr(self)
