"""
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 InferredSearch, LeadSearchInput, LiteralSearch, ProductSearchEngine

logger = logging.getLogger(__name__)

engine = ProductSearchEngine()

@tool(args_schema=LeadSearchInput)
async def lead_search_tool(
    literal: LiteralSearch,
    inferred: InferredSearch,
    magento_ref_code: str | None = None,
    reasoning: str | None = None,
) -> str:
    """
    Tim kiem san pham CANIFA theo Dual-Lane Architecture.
    """
    req = LeadSearchInput(
        literal=literal,
        inferred=inferred,
        magento_ref_code=magento_ref_code,
        reasoning=reasoning,
    )

    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)})
