"""react_framework_demo.py — ReAct prompt + create_react_agent"""

from dotenv import load_dotenv
from langchain_classic.agents import AgentExecutor, create_react_agent
from langchain_core.prompts import PromptTemplate
from langchain_openai import ChatOpenAI
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}'."


REACT_PROMPT = """Answer the following questions as best you can. You have access to the following tools:

{tools}

Use the following format:

Question: the input question you must answer
Thought: you should always think about what to do
Action: the action to take, should be one of [{tool_names}]
Action Input: the input to the action
Observation: the result of the action
... (this Thought/Action/Action Input/Observation can repeat N times)
Thought: I now know the final answer
Final Answer: the final answer to the original input question

Begin!

Question: {input}
Thought:{agent_scratchpad}"""

prompt = PromptTemplate.from_template(REACT_PROMPT)
llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
agent = create_react_agent(llm, [lookup_html_tag], prompt)
executor = AgentExecutor(
    agent=agent,
    tools=[lookup_html_tag],
    verbose=True,
    handle_parsing_errors=True,
)

question = "What does the <a> tag do?"
print(f"Question: {question}\n")
result = executor.invoke({"input": question})
print(f"\nFinal: {result['output']}")