from ..base_azure_agent import BaseAzureAgent
from ..azure_connector import AzureConnector
from azure.mgmt.storage.models import StorageAccountCreateParameters, Sku, Kind
from msrestazure.azure_exceptions import CloudError

class StorageAgent(BaseAzureAgent):
    """
    An agent specialized in handling Azure Storage Account tasks.
    """

    def execute(self, command: str, **kwargs):
        """
        Executes a given command related to Azure Storage Accounts.
        """
        if command == 'list_storage_accounts':
            return self._list_storage_accounts(**kwargs)
        elif command == 'smart_create_storage_account':
            account_name = kwargs.get('account_name', '')
            resource_group = kwargs.get('resource_group', '')
            print(f"You are about to smart-create an Azure Storage Account '{account_name}' in resource group '{resource_group}'.")
            confirm = input("Are you sure you want to proceed? (yes/no): ")
            if confirm.lower() == 'yes':
                return self._smart_create_storage_account(**kwargs)
            else:
                return {"status": "cancelled", "message": "Smart Create Storage Account command cancelled by user."}
        elif command == 'delete_storage_account':
            account_name = kwargs.get('account_name', '')
            resource_group = kwargs.get('resource_group', '')
            print(f"WARNING: You are about to delete Azure Storage Account '{account_name}' in resource group '{resource_group}'. This action is irreversible.")
            confirm = input("Are you sure you want to proceed? (yes/no): ")
            if confirm.lower() == 'yes':
                return self._delete_storage_account(**kwargs)
            else:
                return {"status": "cancelled", "message": "Delete Storage Account command cancelled by user."}
        else:
            raise NotImplementedError(f"Command '{command}' is not supported by StorageAgent.")

    def _list_storage_accounts(self, subscription_id: str, resource_group: str):
        """
        Lists all Storage Accounts in a specified resource group.
        """
        print(f"StorageAgent: Listing Storage Accounts in subscription '{subscription_id}', resource group '{resource_group}'...")
        try:
            storage_client = AzureConnector.get_storage_client()
            accounts = storage_client.storage_accounts.list_by_resource_group(resource_group)
            account_details = []
            for account in accounts:
                account_details.append({
                    'name': account.name,
                    'id': account.id,
                    'location': account.location,
                    'sku': account.sku.name,
                    'kind': account.kind
                })
            return {"status": "success", "storage_accounts": account_details}
        except CloudError as e:
            print(f"Azure Error listing Storage Accounts: {e.message}")
            return {"status": "error", "message": e.message}
        except Exception as e:
            print(f"Error listing Storage Accounts: {e}")
            return {"status": "error", "message": str(e)}

    def _smart_create_storage_account(self, subscription_id: str, resource_group: str, location: str, account_name: str, 
                                       sku_name: str = 'Standard_LRS', kind: str = 'StorageV2'):
        """
        Creates an Azure Storage Account with sensible defaults.
        """
        print(f"StorageAgent: Smart creating Storage Account '{account_name}' in resource group '{resource_group}', location '{location}'...")
        try:
            storage_client = AzureConnector.get_storage_client()

            # Check if resource group exists, if not, create it (simplified, usually done by a separate agent)
            # For now, assume resource group exists or will be handled externally.

            storage_account_params = StorageAccountCreateParameters(
                sku=Sku(name=sku_name),
                kind=Kind(kind),
                location=location,
                enable_https_traffic_only=True, # Best practice
                minimum_tls_version='TLS1_2', # Best practice
                allow_blob_public_access=False, # Best practice
                network_rule_set={'default_action': 'Deny'} # Best practice
            )

            async_creation = storage_client.storage_accounts.begin_create(resource_group, account_name, storage_account_params)
            account = async_creation.wait()

            return {"status": "success", "message": f"Storage Account '{account_name}' created successfully.", "account_id": account.id}
        except CloudError as e:
            print(f"Azure Error creating Storage Account: {e.message}")
            return {"status": "error", "message": e.message}
        except Exception as e:
            print(f"Error creating Storage Account: {e}")
            return {"status": "error", "message": str(e)}

    def _delete_storage_account(self, subscription_id: str, resource_group: str, account_name: str):
        """
        Deletes a specified Storage Account.
        """
        print(f"StorageAgent: Deleting Storage Account '{account_name}' in resource group '{resource_group}'...")
        try:
            storage_client = AzureConnector.get_storage_client()
            async_deletion = storage_client.storage_accounts.begin_delete(resource_group, account_name)
            async_deletion.wait()
            return {"status": "success", "message": f"Storage Account '{account_name}' deleted successfully."}
        except CloudError as e:
            print(f"Azure Error deleting Storage Account: {e.message}")
            return {"status": "error", "message": e.message}
        except Exception as e:
            print(f"Error deleting Storage Account: {e}")
            return {"status": "error", "message": str(e)}
