"""
Canifa Product API — Proxy GraphQL search từ canifa.com.
Dùng để lấy ảnh, giá, stock trực tiếp từ Canifa thay vì StarRocks.
"""
import logging
from fastapi import APIRouter, Query
import httpx

logger = logging.getLogger(__name__)

router = APIRouter(prefix="/api/canifa", tags=["canifa-proxy"])

CANIFA_GRAPHQL = "https://canifa.com/graphql"
CANIFA_MEDIA_BASE = "https://canifa.com/media/catalog/product"


async def search_canifa_products(keyword: str, page_size: int = 12) -> list[dict]:
    """
    Search products từ Canifa GraphQL API.
    Returns list of products with: name, sku, image, price, final_price, discount, stock, url.
    """
    query = '{ products(search: "%s", pageSize: %d) { items total_count } }' % (
        keyword.replace('"', '\\"'),
        page_size,
    )

    try:
        async with httpx.AsyncClient(timeout=10) as client:
            resp = await client.post(
                CANIFA_GRAPHQL,
                json={"query": query},
                headers={"Content-Type": "application/json", "Store": "default"},
            )
            resp.raise_for_status()
            data = resp.json()

        items = data.get("data", {}).get("products", {}).get("items", [])
        total = data.get("data", {}).get("products", {}).get("total_count", 0)

        # Transform to clean format
        products = []
        for item in items:
            # Skip invisible/disabled products
            if item.get("status") != 1:
                continue

            # Build image URL
            image_path = item.get("small_image") or item.get("image") or ""
            image_url = f"{CANIFA_MEDIA_BASE}{image_path}" if image_path else ""

            # Build product URL
            url_key = item.get("url_key") or item.get("slug") or ""
            product_url = f"https://canifa.com/{url_key}.html" if url_key else ""

            # Stock info
            stock = item.get("stock", {})

            product = {
                "name": (item.get("name") or "").replace("�", ""),
                "sku": item.get("sku", ""),
                "image": image_url,
                "url": product_url,
                "price": item.get("price", 0),
                "final_price": item.get("final_price", 0),
                "original_price": item.get("original_price", 0),
                "discount_percent": item.get("discount_percent", 0),
                "is_in_stock": stock.get("is_in_stock", False),
                "qty": stock.get("qty", 0),
            }
            products.append(product)

        logger.info(f"🛍️ Canifa search '{keyword}': {len(products)}/{total} products")
        return products

    except Exception as e:
        logger.error(f"❌ Canifa GraphQL error: {e}")
        return []


@router.get("/search")
async def canifa_search(
    q: str = Query(..., description="Search keyword"),
    limit: int = Query(12, ge=1, le=50),
):
    """Search sản phẩm trực tiếp từ canifa.com GraphQL."""
    products = await search_canifa_products(q, page_size=limit)
    return {
        "status": "success",
        "keyword": q,
        "count": len(products),
        "products": products,
    }
