"""agent_execution_flow_demo.py — print each message after invoke"""

from dotenv import load_dotenv
from langchain.agents import create_agent
from langchain.tools import tool

load_dotenv()

TAGS = {
    "a": "Creates a hyperlink. Use href for the URL.",
    "title": "Sets the browser tab title.",
}


@tool
def lookup_html_tag(tag_name: str) -> str:
    """Look up a short description of an HTML tag by name."""
    key = tag_name.strip().lower().lstrip("<").rstrip(">")
    if key in TAGS:
        return f"<{key}>: {TAGS[key]}"
    return f"No entry for '{tag_name}'."


def print_messages(label: str, messages: list) -> None:
    print(f"\n=== {label} ({len(messages)} messages) ===")
    for i, msg in enumerate(messages):
        msg_type = getattr(msg, "type", type(msg).__name__)
        if msg_type == "ai" and getattr(msg, "tool_calls", None):
            names = [tc["name"] for tc in msg.tool_calls]
            print(f"[{i}] ai tool_calls: {names}")
        elif msg.content:
            text = msg.content.replace("\n", " ")
            print(f"[{i}] {msg_type}: {text[:90]}")
        else:
            print(f"[{i}] {msg_type}: (empty)")


agent = create_agent(model="openai:gpt-4o-mini", tools=[lookup_html_tag])

runs = [
    ("no tool", "What does the <title> tag do? One sentence."),
    ("with tool", "What does the <a> tag do? Use lookup_html_tag."),
]

for label, question in runs:
    print(f"\nQuestion: {question}")
    result = agent.invoke({"messages": [{"role": "user", "content": question}]})
    print_messages(label, result["messages"])