"""
Stock Helpers - Shared stock fetching logic.
Được dùng bởi cả `data_retrieval_tool` và `check_is_stock` tool.
Gọi qua internal API /api/stock/check để tận dụng logic expand SKU.
"""

import logging
from typing import Any

import httpx

from config import INTERNAL_STOCK_API

logger = logging.getLogger(__name__)

# ⚡ OPTIMIZED: Reduce timeout to prevent blocking
DEFAULT_TIMEOUT_SEC = 3.0  # Reduced from 15s to 3s for faster failure


async def fetch_stock_for_skus(
    skus: list[str],
    timeout_sec: float = DEFAULT_TIMEOUT_SEC,
) -> dict[str, dict[str, Any]]:
    """
    Fetch stock info for a list of SKUs via internal API.
    Supports base codes, product_color_code, and full SKUs.
    API will automatically expand short codes to full SKUs.

    Args:
        skus: List of SKU codes (any format: base, color, or full)
        timeout_sec: HTTP timeout in seconds (default 15)

    Returns:
        Dict mapping SKU -> stock data from API response.
        Example: {"6ST25W005-SE091-L": {"qty": 10, "is_in_stock": true, ...}}
    """
    if not skus:
        return {}

    # Deduplicate while preserving order
    seen = set()
    unique_skus: list[str] = []
    for sku in skus:
        if sku and sku not in seen:
            seen.add(sku)
            unique_skus.append(sku)

    if not unique_skus:
        return {}

    stock_map: dict[str, dict[str, Any]] = {}

    try:
        # ⚡ OPTIMIZED: Use connection pooling and HTTP/2 for faster requests
        async with httpx.AsyncClient(
            timeout=timeout_sec,
            http2=True,  # Enable HTTP/2 for better performance
            limits=httpx.Limits(max_keepalive_connections=10, max_connections=20),
        ) as client:
            # Call internal API with POST
            payload = {
                "codes": ",".join(unique_skus),
                "truncate": True,
                "max_skus": 200,
            }
            resp = await client.post(INTERNAL_STOCK_API, json=payload)
            resp.raise_for_status()

            data = resp.json()

            # Parse response from /api/stock/check
            # Format: {"stock_responses": [{"code": 200, "result": [...]}]}
            stock_responses = data.get("stock_responses", [])
            for stock_resp in stock_responses:
                results = stock_resp.get("result", [])
                for item in results:
                    sku_key = item.get("sku")
                    if sku_key:
                        stock_map[sku_key] = {
                            "is_in_stock": item.get("is_in_stock", False),
                            "qty": item.get("qty", 0),
                        }

        logger.info(f"📦 [STOCK] Fetched stock for {len(stock_map)} SKUs (input: {len(unique_skus)})")
        return stock_map

    except httpx.RequestError as exc:
        logger.error(f"Network error fetching stock: {exc}")
        return {}
    except httpx.HTTPStatusError as exc:
        logger.error(f"HTTP error {exc.response.status_code} fetching stock: {exc}")
        return {}
    except Exception as exc:
        logger.error(f"Unexpected error fetching stock: {exc}")
        return {}
