import google.auth
from google.cloud import compute_v1, storage, functions_v1, pubsub_v1
from google.api_core.exceptions import GoogleAPIError
from googleapiclient import discovery

class GCPConnector:
    """
    Handles the connection to Google Cloud Platform (GCP).

    This class provides a singleton pattern for GCP credentials and clients,
    ensuring consistent authentication and client management.
    """
    _credentials = None
    _project_id = None

    @classmethod
    def get_credentials(cls):
        """
        Gets the GCP credentials.

        If credentials do not already exist, it attempts to load them.
        """
        if cls._credentials is None:
            try:
                print("Attempting to load GCP credentials...")
                cls._credentials, cls._project_id = google.auth.default()
                print(f"GCP credentials loaded successfully for project: {cls._project_id}")
            except Exception as e:
                print(f"Error loading GCP credentials: {e}")
                print("Please ensure you have authenticated to GCP (e.g., `gcloud auth application-default login`).")
                raise
        return cls._credentials

    @classmethod
    def get_project_id(cls):
        """
        Gets the GCP Project ID from the current credentials.
        """
        if cls._project_id is None:
            cls.get_credentials() # Ensure credentials are loaded
        return cls._project_id

    @classmethod
    def get_compute_client(cls):
        cls.get_credentials()
        return compute_v1.InstancesClient(credentials=cls._credentials)

    @classmethod
    def get_storage_client(cls):
        cls.get_credentials()
        return storage.Client(credentials=cls._credentials, project=cls._project_id)

    @classmethod
    def get_sql_client(cls):
        cls.get_credentials()
        return discovery.build('sqladmin', 'v1beta4', credentials=cls._credentials)

    @classmethod
    def get_functions_client(cls):
        cls.get_credentials()
        return functions_v1.CloudFunctionsServiceClient(credentials=cls._credentials)

    @classmethod
    def get_pubsub_client(cls):
        cls.get_credentials()
        return pubsub_v1.PublisherClient(credentials=cls._credentials)

    # Add other GCP service clients as needed

    @classmethod
    def login(cls):
        """
        Attempts to log in to GCP by verifying credentials.
        """
        try:
            cls.get_credentials()
            print(f"Successfully verified GCP credentials for project: {cls._project_id}")
            return True
        except GoogleAPIError as e:
            print(f"GCP API error during login: {e}")
            print("Please ensure you have authenticated to GCP (e.g., `gcloud auth application-default login`).")
            return False
        except Exception as e:
            print(f"An unexpected error occurred during GCP login: {e}")
            return False
