import logging
import uuid

import httpx

from config import CONV_SUPABASE_KEY, CONV_SUPABASE_URL

logger = logging.getLogger(__name__)

_http_client: httpx.AsyncClient | None = None


def _get_http_client() -> httpx.AsyncClient:
    global _http_client
    if _http_client is None:
        _http_client = httpx.AsyncClient()
    return _http_client


async def close_http_client() -> None:
    global _http_client
    if _http_client is not None:
        await _http_client.aclose()
        _http_client = None


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

            file_content = base64.b64decode(base64_data)

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

            # 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}

            client = _get_http_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
