"""
Shopping search service using SerpAPI Google Shopping.

Returns structured product data (title, price, image, link, rating, source)
that can be displayed as product cards in the Android app.
"""

import os

import httpx
from loguru import logger

SERPAPI_BASE = "https://serpapi.com/search.json"


async def shopping_search(query: str, num_results: int = 6) -> dict:
    """Search Google Shopping via SerpAPI for structured product results.

    Args:
        query: Product search query in English.
        num_results: Max number of products to return (default 6).

    Returns:
        dict with keys:
            - success (bool)
            - products (list[dict]): Each has title, price, image, link,
              source, rating, reviews, extracted_price.
            - summary (str): Short text summary for TTS.
            - error (str, optional): Error message on failure.
    """
    api_key = os.getenv("SERPAPI_API_KEY")
    if not api_key:
        logger.error("[Shopping] SERPAPI_API_KEY not set")
        return {"success": False, "error": "Shopping service not configured."}

    try:
        logger.info(f"[Shopping] Searching: {query!r}")

        params = {
            "engine": "google_shopping",
            "q": query,
            "api_key": api_key,
            "num": str(num_results),
            "hl": "en",
            "gl": "in",  # India locale for INR prices
        }

        async with httpx.AsyncClient(timeout=15.0) as client:
            resp = await client.get(SERPAPI_BASE, params=params)
            resp.raise_for_status()
            data = resp.json()

        raw_results = data.get("shopping_results", [])

        if not raw_results:
            logger.warning("[Shopping] No shopping results returned")
            return {
                "success": True,
                "products": [],
                "summary": "I could not find any products for that search.",
            }

        # Extract clean product objects
        products = []
        for item in raw_results[:num_results]:
            product = {
                "title": item.get("title", ""),
                "price": item.get("price", ""),
                "extracted_price": item.get("extracted_price", 0),
                "image": item.get("thumbnail", ""),
                "link": item.get("product_link", item.get("link", "")),
                "source": item.get("source", ""),
                "rating": item.get("rating"),
                "reviews": item.get("reviews"),
            }
            products.append(product)

        # Build a natural language summary for TTS (no URLs)
        summary_parts = []
        for i, p in enumerate(products[:4], 1):
            part = f"{p['title']} for {p['price']}"
            if p["source"]:
                part += f" from {p['source']}"
            if p.get("rating"):
                part += f", rated {p['rating']} stars"
            summary_parts.append(part)

        summary = "I found these products. " + ". ".join(summary_parts) + "."
        logger.info(f"[Shopping] Found {len(products)} products")

        return {
            "success": True,
            "products": products,
            "summary": summary,
        }

    except httpx.HTTPStatusError as e:
        logger.error(f"[Shopping] HTTP error: {e.response.status_code} - {e.response.text}")
        return {"success": False, "error": f"Shopping search failed: {e.response.status_code}"}
    except Exception as e:
        logger.error(f"[Shopping] Error: {e}")
        return {"success": False, "error": str(e)}
