import os
from typing import Dict, List, Optional

import instalabel.client
from instalabel.client.models.task_enum import TaskEnum
from instalabel.client.rest import ApiException
from instalabel.config import INSTALABEL_CLIENT_CONFIGURATION as configuration
from instalabel.core.project import Project
from instalabel.core.workspace import Workspace


class InstaLabel:
    def __init__(self):
        self.configuration = configuration

    def login(self, username: str, password: str) -> bool:
        """Login to InstaLabel and get access token"""
        with instalabel.client.ApiClient(configuration) as api_client:
            api_instance = instalabel.client.AuthApi(api_client)
            try:
                api_response = (
                    api_instance.login_for_access_token_api_v1_auth_token_post(
                        username=username, password=password
                    )
                )
                configuration.access_token = api_response.access_token
                os.environ["ACCESS_TOKEN"] = api_response.access_token
                return True
            except ApiException as e:
                print(f"Exception when logging in: {e}")
                return False

    def create_workspace(
        self, workspace_name: str, description: str = None
    ) -> Optional[Workspace]:
        """Create a new workspace"""
        return Workspace.create(workspace_name, description)

    def get_workspaces(self) -> List[Workspace]:
        """Get all workspaces"""
        with instalabel.client.ApiClient(configuration) as api_client:
            api_instance = instalabel.client.WorkspacesApi(api_client)
            try:
                api_response = api_instance.read_workspaces_api_v1_workspaces_get()
                return [Workspace(workspace) for workspace in api_response]
            except Exception as e:
                print(f"Exception when getting workspaces: {e}")
                return []

    def get_workspace(self, workspace_id: str) -> Optional[Workspace]:
        """Get a specific workspace by ID"""
        with instalabel.client.ApiClient(configuration) as api_client:
            api_instance = instalabel.client.WorkspacesApi(api_client)
            try:
                api_response = (
                    api_instance.read_workspace_api_v1_workspaces_workspace_id_get(
                        workspace_id
                    )
                )
                return Workspace(api_response)
            except Exception as e:
                print(f"Exception when getting workspace: {e}")
                return None

    def __str__(self):
        return "InstaLabel Client"
