import uuid

import boto3
from loguru import logger

from app.config import (
    R2_ACCESS_KEY_ID,
    R2_BUCKET_NAME,
    R2_ENDPOINT,
    R2_PUBLIC_URL,
    R2_SECRET_ACCESS_KEY,
)

_s3_client = None


def _get_client():
    global _s3_client
    if _s3_client is None:
        _s3_client = boto3.client(
            "s3",
            endpoint_url=R2_ENDPOINT,
            aws_access_key_id=R2_ACCESS_KEY_ID,
            aws_secret_access_key=R2_SECRET_ACCESS_KEY,
            region_name="auto",
        )
    return _s3_client


def upload_bytes(data: bytes, key: str, content_type: str = "image/png") -> str:
    """Upload bytes to R2. Returns the public URL."""
    client = _get_client()
    client.put_object(
        Bucket=R2_BUCKET_NAME,
        Key=key,
        Body=data,
        ContentType=content_type,
    )
    url = f"{R2_PUBLIC_URL}/{key}"
    logger.info(f"R2_UPLOADED: key={key} size={len(data)} url={url}")
    return url


def generate_key(session_id: str, folder: str, extension: str = ".png") -> str:
    """Generate an unguessable R2 key for a media file."""
    unique_id = uuid.uuid4().hex[:12]
    return f"media/{session_id}/{folder}/{unique_id}{extension}"


def upload_json(data: dict, key: str) -> str:
    """Upload JSON data to R2. Returns public URL."""
    import json
    json_bytes = json.dumps(data, ensure_ascii=False, indent=2).encode("utf-8")
    return upload_bytes(json_bytes, key, "application/json")
