import json
from typing import Optional

from app.agents.shopping_agent import ShoppingAgent


def run_once(agent: ShoppingAgent, query: str, image_path: Optional[str] = None) -> None:
    """Run a single query through the agent and pretty-print details."""
    result = agent.chat(query=query, image_path=image_path)

    print("\n=== Assistant Response ===")
    print(result.get("response", ""))

    print("\n=== Tool Calls ===")
    tool_calls = result.get("tool_calls", []) or []
    if not tool_calls:
        print("(no tool calls)")
    else:
        for i, tc in enumerate(tool_calls, 1):
            print(f"[{i}] {tc.get('name')}")
            print("  args:")
            print("  " + json.dumps(tc.get("args", {}), ensure_ascii=False, indent=2).replace("\n", "\n  "))
            if "result" in tc:
                print("  result (truncated):")
                print("  " + str(tc.get("result")).replace("\n", "\n  "))

    print("\n=== Debug Steps ===")
    debug_steps = result.get("debug_steps", []) or []
    if not debug_steps:
        print("(no debug steps)")
    else:
        for idx, step in enumerate(debug_steps, 1):
            node = step.get("node", "unknown")
            print(f"\n--- Step {idx} [{node}] ---")

            if node == "agent":
                msgs = step.get("messages", []) or []
                if msgs:
                    print("  Agent messages:")
                    for m in msgs:
                        role = m.get("type", "assistant")
                        content = m.get("content", "")
                        print(f"    - {role}: {content}")

                tcs = step.get("tool_calls", []) or []
                if tcs:
                    print("  Planned tool calls:")
                    for j, tc in enumerate(tcs, 1):
                        print(f"    [{j}] {tc.get('name')}")
                        print(
                            "      args: "
                            + json.dumps(tc.get("args", {}), ensure_ascii=False)
                        )

            elif node == "tools":
                results = step.get("results", []) or []
                if results:
                    print("  Tool results:")
                    for j, r in enumerate(results, 1):
                        content = r.get("content", "")
                        print(f"    [{j}] {content}")


def main() -> None:
    """Simple CLI debugger to inspect agent reasoning and tool usage."""
    agent = ShoppingAgent(session_id="cli-debug")
    print("ShopAgent CLI Debugger")
    print("输入你的问题，或者输入 `exit` 退出。\n")

    while True:
        try:
            query = input("你：").strip()
        except (EOFError, KeyboardInterrupt):
            print("\n再见 👋")
            break

        if not query:
            continue
        if query.lower() in {"exit", "quit"}:
            print("再见 👋")
            break

        run_once(agent, query=query)
        print("\n" + "=" * 60 + "\n")


if __name__ == "__main__":
    main()

