import requests
from azure.storage.blob import BlobServiceClient, BlobClient, ContainerClient, BlobSasPermissions, generate_blob_sas, ContentSettings
import time
from datetime import datetime, timedelta, timezone
from dotenv import load_dotenv
import os

load_dotenv()


AZURE_STORAGE_CONTAINER_NAME = os.getenv('AZURE_STORAGE_CONTAINER_NAME')
AZURE_STORAGE_CONNECTION_STRING = os.getenv('AZURE_STORAGE_CONNECTION_STRING')
AZURE_STORAGE_ACCOUNT_NAME = os.getenv('AZURE_STORAGE_ACCOUNT_NAME')
ACCOUNT_KEY = os.getenv('ACCOUNT_KEY')


def upload_pdf_to_api_and_get_url(pdf_file_path):
    url = 'https://hw-api.dmlabs.in/user/upload-pic'
    try:
        # Open the file in binary mode
        with open(pdf_file_path, 'rb') as pdf_file:
            # Create a multipart/form-data payload
            files = {'file': pdf_file}
            # Send POST request
            response = requests.post(url, files=files)

            # Raise an exception if the request failed
            response.raise_for_status()

            # Parse JSON response
            response_data = response.json()

            # Extract the 'url' field from the response
            file_url = response_data.get('url')
            if file_url:
                return file_url
            else:
                return "URL not found in the response."
    except requests.exceptions.RequestException as e:
        # Handle request-related errors
        return f"An error occurred: {e}"





def upload_to_azure_with_signed_url(file_path, blob_name, content_type="audio/mpeg"):
    try:
        # Initialize the BlobServiceClient using the connection string
        blob_service_client = BlobServiceClient.from_connection_string(AZURE_STORAGE_CONNECTION_STRING)
        container_client = blob_service_client.get_container_client(AZURE_STORAGE_CONTAINER_NAME)

        # Open the audio file for reading in binary mode
        with open(file_path, "rb") as data:
            # Upload the file and set the content type for inline display
            container_client.upload_blob(
                name=blob_name,
                data=data,
                overwrite=True,
                max_concurrency=5,  # Number of threads to use for uploading
                content_settings=ContentSettings(content_type=content_type)  # Set content type for inline display
            )

        # Generate a SAS token for the blob
        sas_token = generate_blob_sas(
            account_name=AZURE_STORAGE_ACCOUNT_NAME,
            container_name=AZURE_STORAGE_CONTAINER_NAME,
            blob_name=blob_name,
            account_key=ACCOUNT_KEY,
            permission=BlobSasPermissions(read=True),  # Read-only permission
            expiry = datetime.now(tz=timezone.utc) + timedelta(hours=1)  # SAS token expiry time
        )

        # Construct the signed URL
        signed_blob_url = f"https://{blob_service_client.account_name}.blob.core.windows.net/{AZURE_STORAGE_CONTAINER_NAME}/{blob_name}?{sas_token}"

        # Verify if the blob exists
        blob_client = container_client.get_blob_client(blob_name)
        if blob_client.exists():
            return signed_blob_url
        else:
            return None

    except Exception as e:
        print(f"Error uploading audio file to Azure: {e}")
        return None

 
def upload_img_to_azure_with_signed_url(file_path, blob_name):
    try:
        # Initialize the BlobServiceClient using the connection string
        blob_service_client = BlobServiceClient.from_connection_string(AZURE_STORAGE_CONNECTION_STRING)
        container_client = blob_service_client.get_container_client(AZURE_STORAGE_CONTAINER_NAME)

        # Open the PNG file for reading in binary mode
        with open(file_path, "rb") as data:
            # Upload the file and set the content type to 'image/png' for inline display
            container_client.upload_blob(
                name=blob_name,
                data=data,
                overwrite=True,
                max_concurrency=5,
                content_settings=ContentSettings(content_type="image/png")  # Set content type
            )

        # Generate a SAS token for the blob (allowing read access and inline display)
        sas_token = generate_blob_sas(
            account_name=AZURE_STORAGE_ACCOUNT_NAME,
            container_name=AZURE_STORAGE_CONTAINER_NAME,
            blob_name=blob_name,
            account_key=ACCOUNT_KEY,
            permission=BlobSasPermissions(read=True),
            expiry=datetime.utcnow() + timedelta(hours=1)  # SAS token expiry
        )

        # Construct the signed URL
        signed_blob_url = f"https://{blob_service_client.account_name}.blob.core.windows.net/{AZURE_STORAGE_CONTAINER_NAME}/{blob_name}?{sas_token}"

        # Return the signed URL for inline display in the browser
        return signed_blob_url

    except Exception as e:
        print(f"Error uploading file to Azure: {e}")
        return None   
