import logging
import uuid

import httpx

from config import CONV_SUPABASE_KEY, CONV_SUPABASE_URL

logger = logging.getLogger(__name__)


class ImageStorageService:
    """
    Service quản lý việc upload ảnh lên Supabase Storage.
    Sử dụng httpx để gọi REST API của Supabase.
    """

    def __init__(self, bucket_name: str = "chat-images"):
        self.url = CONV_SUPABASE_URL
        self.key = CONV_SUPABASE_KEY
        self.bucket_name = bucket_name

        if not self.url or not self.key:
            logger.error("Supabase URL or Key is missing in configuration")

    async def upload_base64(self, base64_data: str, filename: str | None = None) -> str | None:
        """
        Upload ảnh từ base64 string lên Supabase Storage.
        Returns: Public URL của ảnh hoặc None nếu lỗi.
        """
        try:
            if not self.url or not self.key:
                return None

            # Xử lý base64 string (loại bỏ prefix nếu có)
            if "," in base64_data:
                header, base64_data = base64_data.split(",", 1)
                content_type = header.split(";")[0].split(":")[1]
            else:
                content_type = "image/jpeg"

            import base64
            import piexif
            from PIL import Image
            import io

            file_content = base64.b64decode(base64_data)

            if not filename:
                ext = content_type.split("/")[-1]
                if ext == "jpeg":
                    ext = "jpg"
                filename = f"{uuid.uuid4()}.{ext}"

            # Strip EXIF metadata to preserve privacy
            if content_type in ["image/jpeg", "image/jpg", "image/tiff"]:
                try:
                    img = Image.open(io.BytesIO(file_content))
                    if "exif" in img.info:
                        output_io = io.BytesIO()
                        # Use PIL to save without EXIF data
                        img.save(output_io, format=img.format, exif=b"")
                        file_content = output_io.getvalue()
                        logger.info(f"Stripped EXIF metadata from {filename}")
                except Exception as e:
                    logger.warning(f"Could not strip EXIF data from {filename}: {e}")

            # Supabase Storage REST API: /storage/v1/object/{bucket}/{path}
            upload_url = f"{self.url}/storage/v1/object/{self.bucket_name}/{filename}"

            headers = {"Authorization": f"Bearer {self.key}", "apikey": self.key, "Content-Type": content_type}

            async with httpx.AsyncClient() as client:
                response = await client.post(upload_url, content=file_content, headers=headers)

                if response.status_code == 200:
                    # Lấy public URL (Giả định bucket là public)
                    public_url = f"{self.url}/storage/v1/object/public/{self.bucket_name}/{filename}"
                    logger.info(f"✅ Uploaded image successfully: {public_url}")
                    return public_url
                logger.error(f"❌ Failed to upload image: {response.status_code} - {response.text}")
                return None

        except Exception as e:
            logger.error(f"Error uploading image to Supabase: {e}")
            return None
