from PIL import Image
from uuid import uuid4
import os

# Get project root (where src folder is located)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
UPLOAD_DIR = os.path.join(BASE_DIR, "uploads")

def save_file(file, folder: str, validate: bool = True) -> str:
    target_folder = os.path.join(UPLOAD_DIR, folder)
    os.makedirs(target_folder, exist_ok=True)

    extension = os.path.splitext(file.filename)[1]
    unique_name = f"{uuid4().hex}{extension}"
    file_path = os.path.join(target_folder, unique_name)

    with open(file_path, "wb") as f:
        f.write(file.file.read())

    if validate:
        validate_image(file_path)

    # Return relative path for DB (e.g. uploads/users/abc.png)
    return os.path.relpath(file_path, BASE_DIR)

def validate_image(path: str):
    try:
        with Image.open(path) as img:
            img.verify()
    except Exception as e:
        print(f"Invalid image: {e}")
        try:
            os.remove(path)
        except Exception as delete_error:
            print(f"Failed to delete invalid image: {delete_error}")
        raise e
