import os
import uuid
from fastapi import UploadFile, HTTPException
from pathlib import Path


class FileUploadHandler:
    """Handle file uploads and generate accessible URLs"""
    
    UPLOAD_DIR = "uploads"
    ALLOWED_TYPES = ["image/jpeg", "image/png", "image/jpg", "application/pdf"]
    
    def __init__(self):
        # Create uploads directory if it doesn't exist
        Path(self.UPLOAD_DIR).mkdir(exist_ok=True)
    
    async def save_uploaded_file(self, file: UploadFile, host_url: str) -> str:
        """
        Save uploaded file and return accessible URL
        
        Args:
            file: FastAPI UploadFile object
            host_url: Base URL of the application (e.g., http://localhost:8000)
            
        Returns:
            str: Full URL to access the uploaded file
        """
        # Validate file type
        if file.content_type not in self.ALLOWED_TYPES:
            raise HTTPException(
                status_code=400,
                detail=f"Unsupported file type: {file.content_type}. Allowed types: {', '.join(self.ALLOWED_TYPES)}"
            )
        
        # Validate file size (limit to 10MB)
        if file.size and file.size > 10 * 1024 * 1024:
            raise HTTPException(
                status_code=400,
                detail="File too large. Maximum size is 10MB."
            )
        
        # Generate unique filename
        file_extension = self._get_file_extension(file.filename)
        unique_filename = f"{uuid.uuid4()}{file_extension}"
        file_path = os.path.join(self.UPLOAD_DIR, unique_filename)
        
        try:
            # Save file using built-in file operations
            content = await file.read()
            
            # Validate content is not empty
            if not content:
                raise HTTPException(
                    status_code=400,
                    detail="Uploaded file is empty"
                )
            
            with open(file_path, 'wb') as f:
                f.write(content)
            
            # Verify file was saved successfully
            if not os.path.exists(file_path):
                raise HTTPException(
                    status_code=500,
                    detail="File was not saved successfully"
                )
            
            # Return accessible URL - ensure proper path format
            # Since static files are mounted at /uploads, we only need the filename
            # Convert Windows path separators to forward slashes for URL
            file_url = f"{host_url.rstrip('/')}/uploads/{unique_filename}"
            
            print(f"DEBUG: File saved to: {file_path}")
            print(f"DEBUG: Generated URL: {file_url}")
            
            return file_url
            
        except HTTPException:
            # Clean up file if something went wrong
            if os.path.exists(file_path):
                os.remove(file_path)
            raise
        except Exception as e:
            # Clean up file if something went wrong
            if os.path.exists(file_path):
                os.remove(file_path)
            raise HTTPException(
                status_code=500,
                detail=f"Failed to save file: {str(e)}"
            )
    
    def _get_file_extension(self, filename: str) -> str:
        """Get file extension from filename"""
        if not filename:
            return ".tmp"
        
        extension = os.path.splitext(filename)[1]
        return extension if extension else ".tmp"


# Global instance
file_upload_handler = FileUploadHandler()