#!/usr/bin/env python3
"""
Textual Interactive Dashboard Demo
===================================

This example demonstrates the new Textual interactive dashboard for MarSys,
showing real-time agent execution monitoring with user interaction capabilities.

Features demonstrated:
- Beautiful TUI with agent panels
- Real-time event streaming
- User input handling through the dashboard
- Detail level filtering (Ctrl+D)
- Collapsible panels (Ctrl+R)
- Multi-agent coordination visualization
"""

import asyncio
import os
import sys
from pathlib import Path

# Add parent directory to path
sys.path.insert(0, str(Path(__file__).parent.parent))

from marsys.agents import Agent
from marsys.agents.registry import AgentRegistry
from marsys.coordination import Orchestra
from marsys.coordination.config import ExecutionConfig, StatusConfig, VerbosityLevel
from marsys.models import ModelConfig
from marsys.coordination.communication.manager import CommunicationManager


def create_demo_agents():
    """Create simple demo agents for testing."""
    registry = AgentRegistry()

    # Create a simple analyzer agent
    analyzer_config = ModelConfig(
        type="api",
        name="gpt-3.5-turbo",
        provider="openai",
        api_key=os.getenv("OPENAI_API_KEY", "demo-key"),
        parameters={"temperature": 0.7, "max_tokens": 500}
    )

    analyzer = Agent(
        name="Analyzer",
        role="Data Analyzer",
        goal="Analyze input and provide insights",
        backstory="Expert at analyzing data and finding patterns",
        model_config=analyzer_config
    )

    # Create a simple writer agent
    writer_config = ModelConfig(
        type="api",
        name="gpt-3.5-turbo",
        provider="openai",
        api_key=os.getenv("OPENAI_API_KEY", "demo-key"),
        parameters={"temperature": 0.8, "max_tokens": 500}
    )

    writer = Agent(
        name="Writer",
        role="Content Writer",
        goal="Create clear and engaging content",
        backstory="Skilled at writing clear explanations",
        model_config=writer_config
    )

    # Register agents
    registry.register(analyzer)
    registry.register(writer)

    return registry


async def run_dashboard_demo():
    """Run the dashboard demonstration."""
    print("\n" + "="*60)
    print("MarSys Textual Dashboard Demo")
    print("="*60)
    print("\nInitializing agents and dashboard...")

    # Create agent registry
    agent_registry = create_demo_agents()

    # Create communication manager
    comm_manager = CommunicationManager()

    # Create status config with Textual dashboard
    status_config = StatusConfig.textual_interactive()

    # Alternative: You can also configure it manually:
    # status_config = StatusConfig(
    #     enabled=True,
    #     dashboard_mode="textual",
    #     channels=["textual_dashboard"],
    #     textual_detail_level=1,  # Start with Standard view
    #     verbosity=VerbosityLevel.NORMAL
    # )

    # Create execution config with status enabled
    execution_config = ExecutionConfig(
        status=status_config,
        steering_mode="auto",
        dynamic_convergence_enabled=True
    )

    # Create Orchestra with dashboard configuration
    orchestra = Orchestra(
        agent_registry=agent_registry,
        communication_manager=comm_manager,
        execution_config=execution_config
    )

    # Define topology with User interaction
    topology = {
        "agents": ["User", "Analyzer", "Writer"],
        "flows": [
            "User -> Analyzer",
            "Analyzer -> Writer",
            "Writer -> User"
        ],
        "rules": []
    }

    # Initial task
    task = """
    Please help me analyze the following topic and write a brief article about it:
    "The impact of artificial intelligence on modern education"

    First analyze the key aspects, then write a short engaging article.
    """

    print("\n" + "-"*60)
    print("Dashboard Controls:")
    print("  • Ctrl+D: Cycle through detail levels (0-3)")
    print("  • Ctrl+R: Toggle collapse/expand all panels")
    print("  • Ctrl+Q: Quit application")
    print("  • Enter: Send input when prompted")
    print("  • Shift+Enter: New line in input field")
    print("-"*60)
    print("\nLaunching Textual dashboard...")
    print("(The dashboard will open in this terminal)\n")

    # Small delay to let users read the instructions
    await asyncio.sleep(2)

    try:
        # Run the orchestration - this will open the Textual dashboard
        result = await Orchestra.run(
            task=task,
            topology=topology,
            agent_registry=agent_registry,
            context={"demo": True},
            execution_config=execution_config
        )

        # After dashboard closes, show results
        print("\n" + "="*60)
        print("Execution Complete!")
        print("="*60)

        if result.success:
            print("\n✅ Success!")
            print(f"Total steps: {result.total_steps}")
            print(f"Duration: {result.total_duration:.2f}s")

            if result.final_response:
                print("\n📄 Final Response:")
                print("-"*40)
                response_text = result.get_final_response_as_text()
                # Truncate if very long
                if len(response_text) > 1000:
                    print(response_text[:1000] + "...\n[Response truncated]")
                else:
                    print(response_text)
        else:
            print("\n❌ Execution failed")
            if result.error:
                print(f"Error: {result.error}")

        # Show branch information
        if result.branch_results:
            print("\n📊 Branch Statistics:")
            print("-"*40)
            for branch in result.branch_results:
                print(f"  • Branch {branch.branch_id[:8]}: {branch.total_steps} steps, "
                      f"{'✓' if branch.success else '✗'}")

    except KeyboardInterrupt:
        print("\n\n⚠️ Dashboard closed by user (Ctrl+C)")
    except Exception as e:
        print(f"\n❌ Error running demo: {e}")
        import traceback
        traceback.print_exc()


def main():
    """Main entry point."""
    # Check for required environment variables
    if not os.getenv("OPENAI_API_KEY"):
        print("\n⚠️ Warning: OPENAI_API_KEY not set")
        print("The demo will run but agents won't make actual API calls.")
        print("Set your API key to see real agent interactions:")
        print("  export OPENAI_API_KEY='your-key-here'\n")

    # Check if Textual is installed
    try:
        import textual
        print(f"✓ Textual {textual.__version__} is installed")
    except ImportError:
        print("\n❌ Textual is not installed!")
        print("Please install it with: pip install textual>=0.50.0")
        print("Or install all requirements: pip install -r requirements.txt")
        sys.exit(1)

    # Run the async demo
    try:
        asyncio.run(run_dashboard_demo())
    except KeyboardInterrupt:
        print("\n\nDemo terminated by user.")
    except Exception as e:
        print(f"\n❌ Fatal error: {e}")
        import traceback
        traceback.print_exc()


if __name__ == "__main__":
    main()