import logging
from datetime import datetime, timedelta

from azure.storage.blob import BlobSasPermissions, BlobServiceClient, generate_blob_sas

from app.core.config import settings

logger = logging.getLogger(__name__)

class AzureStorageService:
    def __init__(self):
        try:
            self.blob_service_client = BlobServiceClient.from_connection_string(settings.AZURE_STORAGE_CONNECTION_STRING)
            self.container_name = "knowledge-base"
        except Exception as e:
            logger.error(f"Failed to initialize Azure Blob Storage client: {e}", exc_info=True)
            self.blob_service_client = None

    def _ensure_container(self):
        if not self.blob_service_client:
            return False
        try:
            container_client = self.blob_service_client.get_container_client(self.container_name)
            if not container_client.exists():
                self.blob_service_client.create_container(self.container_name)
            return True
        except Exception as e:
            logger.error(f"Error ensuring Azure container exists: {e}", exc_info=True)
            return False

    def upload_file(self, tenant_id: str, file_name: str, content_bytes: bytes) -> bool:
        """
        Uploads a file to Azure Blob Storage under a tenant-specific path.
        """
        if not self._ensure_container():
            return False
        
        try:
            # Path: tenant_id/files/file_name
            blob_path = f"tenant/{tenant_id}/files/{file_name}"
            blob_client = self.blob_service_client.get_blob_client(container=self.container_name, blob=blob_path)
            
            blob_client.upload_blob(content_bytes, overwrite=True)
            logger.info(f"Successfully uploaded {file_name} to Azure for tenant {tenant_id}")
            return True
        except Exception as e:
            logger.error(f"Failed to upload file to Azure: {e}", exc_info=True)
            return False

    def delete_file(self, tenant_id: str, file_name: str) -> bool:
        """
        Deletes a file from Azure Blob Storage.
        """
        if not self.blob_service_client:
            return False

        try:
            blob_path = f"tenant/{tenant_id}/files/{file_name}"
            blob_client = self.blob_service_client.get_blob_client(container=self.container_name, blob=blob_path)
            
            if blob_client.exists():
                blob_client.delete_blob()
                logger.info(f"Successfully deleted {file_name} from Azure for tenant {tenant_id}")
            return True
        except Exception as e:
            logger.error(f"Failed to delete file from Azure: {e}", exc_info=True)
            return False

    def download_url(self, tenant_id: str, file_name: str, hours: int = 24) -> str:
        """A temporary read-only link to a stored file, or '' if it cannot be made.

        The container is private, so visitors cannot be handed a plain blob URL.
        A SAS token grants read access to this one blob and nothing else, and
        stops working once it expires.
        """
        if not self.blob_service_client:
            return ""
        try:
            blob_path = f"tenant/{tenant_id}/files/{file_name}"
            blob_client = self.blob_service_client.get_blob_client(
                container=self.container_name, blob=blob_path)
            if not blob_client.exists():
                logger.warning(f"No stored file at {blob_path}")
                return ""

            token = generate_blob_sas(
                account_name=self.blob_service_client.account_name,
                container_name=self.container_name,
                blob_name=blob_path,
                account_key=self.blob_service_client.credential.account_key,
                permission=BlobSasPermissions(read=True),
                expiry=datetime.utcnow() + timedelta(hours=hours),
            )
            return f"{blob_client.url}?{token}"
        except Exception as e:
            logger.error(f"Could not build a download link for {file_name}: {e}", exc_info=True)
            return ""


# Singleton instance
storage_service = AzureStorageService()
