from ..base_gcp_agent import BaseGCPAgent
from ..gcp_connector import GCPConnector
from google.cloud import container_v1

class GKEAgent(BaseGCPAgent):
    """
    An agent specialized in handling GCP Google Kubernetes Engine (GKE) tasks.
    """

    def execute(self, command: str, **kwargs):
        """
        Executes a given command related to GKE.
        """
        if command == 'smart_create_cluster':
            cluster_name = kwargs.get('cluster_name', '')
            print(f"You are about to smart-create a GKE cluster '{cluster_name}'.")
            confirm = input("This will create a new GKE cluster. Are you sure you want to proceed? (yes/no): ")
            if confirm.lower() == 'yes':
                return self._smart_create_cluster(**kwargs)
            else:
                return {"status": "cancelled", "message": "Smart Create GKE cluster command cancelled by user."}
        else:
            raise NotImplementedError(f"Command '{command}' is not supported by GKEAgent.")

    def _smart_create_cluster(self, project_id: str, region: str, cluster_name: str, machine_type: str = 'e2-medium', num_nodes: int = 1, anthos_enabled: bool = False):
        """
        Creates a GKE cluster with sensible defaults, optionally enabling Anthos features.
        """
        print(f"GKEAgent: Smart creating cluster '{cluster_name}' in project '{project_id}', region '{region}'...")
        try:
            client = container_v1.ClusterManagerClient(credentials=GCPConnector.get_credentials())

            # Configure node pool
            node_config = container_v1.NodeConfig()
            node_config.machine_type = machine_type
            node_config.oauth_scopes = [
                'https://www.googleapis.com/auth/devstorage.read_only',
                'https://www.googleapis.com/auth/logging.write',
                'https://www.googleapis.com/auth/monitoring',
                'https://www.googleapis.com/auth/servicecontrol',
                'https://www.googleapis.com/auth/service.management.readonly',
                'https://www.googleapis.com/auth/trace.append',
                'https://www.googleapis.com/auth/cloud-platform', # Required for Anthos
            ]

            node_pool = container_v1.NodePool()
            node_pool.name = f'{cluster_name}-node-pool'
            node_pool.initial_node_count = num_nodes
            node_pool.config = node_config

            # Configure cluster
            cluster = container_v1.Cluster()
            cluster.name = cluster_name
            cluster.initial_node_count = num_nodes
            cluster.node_pools = [node_pool]
            cluster.location = region # Use region for regional clusters

            # Enable Workload Identity (best practice and often required for Anthos)
            cluster.workload_identity_config.identity_namespace = f'{project_id}.svc.id.goog'

            if anthos_enabled:
                print(f"Enabling Anthos features for cluster '{cluster_name}'...")
                # Enable Anthos Service Mesh (ASM) - simplified, actual setup is more involved
                # This typically involves enabling APIs and installing components via `gcloud` or `asmcli`
                # For API creation, we can enable the Anthos Service Mesh API
                # Note: Direct API for enabling ASM during cluster creation is not straightforward.
                # This will primarily ensure the cluster is ready for Anthos registration.
                cluster.addons_config.cloud_run_config.disabled = False # Example Anthos-related addon
                cluster.addons_config.istio_config.disabled = False # Example Anthos-related addon
                cluster.addons_config.istio_config.auth = container_v1.IstioConfig.Auth.AUTH_MUTUAL_TLS
                cluster.enable_k8s_beta_apis = True # Often needed for Anthos components
                cluster.resource_labels = {'mesh_id': f'projects/{project_id}/locations/{region}/meshes/default'} # Example label

            request = container_v1.CreateClusterRequest(
                parent=f"projects/{project_id}/locations/{region}",
                cluster=cluster,
            )

            operation = client.create_cluster(request=request)
            print("Waiting for GKE cluster creation to complete... (this may take several minutes)")
            operation.result() # This blocks until the operation completes

            message = f"GKE cluster '{cluster_name}' created successfully."
            if anthos_enabled:
                message += " Anthos features enabled (cluster ready for Anthos registration)."

            return {"status": "success", "message": message, "cluster_name": cluster_name}
        except Exception as e:
            print(f"Error creating GKE cluster: {e}")
            return {"status": "error", "message": str(e)}
