import logging

import requests
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured

from .capture_errors import capture_and_log

logger = logging.getLogger(__name__)


def get_direct_upload_url(user_id=None):
    """
    Generates a direct upload URL for Cloudflare Images.

    Args:
        user_id (str, optional): The user ID to associate with the upload.

    Returns:
        dict: A dictionary containing 'id' and 'uploadURL'.

    Raises:
        ImproperlyConfigured: If Cloudflare settings are missing.
        requests.RequestException: If the Cloudflare API request fails.
    """
    account_id = getattr(settings, "CLOUDFLARE_IMAGES_ACCOUNT_ID", None)
    api_token = getattr(settings, "CLOUDFLARE_IMAGES_API_TOKEN", None)

    if not account_id or not api_token:
        raise ImproperlyConfigured("CLOUDFLARE_IMAGES_ACCOUNT_ID and CLOUDFLARE_IMAGES_API_TOKEN must be set.")

    url = f"https://api.cloudflare.com/client/v4/accounts/{account_id}/images/v2/direct_upload"

    headers = {
        "Authorization": f"Bearer {api_token}",
    }

    data = {
        "requireSignedURLs": "false",
    }

    if user_id:
        data["metadata"] = f'{{"user_id": "{user_id}"}}'

    response = requests.post(url, headers=headers, data=data)
    response.raise_for_status()

    result = response.json()

    if not result.get("success"):
        error_msg = result.get("errors", [{"message": "Unknown error"}])[0].get("message")
        # Create error for capture
        e = requests.RequestException(f"Cloudflare Error: {error_msg}")
        capture_and_log(e, 'Cloudflare direct upload', source='service')
        raise e

    return result.get("result", {})
