import argparse
import sys
from pathlib import Path
from typing import Sequence

# This is a workaround to be able to import the 'agent' module.
# We assume this script is in `backend/src/agent` and we add `backend/src` to the path.
src_dir = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(src_dir))

from agent.app import get_agent_executor


def main(argv: Sequence[str] | None = None) -> None:
    """The main function."""
    parser = argparse.ArgumentParser(
        description="""
A script to run the research agent from the command line.
This script is a command-line interface to the research agent.
It takes a query as input and prints the research process and the final result.

Example:
python backend/run_agent_cli.py "What are the latest trends in AI?"
"""
    )
    parser.add_argument("query", help="The query to search for.")
    args = parser.parse_args(argv)
    
    # Get the compiled agent executor
    app = get_agent_executor()

    print(f"\nRunning agent with query: '{args.query}'\n")
    print("--- Intermediate Steps ---\n")

    # Stream the execution of the agent
    for s in app.stream(
        {"messages": [("user", args.query)]},
        # The recursion limit is a safety measure to prevent infinite loops.
        {"recursion_limit": 150},
    ):
        if "__end__" not in s:
            print(s)
            print("--------------------")

    # To get the final result, we can invoke the agent and get the last message.
    print("\n--- Final Result ---")
    final_state = app.invoke({"messages": [("user", args.query)]}, {"recursion_limit": 150})
    final_result = final_state['messages'][-1].content
    print(final_result)


if __name__ == "__main__":
    main()
