"""
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,
    user_insight: dict | None = None,  # Từ graph state
    event_context: dict | None = None,  # Từ graph state (event_hard.get_event_context)
) -> str:
    """
    Tim kiem san pham CANIFA theo Dual-Lane Architecture.
    """
    req = LeadSearchInput(
        literal=literal,
        inferred=inferred,
        magento_ref_code=magento_ref_code,
        reasoning=reasoning,
        event_context=event_context,  # Truyền vào model
    )

    try:
        # Gọi engine — event_context đã có trong req
        result_dict = await engine.search(req, reasoning=reasoning, user_insight=user_insight)
        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)})
