"""
CANIFA Fashion Agent - Terminal Tester
Test agent với full flow: LLM + Tools + MongoDB Memory (No Postgres Checkpoint)
"""

import asyncio
import platform
import sys
from pathlib import Path

# Add parent dir to sys.path
sys.path.insert(0, str(Path(__file__).parent))

from langchain_core.messages import AIMessage, HumanMessage

# from langfuse import get_client, observe, propagate_attributes  # TẮT TẠM
# from langfuse.langchain import CallbackHandler  # TẮT TẠM
from agent.graph import build_graph
from agent.models import get_config


async def main():
    import logging

    # Tắt log rác của LangChain để terminal sạch sẽ
    logging.getLogger("langchain").setLevel(logging.ERROR)
    logging.getLogger("langgraph").setLevel(logging.ERROR)
    logging.getLogger("langfuse").setLevel(logging.ERROR)  # TẮT Langfuse logs

    # 📝 Enable INFO logs for Data Retrieval & Embedding tools (Timing & Debug)
    logging.basicConfig(level=logging.INFO, format="%(message)s")  # Bật INFO để thấy tool calls
    logging.getLogger("agent.tools.data_retrieval_tool").setLevel(logging.INFO)
    logging.getLogger("agent.tools.product_search_helpers").setLevel(logging.INFO)

    print("\n" + "=" * 50)
    print("🚀 CANIFA FASHION AGENT - TERMINAL TESTER (MEM V2)")
    print("=" * 50)

    try:
        # 1. Init Langfuse (Monitor tool) - TẮT TẠM ĐỂ TRÁNH RATE LIMIT
        # from langfuse import Langfuse
        # Langfuse()  # Initialize singleton

        # 2. Build Graph
        config = get_config()
        graph = build_graph(config)
        print("✅ System: Graph & MongoDB Memory Ready!")

    except Exception as e:
        print(f"❌ System Error: {e}")
        import traceback

        traceback.print_exc()
        return

    print("\n💬 CiCi: 'Em chào anh/chị ạ! Em là CiCi, stylist riêng của mình đây. Anh/chị cần em tư vấn gì không ạ?'")
    print("(Gõ 'q' để thoát, 'image' để giả lập gửi ảnh)")

    conversation_id = "test_terminal_session_v2"
    user_id = "tester_01"

    while True:
        query = input("\n[User]: ").strip()

        if query.lower() in ["exit", "q"]:
            break

        if not query:
            continue

        # Giả lập gửi ảnh
        if query.lower() == "image":
            print("📸 [System]: Đã giả lập gửi 1 ảnh (base64).")
            query = "Mẫu này chất liệu gì vậy em?"
            print(f"[User]: {query}")

        # ⚙️ STREAMING MODE - Bật/Tắt
        ENABLE_STREAMING = True

        print("⏳ CiCi is thinking...")

        # 🎯 Call wrapped function - each call = 1 trace
        await run_single_query(
            graph=graph,
            query=query,
            conversation_id=conversation_id,
            user_id=user_id,
            enable_streaming=ENABLE_STREAMING,
        )

    print("\n👋 CiCi: 'Cảm ơn anh/chị đã ghé thăm CANIFA. Hẹn gặp lại nhé!'")


# @observe()  # TẮT TẠM - Tránh Langfuse rate limit
async def run_single_query(graph, query: str, conversation_id: str, user_id: str, enable_streaming: bool = True):
    """Run single query - Langfuse DISABLED"""
    import logging

    logger = logging.getLogger(__name__)

    # Load History từ MongoDB
    history = []

    current_human_msg = HumanMessage(content=query)
    input_state = {
        "messages": [current_human_msg],
        "history": history,
        "user_id": user_id,
    }

    # TẮT Langfuse callback
    # langfuse_handler = CallbackHandler()

    config_runnable = {
        "configurable": {"conversation_id": conversation_id, "user_id": user_id, "transient_images": []},
        # "callbacks": [langfuse_handler],  # TẮT
    }

    final_ai_message = None
    ai_content = ""

    try:
        # Chạy Stream
        if enable_streaming:
            print("\n👸 CiCi: ", end="", flush=True)

        async for event in graph.astream(input_state, config=config_runnable, stream_mode="values"):
            if "messages" in event:
                msg = event["messages"][-1]

                # 🔍 LOG TOOL CALLS
                if hasattr(msg, "tool_calls") and msg.tool_calls:
                    logger.info(f"\n🛠️  TOOL CALLED: {[tc['name'] for tc in msg.tool_calls]}")

                if isinstance(msg, AIMessage) and msg.content:
                    final_ai_message = msg

                    # STREAMING MODE: In từng đoạn content
                    if enable_streaming and msg.content != ai_content:
                        new_content = msg.content[len(ai_content) :]
                        print(new_content, end="", flush=True)
                        ai_content = msg.content

        # Nếu không stream, in toàn bộ
        if not enable_streaming and final_ai_message:
            print(f"\n👸 CiCi: {final_ai_message.content}")
        else:
            print()  # Xuống dòng

        if final_ai_message:
            # Lưu History mới
            new_history = [*history, current_human_msg, final_ai_message]

        # TẮT Langfuse update
        # langfuse = get_client()
        # langfuse.update_current_trace(...)

        print("[System]: ✅ Response complete")

    except Exception as e:
        print(f"\n❌ Error during execution: {e}")
        import traceback

        traceback.print_exc()


if __name__ == "__main__":
    if platform.system() == "Windows":
        asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())

    asyncio.run(main())
