"""
Test Recall Flow — 5 câu conversation liên tiếp.
Kiểm tra chatbot có nhớ SP đã giới thiệu khi user tham chiếu lại.
"""
import asyncio
import io
import json
import sys

sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')

from langchain_core.messages import AIMessage, HumanMessage

from agent.lead_stage_agent.graph import get_lead_stage_agent

CONVERSATION = [
    "tìm áo ngọ nghiêng",
    "có quần nào phối với áo đó không",
    "cho cái áo người lớn cơ mà",
    "mình thích cái polo, giá bao nhiêu vậy",
    "còn size nào cho mình cao 1m70 65kg",
]

async def main():
    agent = get_lead_stage_agent()
    history = []
    insight_json = None

    for i, query in enumerate(CONVERSATION):
        print(f"\n{'='*60}")
        print(f"👤 Turn {i+1}: {query}")
        print(f"{'='*60}")

        result = await agent.chat(
            user_message=query,
            user_insight=json.dumps(insight_json, ensure_ascii=False) if insight_json else None,
            history=history,
        )

        # Update history
        history.append(HumanMessage(content=query))
        history.append(AIMessage(content=result["response"]))

        # Update insight
        if result.get("updated_insight"):
            insight_json = result["updated_insight"]

        # Print response
        resp = result["response"]
        print(f"\n🤖 Bot: {resp[:400]}")

        # Print products shown
        products = result.get("products", [])
        if products:
            print(f"\n📦 Products shown ({len(products)}):")
            for p in products[:5]:
                print(f"   - [{p.get('sku', p.get('sku_code', '?'))}] {p.get('name', '?')}")

        # Print insight highlights
        if insight_json:
            latest = insight_json.get("LATEST_PRODUCT_INTEREST", "")
            summary = insight_json.get("SUMMARY_HISTORY", "")
            print(f"\n💾 LATEST_PRODUCT_INTEREST: {latest[:200]}")
            print(f"💾 SUMMARY_HISTORY: {summary[:200]}")

        # Pipeline diagnostics
        for diag in result.get("pipeline", []):
            if diag.get("step") == "classifier":
                print(f"\n🔧 Classifier: {diag.get('content', '')[:200]}")
                if diag.get("tool_calls"):
                    for tc in diag["tool_calls"]:
                        print(f"   Tool: {tc['name']} | Args: {json.dumps(tc.get('args', {}), ensure_ascii=False)[:200]}")
                else:
                    print(f"   ⚡ Early Exit (no tool call)")

    print(f"\n\n{'='*60}")
    print("✅ TEST COMPLETE — Check if Turn 3 recalls Ngọ Nghiêng instead of searching")
    print(f"{'='*60}")

if __name__ == "__main__":
    asyncio.run(main())
