"""
CLI entry point for the OpenRouter Agent.
Uses the abstracted UserInterface for all user I/O.
"""

import argparse
import os
from typing import Optional

from core.agent import OpenRouterAgent
from core.io.cli import CLIInterface
from core.tools.builtin import get_builtin_tools, set_working_directory
from core.tools.custom import get_custom_tools


def create_agent_with_tools(
    api_key: str,
    working_directory: Optional[str] = None
) -> OpenRouterAgent:
    """Create an agent with built-in and custom tools"""
    if working_directory:
        set_working_directory(working_directory)
    
    tools = get_builtin_tools()
    tools.update(get_custom_tools())
    
    return OpenRouterAgent(
        api_key=api_key,
        model="qwen/qwen3-coder-next",
        temperature=0.7,
        max_iterations=8,
        tools=tools
    )


def main():
    """Main entry point for the CLI"""
    
    parser = argparse.ArgumentParser(description="OpenRouter AI Agent")
    parser.add_argument(
        "--directory", "-d",
        help="Working directory for file operations"
    )
    args = parser.parse_args()
    
    api_key = os.getenv("OPENROUTER_API_KEY")
    if not api_key:
        print("Error: OPENROUTER_API_KEY environment variable not set")
        return
    
    agent = create_agent_with_tools(api_key, args.directory)
    ui = CLIInterface()
    
    system_prompt = """You are a helpful AI assistant with access to various tools.
    When asked a question, use the available tools to gather information or perform actions.
    Always be concise and helpful in your responses."""
    
    ui.run_session(agent, system_prompt)


if __name__ == "__main__":
    main()