from typing import Optional

from truefoundry.deploy.lib.clients.servicefoundry_client import (
    ServiceFoundryServiceClient,
)
from truefoundry.deploy.lib.model.entity import Workspace


def list_workspaces(
    cluster_name: Optional[str] = None,
    client: Optional[ServiceFoundryServiceClient] = None,
):
    client = client or ServiceFoundryServiceClient()
    workspaces = client.list_workspaces(cluster_id=cluster_name)
    return workspaces


def get_workspace_by_fqn(
    workspace_fqn: str,
    client: Optional[ServiceFoundryServiceClient] = None,
) -> Workspace:
    client = client or ServiceFoundryServiceClient()
    workspaces = client.get_workspace_by_fqn(workspace_fqn=workspace_fqn)
    if len(workspaces) == 0:
        raise ValueError(f"Workspace with FQN {workspace_fqn!r} does not exist.")
    workspace = workspaces[0]
    return workspace


def delete_workspace(
    workspace_fqn: str,
    client: Optional[ServiceFoundryServiceClient] = None,
) -> Workspace:
    client = client or ServiceFoundryServiceClient()
    workspace = client.get_id_from_fqn(fqn=workspace_fqn, fqn_type="workspace")
    deleted_workspace = client.delete_workspace(workspace_id=workspace["workspaceId"])
    return deleted_workspace
