from ..base_gcp_agent import BaseGCPAgent
from ..gcp_connector import GCPConnector
from googleapiclient import discovery

class SQLAgent(BaseGCPAgent):
    """
    An agent specialized in handling GCP Cloud SQL tasks.
    """

    def execute(self, command: str, **kwargs):
        """
        Executes a given command related to Cloud SQL.
        """
        if command == 'smart_create_instance':
            instance_name = kwargs.get('instance_name', '')
            print(f"You are about to smart-create a Cloud SQL instance '{instance_name}'.")
            confirm = input("Are you sure you want to proceed? (yes/no): ")
            if confirm.lower() == 'yes':
                return self._smart_create_instance(**kwargs)
            else:
                return {"status": "cancelled", "message": "Smart Create Cloud SQL instance command cancelled by user."}
        else:
            raise NotImplementedError(f"Command '{command}' is not supported by SQLAgent.")

    def _smart_create_instance(self, project_id: str, region: str, instance_name: str, database_version: str = 'POSTGRES_14', tier: str = 'db-f1-micro'):
        """
        Creates a Cloud SQL instance with sensible defaults.
        """
        print(f"SQLAgent: Smart creating instance '{instance_name}' in project '{project_id}', region '{region}'...")
        try:
            client = GCPConnector.get_sql_client()

            # Configure settings
            settings = {
                "tier": tier,
                "backupConfiguration": {"enabled": True},
                "ipConfiguration": {"ipv4Enabled": True, "requireSsl": True}
            }

            # Create the instance
            instance = {
                "name": instance_name,
                "databaseVersion": database_version,
                "region": region,
                "settings": settings
            }

            request = client.instances().insert(
                project=project_id,
                body=instance
            )

            operation = request.execute()
            # The operation object itself is a Future, so we can wait on it.
            operation_result = operation.result() # This blocks until the operation completes

            return {"status": "success", "message": f"Cloud SQL instance '{instance_name}' created successfully.", "instance_name": operation_result.name}
        except Exception as e:
            print(f"Error creating Cloud SQL instance: {e}")
            return {"status": "error", "message": str(e)}
