"""
Lead Search Tool - LangChain @tool cho AI goi.
Lớp này giờ chỉ đóng vai trò Wrapper mỏng (Thin Wrapper).
Toàn bộ logic phức tạp đã được đưa sang ProductSearchEngine.
"""

import json
import logging
from langchain_core.tools import tool
from .product_search_engine import ProductSearchEngine, LeadSearchInput

logger = logging.getLogger(__name__)

engine = ProductSearchEngine()

@tool(args_schema=LeadSearchInput)
async def lead_search_tool(
    keywords: list[str] | None = None,
    tags: list[str] | None = None,
    product_line_vn: list[str] | None = None,
    gender_by_product: str | None = None,
    age_by_product: str | None = None,
    master_color: str | None = None,
    price_min: int | None = None,
    price_max: int | None = None,
    discount_min: int | None = None,
    discount_max: int | None = None,
    discovery_mode: str | None = None,
    size: str | None = None,
    magento_ref_code: str | None = None,
    reasoning: str | None = None,
) -> str:
    """
    Tim kiem san pham CANIFA theo tags va tu khoa. Toi uu hoa de chay cuc nhanh bang BITMAP index.
    """
    req = LeadSearchInput(
        keywords=keywords or [],
        tags=tags or [],
        product_line_vn=product_line_vn or [],
        gender_by_product=gender_by_product,
        age_by_product=age_by_product,
        master_color=master_color,
        price_min=price_min,
        price_max=price_max,
        discount_min=discount_min,
        discount_max=discount_max,
        discovery_mode=discovery_mode,
        size=size,
        magento_ref_code=magento_ref_code,
    )

    try:
        # Gọi engine để xử lý logic dual-query / cascade
        result_dict = await engine.search(req, reasoning=reasoning)
        return json.dumps(result_dict, ensure_ascii=False, default=str)
    except Exception as e:
        logger.error("Lead search tool error: %s", e, exc_info=True)
        return json.dumps({"status": "error", "message": str(e)})
