import os
import platform

import globus_sdk
from fastmcp.exceptions import ClientError

DEFAULT_CLIENT_ID = "ee05bbfa-2a1a-4659-95df-ed8946e3aae6"


def get_client_creds():
    client_id = os.getenv("GLOBUS_CLIENT_ID")
    client_secret = os.getenv("GLOBUS_CLIENT_SECRET")
    return client_id, client_secret


def get_globus_app() -> globus_sdk.GlobusApp:
    # Check if running in test mode
    if os.getenv("MCP_TEST_MODE") == "1":
        # Return a mock app for testing without authentication
        return MockGlobusApp()

    app_name = platform.node()
    client_id, client_secret = get_client_creds()

    if client_id and client_secret:
        return globus_sdk.ClientApp(
            app_name=app_name, client_id=client_id, client_secret=client_secret
        )

    elif client_secret:
        raise ClientError(
            "Both GLOBUS_CLIENT_ID and GLOBUS_CLIENT_SECRET must be set to"
            " use a client identity."
        )

    else:
        client_id = client_id or DEFAULT_CLIENT_ID
        config = globus_sdk.GlobusAppConfig(login_flow_manager="local-server")
        return globus_sdk.UserApp(app_name=app_name, client_id=client_id, config=config)


class MockGlobusApp:
    """Mock GlobusApp for testing without authentication."""

    def __init__(self):
        self.client_id = "test-client-id"
        self.scopes = []

    def get_authorizer(self, scopes):
        return MockAuthorizer()

    def login(self):
        pass


class MockAuthorizer:
    """Mock authorizer for testing."""

    def get_authorization_header(self):
        return "Bearer test-token"

    def get_token(self):
        return "test-token"


class MockTransferClient:
    """Mock TransferClient for testing."""

    def __init__(self, app=None):
        self.app = app

    def add_app_scope(self, scope):
        pass

    def endpoint_search(self, filter_fulltext=None, filter_scope=None, limit=None):
        """Mock endpoint search response."""
        class MockResponse:
            def __init__(self):
                self.data = {"DATA": []}

        return MockResponse()

    def submit_transfer(self, data):
        """Mock submit transfer response."""
        class MockResponse:
            def __init__(self):
                self.data = {"task_id": "test-task-id"}

        return MockResponse()

    def task_event_list(self, task_id, limit=None):
        """Mock task event list response."""
        class MockResponse:
            def __init__(self):
                self.data = {"DATA": []}

        return MockResponse()

    def operation_ls(self, collection_id, path, limit=None):
        """Mock operation ls response."""
        class MockResponse:
            def __init__(self):
                self.data = {"DATA": []}

        return MockResponse()