import logging

import requests
from django.conf import settings

logger = logging.getLogger(__name__)

FASTCORK_BASE_URL = "https://fastcork.com"
FASTCORK_SEARCH_URL = f"{FASTCORK_BASE_URL}/v1/search"


def search_wines(query: str) -> list[dict]:
    api_key = settings.FASTCORK_API_KEY
    if not api_key:
        logger.warning("FASTCORK_API_KEY is not configured")
        return []

    headers = {
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json",
    }
    payload = {"query": query, "lang": "en"}

    try:
        response = requests.post(
            FASTCORK_SEARCH_URL, headers=headers, json=payload, timeout=10
        )
    except requests.RequestException:
        logger.exception("FastCork search request failed")
        return []

    if response.status_code != 200:
        logger.warning(
            "Bad response from FastCork search",
            extra={"status_code": response.status_code},
        )
        return []

    data = response.json()
    if not data.get("success"):
        logger.warning(
            "FastCork search returned success=false",
            extra={"response": data},
        )
        return []

    return data.get("results", {}).get("query", [])
