from pathlib import Path
from PIL import Image
from django.core.management.base import BaseCommand


class Command(BaseCommand):
    help = "Convert farm_produce.jfif to farm_produce.jpg for better compatibility"

    def handle(self, *args, **options):
        static_img_dir = Path(__file__).resolve().parent.parent.parent.parent / "static" / "img"
        jfif_path = static_img_dir / "farm_produce.jfif"
        jpg_path = static_img_dir / "farm_produce.jpg"

        if not jfif_path.exists():
            self.stdout.write(self.style.ERROR(f"JFIF file not found at: {jfif_path}"))
            return

        self.stdout.write(f"Converting {jfif_path} to JPG...")

        try:
            # Open JFIF and convert to JPG
            img = Image.open(jfif_path)
            
            # Convert CMYK or other formats to RGB if needed
            if img.mode in ("CMYK", "LA", "P"):
                rgb_img = Image.new("RGB", img.size, (255, 255, 255))
                rgb_img.paste(img)
                img = rgb_img
            elif img.mode == "RGBA":
                rgb_img = Image.new("RGB", img.size, (255, 255, 255))
                rgb_img.paste(img, mask=img.split()[3] if img.mode == "RGBA" else None)
                img = rgb_img
            
            # Save as JPG with high quality
            img.save(jpg_path, "JPEG", quality=95, optimize=True)
            self.stdout.write(self.style.SUCCESS(f"✓ Successfully converted to: {jpg_path}"))
        except Exception as exc:
            self.stdout.write(self.style.ERROR(f"✗ Conversion failed: {exc}"))
