"""
SKU Search API — FastAPI route cho tra cứu sản phẩm theo mã SKU.
Gọi SkuSearchGraph 2-Agent (Planner → Tool → Responder).
"""

import logging

from fastapi import APIRouter
from fastapi.responses import JSONResponse
from pydantic import BaseModel

from agent.sku_search_agent.sku_search_graph import get_sku_search_agent
from common.starrocks_connection import get_db_connection

logger = logging.getLogger(__name__)
router = APIRouter(prefix="/api/sku-search", tags=["SKU Search"])


class SkuChatRequest(BaseModel):
    query: str
    # history support later if needed


@router.post("/chat", summary="Chat with SKU Search Agent")
async def sku_chat(req: SkuChatRequest):
    """
    Gửi câu hỏi cho SKU Search Agent.
    Agent sẽ tự extract mã SKU → gọi tool → format câu trả lời.
    """
    query = req.query.strip()
    if not query:
        return JSONResponse(status_code=400, content={"status": "error", "message": "Query trống"})

    try:
        agent = get_sku_search_agent()
        result = await agent.chat(query)

        return {
            "status": "success",
            "response": result["response"],
            "elapsed_ms": result["elapsed_ms"],
            "agent_path": result["agent_path"],
            "tool_calls": result["tool_calls"],
            "pipeline": result.get("pipeline", []),
        }
    except Exception as e:
        logger.error(f"❌ SKU Search error: {e}", exc_info=True)
        return JSONResponse(status_code=500, content={"status": "error", "message": str(e)})


@router.get("/lookup/{sku}", summary="Quick SKU lookup (no agent, direct query)")
async def sku_lookup(sku: str):
    """
    Tra cứu nhanh theo mã SKU — không qua Agent, query thẳng DB.
    Dùng cho API integration hoặc lookup nhanh.
    """
    sku = sku.strip()
    if not sku or len(sku) < 3:
        return JSONResponse(status_code=400, content={"status": "error", "message": "SKU phải >= 3 ký tự"})

    try:
        db = get_db_connection()
        code = sku.upper()
        internal_ref, _ = code.split("-", 1) if "-" in code else (code, None)
        loose_pattern = "%" + "%".join(code.replace("-", "")) + "%"

        sql = """
        WITH resolved_family AS (
            SELECT DISTINCT internal_ref_code
            FROM test_db.magento_product_dimension_with_text_embedding
            WHERE UPPER(internal_ref_code) = %s
               OR UPPER(magento_ref_code) = %s
               OR UPPER(product_color_code) = %s
               OR UPPER(product_color_code) LIKE %s
               OR REPLACE(UPPER(magento_ref_code), '-', '') LIKE %s
        )
        SELECT magento_ref_code, product_color_code, product_name, master_color,
               product_color_name, sale_price, original_price,
               product_image_url_thumbnail, product_web_url, size_scale,
               gender_by_product, product_line_vn, quantity_sold
        FROM test_db.magento_product_dimension_with_text_embedding
        WHERE internal_ref_code IN (SELECT internal_ref_code FROM resolved_family)
        """
        params = (internal_ref, code, code, f"{internal_ref}-%", loose_pattern)
        products = await db.execute_query_async(sql, params=params)

        return {
            "status": "success",
            "sku": sku,
            "count": len(products),
            "products": products,
        }
    except Exception as e:
        logger.error(f"❌ SKU Lookup error: {e}", exc_info=True)
        return JSONResponse(status_code=500, content={"status": "error", "message": str(e)})
