import os
import uuid
from pathlib import Path
from typing import Optional
from fastapi import UploadFile, HTTPException
from PIL import Image
from app.config import UPLOAD_PRODUCTS_DIR, UPLOAD_CATEGORIES_DIR

ALLOWED_EXTENSIONS = {".jpg", ".jpeg", ".png", ".webp", ".gif"}
MAX_FILE_SIZE = 10 * 1024 * 1024  # 10 MB

def save_uploaded_image(file: UploadFile, folder: str = "products", max_width: int = 1400) -> str:
    ext = Path(file.filename).suffix.lower()
    if ext not in ALLOWED_EXTENSIONS:
        raise HTTPException(
            status_code=400,
            detail=f"Unsupported file format '{ext}'. Allowed formats: JPG, JPEG, PNG, WEBP."
        )

    target_dir = UPLOAD_PRODUCTS_DIR if folder == "products" else UPLOAD_CATEGORIES_DIR
    target_dir.mkdir(parents=True, exist_ok=True)

    unique_filename = f"{uuid.uuid4().hex[:12]}{ext}"
    target_path = target_dir / unique_filename

    try:
        # Open and process image
        image = Image.open(file.file)
        
        # Convert RGBA/P to RGB if saving as JPEG
        if image.mode in ("RGBA", "P") and ext in (".jpg", ".jpeg"):
            image = image.convert("RGB")
            
        # Resize if overly large
        if image.width > max_width:
            aspect_ratio = image.height / image.width
            new_height = int(max_width * aspect_ratio)
            image = image.resize((max_width, new_height), Image.Resampling.LANCZOS)

        image.save(target_path, optimize=True, quality=88)
        return f"/uploads/{folder}/{unique_filename}"
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Image upload processing failed: {str(e)}")


def remove_uploaded_file(file_url: str):
    if not file_url or not file_url.startswith("/uploads/"):
        return
    try:
        rel_path = file_url.lstrip("/")
        # Path relative to backend directory
        full_path = Path(__file__).resolve().parent.parent / rel_path
        if full_path.exists() and full_path.is_file():
            os.remove(full_path)
    except Exception:
        pass
