import os
from PIL import Image
from io import BytesIO
from django.core.files.base import ContentFile

import os
from PIL import Image

def compress_and_resize_inplace(image_field, max_width=1200, quality=75):
    """
    Surgical In-Place Compressor:
    1. Seedha physical file ko overwrite karta hai.
    2. Django ke Storage System (save method) ko bypass karta hai suffixes rokne ke liye.
    """
    if not image_field or not hasattr(image_field, 'path'):
        return

    try:
        physical_path = image_field.path
        
        # 🛡️ SAFETY CHECK: Agar file 200KB se choti hai, toh optimize ho chuki hai
        if os.path.exists(physical_path) and os.path.getsize(physical_path) < 200000:
            return

        # Image load karein
        img = Image.open(physical_path)
        
        # RGB Conversion (PNG/GIF compatibility)
        if img.mode in ("RGBA", "P"):
            img = img.convert("RGB")

        # Resize logic
        if img.width > max_width:
            output_size = (max_width, int((max_width / img.width) * img.height))
            img = img.resize(output_size, Image.Resampling.LANCZOS)

        # 🚩 THE MAGIC: Physically overwrite the EXACT SAME file on disk
        # Isse database path wahi rahega aur naya suffix nahi banega
        img.save(physical_path, format='JPEG', quality=quality, optimize=True)
        
        print(f"SUCCESS: In-place optimization done for {os.path.basename(physical_path)}")

    except Exception as e:
        print(f"CRITICAL ERROR in Image Utility: {e}")