#!/usr/bin/env python3
"""
Simple example demonstrating user interaction in auto_run mode.

This example shows how agents can:
1. Auto-detect when user interaction is needed
2. Ask clarifying questions
3. Get user feedback
4. Adjust their behavior based on user input
"""

import asyncio
import os
from dotenv import load_dotenv
from marsys.agents.agents import Agent
from marsys.models.models import ModelConfig


async def simple_interactive_agent():
    """Create a simple agent that interacts with the user."""
    
    load_dotenv()
    api_key = os.getenv("OPENAI_API_KEY")
    if not api_key:
        print("❌ OPENAI_API_KEY not found in environment!")
        return

    # Model configuration
    model_config = ModelConfig(
        provider="openai",
        name="gpt-4o-mini",
        api_key=api_key,
        type="api",
        temperature=0.7,
    )

    # Create an agent that can interact with users
    ASSISTANT_DESC = """You are a helpful AI assistant that engages in dialogue with the user.

Your workflow:
1. First, greet the user and ask what they need help with
2. If their request is unclear, ask clarifying questions
3. Provide helpful responses based on their needs
4. Ask if they need anything else before completing

IMPORTANT: You have access to the User node. To interact with the user:
{
    "next_action": "invoke_agent",
    "action_input": "User",
    "message": "Your message or question for the user"
}

Always be polite, helpful, and ask for clarification when needed.
Don't make assumptions - ask the user when you're unsure."""

    assistant = Agent(
        model_config=model_config,
        description=ASSISTANT_DESC,
        agent_name="AssistantAgent",
        allowed_peers=["User"],  # This enables user interaction!
    )

    print("\n" + "="*60)
    print("🤖 Simple Interactive Agent Example")
    print("="*60)
    print("\nThis example demonstrates automatic user interaction.")
    print("The agent will detect that it can talk to users and will")
    print("automatically enable terminal interaction.\n")

    # Check if auto-detection works
    needs_user = assistant._should_enable_user_interaction()
    print(f"🔍 Auto-detection: User interaction needed = {needs_user}")

    # Get user's initial request
    task = input("\n💬 What would you like help with today? ")
    if not task:
        task = "Help me understand how user interaction works in this framework"
        print(f"Using default task: {task}")

    print("\n" + "="*60)
    print("🚀 Starting Interactive Session")
    print("="*60)
    print("\n💡 The agent will now interact with you directly!\n")

    try:
        # Run with auto-detected user interaction
        result = await assistant.auto_run(
            initial_request=task,
            max_steps=10,
            verbosity=1,
            # user_interaction is auto-detected because "User" is in allowed_peers!
            # But we can explicitly enable it too:
            user_interaction="terminal"
        )

        print("\n" + "="*60)
        print("✅ Interactive Session Complete")
        print("="*60)
        
        if result:
            print(f"\n📝 Final Response: {str(result)[:500]}")

    except KeyboardInterrupt:
        print("\n\n⚠️ Session interrupted by user")
    except Exception as e:
        print(f"\n❌ Error: {e}")


async def multi_agent_with_user():
    """Example with multiple agents where one can interact with users."""
    
    load_dotenv()
    api_key = os.getenv("OPENAI_API_KEY")
    if not api_key:
        print("❌ OPENAI_API_KEY not found in environment!")
        return

    model_config = ModelConfig(
        provider="openai",
        name="gpt-4o-mini",
        api_key=api_key,
        type="api",
        temperature=0.7,
    )

    # Coordinator can talk to users
    COORDINATOR_DESC = """You coordinate tasks and interact with users.
When you need user input or clarification:
{
    "next_action": "invoke_agent",
    "action_input": "User",
    "message": "Your question"
}
After getting user input, delegate tasks to Worker."""

    # Worker cannot talk to users directly
    WORKER_DESC = """You perform tasks assigned by the Coordinator.
Complete the task and return results to Coordinator."""

    coordinator = Agent(
        model_config=model_config,
        description=COORDINATOR_DESC,
        agent_name="Coordinator",
        allowed_peers=["User", "Worker"],  # Can talk to users!
    )

    worker = Agent(
        model_config=model_config,
        description=WORKER_DESC,
        agent_name="Worker",
        allowed_peers=["Coordinator"],  # Cannot talk to users directly
    )

    print("\n" + "="*60)
    print("🤝 Multi-Agent System with User Interaction")
    print("="*60)
    print("\nCoordinator can interact with users")
    print("Worker cannot (must go through Coordinator)\n")

    # Show auto-detection
    coord_needs_user = coordinator._should_enable_user_interaction()
    worker_needs_user = worker._should_enable_user_interaction()
    
    print(f"🔍 Coordinator needs user interaction: {coord_needs_user}")
    print(f"🔍 Worker needs user interaction: {worker_needs_user} (reaches User through Coordinator)")

    task = input("\n💬 Enter a task for the team: ")
    if not task:
        task = "Create a simple Python function"
        print(f"Using default task: {task}")

    print("\n🚀 Starting multi-agent workflow with user interaction...\n")

    try:
        result = await coordinator.auto_run(
            initial_request=task,
            max_steps=15,
            verbosity=1,
            user_interaction="terminal"  # Enable user interaction
        )

        print("\n✅ Multi-agent task complete!")
        if result:
            print(f"\n📝 Result: {str(result)[:500]}")

    except Exception as e:
        print(f"\n❌ Error: {e}")


def main():
    """Main entry point."""
    print("\n🎆 User Interaction Examples")
    print("="*60)
    print("Choose an example to run:")
    print("1. Simple interactive agent")
    print("2. Multi-agent system with user interaction")
    print("="*60)
    
    choice = input("\nSelect (1 or 2) [default: 1]: ").strip()
    
    if choice == "2":
        asyncio.run(multi_agent_with_user())
    else:
        asyncio.run(simple_interactive_agent())


if __name__ == "__main__":
    main()