# project/utils/woocommerce_service.py
from woocommerce import API
from django.conf import settings
import logging
import time

logger = logging.getLogger(__name__)


# -------------------------------------------------
# 1. Base WooCommerce Client
# -------------------------------------------------
def get_woocommerce_client():
    """Return a fresh WooCommerce API client instance."""
    return API(
        url=settings.WOOCOMMERCE_URL.rstrip("/"),
        consumer_key=settings.WOOCOMMERCE_CONSUMER_KEY,
        consumer_secret=settings.WOOCOMMERCE_CONSUMER_SECRET,
        version="wc/v3",
        timeout=30,
        verify_ssl=True,
    )


# Expose a default global client for quick use in admin actions, etc.
woo_api = get_woocommerce_client()


# -------------------------------------------------
# 2. Utility: Update stock for a variant
# -------------------------------------------------
def update_variant_stock(variant_or_id, in_stock=True, quantity=None):
    """
    Update WooCommerce stock information for a given variation.

    Args:
        variant_or_id: BouquetVariant instance OR Woo variation ID (int)
        in_stock: bool - whether the variant should be marked as in stock
        quantity: int | None - optional stock quantity to set
    """
    # Resolve Woo variation ID
    if isinstance(variant_or_id, int):
        variation_id = variant_or_id
    else:
        variation_id = getattr(variant_or_id, "woo_variation_id", None)

    if not variation_id:
        logger.warning("update_variant_stock: No variation id provided.")
        return False

    client = get_woocommerce_client()
    payload = {"manage_stock": True, "stock_status": "instock" if in_stock else "outofstock"}
    if quantity is not None:
        payload["stock_quantity"] = int(quantity)

    # Retry logic with exponential backoff
    max_attempts = 3
    for attempt in range(1, max_attempts + 1):
        try:
            resp = client.put(f"products/variations/{variation_id}", payload)
            status = getattr(resp, "status_code", None)
            logger.info("✅ Updated Woo variation %s (%s) [HTTP %s]", variation_id, payload, status)
            return True
        except Exception as e:
            logger.exception("⚠️ Attempt %d failed for %s: %s", attempt, variation_id, e)
            time.sleep(2 ** attempt)

    logger.error("❌ Failed to update Woo variation %s after %d attempts", variation_id, max_attempts)
    return False


# -------------------------------------------------
# 3. Utility: Fetch Woo product variants easily
# -------------------------------------------------
def fetch_product_variants(product_id):
    """
    Retrieve all WooCommerce variations for a given product ID.
    Returns a list of dicts or [] on failure.
    """
    try:
        client = get_woocommerce_client()
        response = client.get(f"products/{product_id}/variations")
        data = response.json()
        if isinstance(data, list):
            return data
        logger.warning("Unexpected Woo response for product %s: %s", product_id, data)
        return []
    except Exception as e:
        logger.exception("Failed to fetch product variants for %s: %s", product_id, e)
        return []


# -------------------------------------------------
# 4. Utility: Simple health check
# -------------------------------------------------
def test_connection():
    """Quickly test if WooCommerce API credentials work."""
    try:
        client = get_woocommerce_client()
        resp = client.get("products", params={"per_page": 1})
        return resp.status_code == 200
    except Exception as e:
        logger.error("WooCommerce connection test failed: %s", e)
        return False