import boto3
import os
from botocore.exceptions import ClientError
from fastapi import HTTPException, status
from typing import Optional
from dotenv import load_dotenv
import uuid
from datetime import datetime

load_dotenv()

# AWS S3 Configuration
AWS_ACCESS_KEY_ID = os.getenv("AWS_ACCESS_KEY_ID")
AWS_SECRET_ACCESS_KEY = os.getenv("AWS_SECRET_ACCESS_KEY")
AWS_REGION = os.getenv("AWS_REGION", "us-east-1")
S3_BUCKET_NAME = os.getenv("S3_BUCKET_NAME")

# Initialize S3 client
s3_client = boto3.client(
    's3',
    aws_access_key_id=AWS_ACCESS_KEY_ID,
    aws_secret_access_key=AWS_SECRET_ACCESS_KEY,
    region_name=AWS_REGION
)


def upload_file_to_s3(file_content: bytes, file_name: str, folder: Optional[str] = None) -> str:
    """
    Upload a file to S3 and return the public URL
    
    Args:
        file_content: The file content as bytes
        file_name: The original file name
        folder: Optional folder path in S3 (e.g., "images", "uploads")
    
    Returns:
        The public URL of the uploaded file
    """
    if not AWS_ACCESS_KEY_ID or not AWS_SECRET_ACCESS_KEY or not S3_BUCKET_NAME:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="AWS S3 configuration is missing. Please set AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, and S3_BUCKET_NAME in environment variables."
        )
    
    try:
        # Generate unique file name with timestamp and UUID
        file_extension = os.path.splitext(file_name)[1]
        unique_file_name = f"{uuid.uuid4()}_{int(datetime.now().timestamp())}{file_extension}"
        
        # Construct S3 key (path)
        if folder:
            s3_key = f"{folder}/{unique_file_name}"
        else:
            s3_key = unique_file_name
        
        # Upload file to S3
        s3_client.put_object(
            Bucket=S3_BUCKET_NAME,
            Key=s3_key,
            Body=file_content,
            ContentType=get_content_type(file_extension)
        )
        
        # Generate public URL
        file_url = f"https://{S3_BUCKET_NAME}.s3.{AWS_REGION}.amazonaws.com/{s3_key}"
        
        return file_url
    
    except ClientError as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Failed to upload file to S3: {str(e)}"
        )
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Unexpected error while uploading file: {str(e)}"
        )


def delete_file_from_s3(file_url: str) -> bool:
    """
    Delete a file from S3 using its URL
    
    Args:
        file_url: The public URL of the file to delete
    
    Returns:
        True if deletion was successful, False otherwise
    """
    if not AWS_ACCESS_KEY_ID or not AWS_SECRET_ACCESS_KEY or not S3_BUCKET_NAME:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="AWS S3 configuration is missing. Please set AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, and S3_BUCKET_NAME in environment variables."
        )
    
    try:
        # Extract S3 key from URL
        # URL format: https://bucket-name.s3.region.amazonaws.com/key
        if f"{S3_BUCKET_NAME}.s3.{AWS_REGION}.amazonaws.com" in file_url:
            s3_key = file_url.split(f"{S3_BUCKET_NAME}.s3.{AWS_REGION}.amazonaws.com/")[1]
        elif S3_BUCKET_NAME in file_url:
            # Handle different URL formats
            parts = file_url.split(f"{S3_BUCKET_NAME}/")
            if len(parts) > 1:
                s3_key = parts[1]
            else:
                # If it's just the key, use it directly
                s3_key = file_url
        else:
            # Assume the URL is just the key
            s3_key = file_url
        
        # Delete file from S3
        s3_client.delete_object(
            Bucket=S3_BUCKET_NAME,
            Key=s3_key
        )
        
        return True
    
    except ClientError as e:
        if e.response['Error']['Code'] == 'NoSuchKey':
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="File not found in S3"
            )
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Failed to delete file from S3: {str(e)}"
        )
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Unexpected error while deleting file: {str(e)}"
        )


def get_content_type(file_extension: str) -> str:
    """
    Get content type based on file extension
    
    Args:
        file_extension: File extension (e.g., ".jpg", ".png")
    
    Returns:
        Content type string
    """
    content_types = {
        ".jpg": "image/jpeg",
        ".jpeg": "image/jpeg",
        ".png": "image/png",
        ".gif": "image/gif",
        ".webp": "image/webp",
        ".svg": "image/svg+xml",
        ".pdf": "application/pdf",
        ".txt": "text/plain",
        ".json": "application/json",
    }
    
    return content_types.get(file_extension.lower(), "application/octet-stream")

