"""
CLI commands for Metis Agent.

This module provides the command-line interface for the agent.
"""
import os
import click
from ..core import SingleAgent
from ..tools import get_available_tools
from ..auth.api_key_manager import APIKeyManager


@click.group()
def cli():
    """Metis Agent CLI for building and running AI agents."""
    pass


@cli.command()
@click.argument("query")
@click.option("--tool", help="Specify a tool to use")
@click.option("--session-id", help="Session ID for context")
@click.option("--memory", is_flag=True, help="Enable Titans memory")
@click.option("--llm", default="openai", help="LLM provider to use")
@click.option("--model", help="LLM model to use")
def run(query, tool=None, session_id=None, memory=False, llm="openai", model=None):
    """Run an agent with a specific query."""
    agent = SingleAgent(use_titans_memory=memory, llm_provider=llm, llm_model=model)
    result = agent.process_query(query, session_id=session_id, tool_name=tool)
    click.echo(result)


@cli.command()
@click.option("--port", default=5000, help="Port to run the server on")
@click.option("--memory", is_flag=True, help="Enable Titans memory")
def serve(port, memory=False):
    """Start the web server."""
    try:
        from ..web.server import app
        click.echo(f"Starting server on port {port} with Titans memory: {memory}")
        app.config['USE_TITANS_MEMORY'] = memory
        app.run(debug=True, port=port)
    except ImportError:
        click.echo("Web server not available. Please install Flask: pip install flask")


@cli.group()
def tools():
    """Manage agent tools."""
    pass


@tools.command("list")
def list_tools():
    """List available tools."""
    tools = get_available_tools()
    click.echo("Available tools:")
    for tool in tools:
        click.echo(f"- {tool}")


@cli.group()
def tasks():
    """Manage agent tasks."""
    pass


@tasks.command("list")
@click.option("--session-id", help="Session ID to filter tasks")
def list_tasks(session_id=None):
    """List current tasks."""
    from ..core.task_manager import TaskManager
    task_file = os.path.join(os.getcwd(), "tasks.md")
    task_manager = TaskManager(task_file)
    tasks = task_manager.get_all_tasks()
    
    click.echo("Pending tasks:")
    for task in tasks["pending"]:
        click.echo(f"- [ ] {task}")
    
    click.echo("\nCompleted tasks:")
    for task in tasks["completed"]:
        click.echo(f"- [x] {task}")


@cli.group()
def memory():
    """Manage agent memory."""
    pass


@memory.command("stats")
def memory_stats():
    """Show memory statistics."""
    from ..memory.titans.titans_adapter import TitansMemoryAdapter
    from ..core.agent import SingleAgent
    
    agent = SingleAgent(use_titans_memory=True)
    insights = agent.get_memory_insights()
    
    click.echo("Memory Statistics:")
    
    if insights["adaptive_memory"]["enabled"]:
        if "insights" in insights["adaptive_memory"]:
            memory_stats = insights["adaptive_memory"]["insights"]["memory_statistics"]
            click.echo(f"- Short-term memories: {memory_stats['short_term_count']}")
            click.echo(f"- Long-term memories: {memory_stats['long_term_count']}")
            click.echo(f"- Contexts: {memory_stats['context_count']}")
            click.echo(f"- Adaptations: {memory_stats['adaptation_count']}")
            click.echo(f"- Average surprise: {memory_stats['avg_surprise_recent']:.2f}")
            
            if "recommendations" in insights["adaptive_memory"]["insights"]:
                click.echo("\nRecommendations:")
                for rec in insights["adaptive_memory"]["insights"]["recommendations"]:
                    click.echo(f"- {rec}")
        else:
            click.echo("Titans memory enabled but no insights available.")
    else:
        click.echo("Titans memory not enabled.")


@cli.group()
def auth():
    """Manage authentication and API keys."""
    pass


@auth.command("set-key")
@click.argument("service")
@click.argument("key")
def set_key(service, key):
    """Set an API key for a service."""
    key_manager = APIKeyManager()
    key_manager.set_key(service, key)
    click.echo(f"API key for {service} set successfully.")


@auth.command("list-keys")
def list_keys():
    """List all configured API keys."""
    key_manager = APIKeyManager()
    services = key_manager.list_services()
    
    if not services:
        click.echo("No API keys configured.")
        return
        
    click.echo("Configured API keys:")
    for service in services:
        click.echo(f"- {service}")


@auth.command("remove-key")
@click.argument("service")
def remove_key(service):
    """Remove an API key for a service."""
    key_manager = APIKeyManager()
    key_manager.remove_key(service)
    click.echo(f"API key for {service} removed successfully.")


@cli.command("configure-llm")
@click.option("--provider", default="openai", help="LLM provider (openai, groq, anthropic, huggingface)")
@click.option("--model", help="Model name")
def configure_llm(provider, model):
    """Configure the LLM to use."""
    from ..core.llm_interface import configure_llm
    from ..auth.api_key_manager import APIKeyManager
    
    key_manager = APIKeyManager()
    api_key = key_manager.get_key(provider)
    
    if not api_key:
        api_key = click.prompt(f"Enter API key for {provider}", hide_input=True)
        key_manager.set_key(provider, api_key)
    
    configure_llm(provider, model, api_key)
    click.echo(f"LLM configured: {provider}" + (f" ({model})" if model else ""))


if __name__ == "__main__":
    cli()