#!/usr/bin/env python3
"""
Demonstration of the Enhanced Terminal Channel with Rich formatting.

This example shows the visual improvements and enhanced input capabilities
of the new terminal channel implementation.
"""

import asyncio
import sys
from pathlib import Path

# Add project root to path
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))

from marsys.coordination.communication import CommunicationManager
from marsys.coordination.communication.channels import EnhancedTerminalChannel
from marsys.coordination.communication.core import UserInteraction, CommunicationMode
from marsys.coordination.config import CommunicationConfig
import time


async def demo_basic_interaction():
    """Demonstrate basic interaction with enhanced formatting."""
    print("\n" + "=" * 60)
    print("DEMO 1: Basic Enhanced Terminal Interaction")
    print("=" * 60)

    # Create communication manager with enhanced terminal
    config = CommunicationConfig(
        use_enhanced_terminal=True,
        use_rich_formatting=True,
        theme_name="modern",
        prefix_width=20,
        show_timestamps=True
    )

    manager = CommunicationManager(config)

    # Create a simple question interaction
    interaction = UserInteraction(
        interaction_id="demo-1",
        branch_id="main",
        session_id="demo-session",
        incoming_message="What topic would you like to research today? I can help you explore any subject in depth.",
        interaction_type="question",
        calling_agent="ResearchAgent",
        resume_agent="ResearchAgent",
        communication_mode=CommunicationMode.SYNC,
        timeout=60
    )

    # Send interaction and get response
    response = await manager.handle_interaction(interaction)
    print(f"\nReceived response: {response}")


async def demo_choice_interaction():
    """Demonstrate multiple choice interaction."""
    print("\n" + "=" * 60)
    print("DEMO 2: Multiple Choice with Rich Formatting")
    print("=" * 60)

    config = CommunicationConfig(
        use_enhanced_terminal=True,
        theme_name="modern"
    )

    manager = CommunicationManager(config)

    # Create a choice interaction
    interaction = UserInteraction(
        interaction_id="demo-2",
        branch_id="main",
        session_id="demo-session",
        incoming_message={
            "content": "Which analysis approach would you prefer?",
            "options": [
                "Comprehensive deep research",
                "Quick market overview",
                "Competitive analysis",
                "Technical feasibility study"
            ]
        },
        interaction_type="choice",
        calling_agent="AnalysisCoordinator",
        resume_agent="AnalysisCoordinator",
        communication_mode=CommunicationMode.SYNC
    )

    response = await manager.handle_interaction(interaction)
    print(f"\nChosen option: {response}")


async def demo_confirmation():
    """Demonstrate confirmation prompt."""
    print("\n" + "=" * 60)
    print("DEMO 3: Confirmation with Rich Prompt")
    print("=" * 60)

    config = CommunicationConfig(
        use_enhanced_terminal=True,
        theme_name="classic"  # Try a different theme
    )

    manager = CommunicationManager(config)

    # Create confirmation interaction
    interaction = UserInteraction(
        interaction_id="demo-3",
        branch_id="main",
        session_id="demo-session",
        incoming_message="The research will analyze 50+ sources and may take 5-10 minutes. Proceed?",
        interaction_type="confirmation",
        calling_agent="System",
        resume_agent="System",
        communication_mode=CommunicationMode.SYNC
    )

    response = await manager.handle_interaction(interaction)
    print(f"\nConfirmation result: {response}")


async def demo_multi_agent_conversation():
    """Demonstrate multiple agents with colored prefixes."""
    print("\n" + "=" * 60)
    print("DEMO 4: Multi-Agent Conversation with Prefixes")
    print("=" * 60)

    # Create enhanced terminal directly to show prefix formatting
    channel = EnhancedTerminalChannel(
        channel_id="demo",
        use_rich=True,
        theme_name="modern",
        prefix_width=20,
        show_timestamps=True
    )

    # Start the channel
    await channel.start()

    # Simulate different agents sending messages
    agents = [
        ("System", "notification", "Workflow initialized"),
        ("OrchestratorAgent", "question", "What would you like me to help you with today?"),
        ("ResearchAgent", "notification", "Preparing to gather information from multiple sources"),
        ("AnalysisAgent", "notification", "Ready to process and analyze data"),
        ("SynthesisAgent", "notification", "Standing by to compile final report"),
    ]

    for agent_name, msg_type, message in agents:
        interaction = UserInteraction(
            interaction_id=f"demo-{agent_name}",
            branch_id="main",
            session_id="demo-session",
            incoming_message=message,
            interaction_type=msg_type,
            calling_agent=agent_name,
            resume_agent=agent_name,
            communication_mode=CommunicationMode.SYNC
        )

        await channel.send_interaction(interaction)
        await asyncio.sleep(0.5)  # Small delay for visual effect

    # Stop the channel
    await channel.stop()


async def demo_complex_context():
    """Demonstrate complex message with context."""
    print("\n" + "=" * 60)
    print("DEMO 5: Complex Message with Context")
    print("=" * 60)

    config = CommunicationConfig(
        use_enhanced_terminal=True,
        theme_name="modern"
    )

    manager = CommunicationManager(config)

    # Create interaction with complex context
    interaction = UserInteraction(
        interaction_id="demo-5",
        branch_id="main",
        session_id="demo-session",
        incoming_message={
            "content": "Based on the analysis, I found several insights. Would you like me to elaborate on any of these areas?",
            "context": {
                "Documents analyzed": 47,
                "Key findings": 12,
                "Confidence score": "92%",
                "Processing time": "3.7 seconds"
            },
            "options": [
                "Show detailed findings",
                "Generate executive summary",
                "Export raw data",
                "Start new analysis"
            ]
        },
        interaction_type="choice",
        calling_agent="AnalysisAgent",
        resume_agent="AnalysisAgent",
        communication_mode=CommunicationMode.SYNC
    )

    response = await manager.handle_interaction(interaction)
    print(f"\nSelected action: {response}")


async def demo_theme_comparison():
    """Show different themes side by side."""
    print("\n" + "=" * 60)
    print("DEMO 6: Theme Comparison")
    print("=" * 60)

    themes = ["modern", "classic", "minimal"]

    for theme in themes:
        print(f"\n--- Theme: {theme.upper()} ---")

        channel = EnhancedTerminalChannel(
            channel_id=f"demo-{theme}",
            use_rich=True,
            theme_name=theme,
            show_timestamps=False  # Disable for cleaner comparison
        )

        await channel.start()

        interaction = UserInteraction(
            interaction_id=f"theme-{theme}",
            branch_id="main",
            session_id="demo-session",
            incoming_message=f"This is how the {theme} theme looks!",
            interaction_type="notification",
            calling_agent="ThemeDemo",
            resume_agent="ThemeDemo",
            communication_mode=CommunicationMode.SYNC
        )

        await channel.send_interaction(interaction)
        await channel.stop()
        await asyncio.sleep(0.5)


async def demo_fallback_mode():
    """Demonstrate fallback to basic mode when Rich is disabled."""
    print("\n" + "=" * 60)
    print("DEMO 7: Fallback Mode (No Rich)")
    print("=" * 60)

    # Create config with Rich disabled
    config = CommunicationConfig(
        use_enhanced_terminal=True,
        use_rich_formatting=False  # Disable Rich formatting
    )

    manager = CommunicationManager(config)

    interaction = UserInteraction(
        interaction_id="demo-fallback",
        branch_id="main",
        session_id="demo-session",
        incoming_message="This uses fallback formatting without Rich library features.",
        interaction_type="notification",
        calling_agent="FallbackDemo",
        resume_agent="FallbackDemo",
        communication_mode=CommunicationMode.SYNC
    )

    await manager.handle_interaction(interaction)


async def main():
    """Run all demos."""
    print("\n" + "=" * 80)
    print(" ENHANCED TERMINAL CHANNEL DEMONSTRATION ".center(80, "="))
    print("=" * 80)
    print("\nThis demo showcases the new Rich-powered terminal interface")
    print("with beautiful formatting, colored prefixes, and enhanced input.\n")

    demos = [
        ("Basic Interaction", demo_basic_interaction),
        ("Multiple Choice", demo_choice_interaction),
        ("Confirmation Prompt", demo_confirmation),
        ("Multi-Agent Prefixes", demo_multi_agent_conversation),
        ("Complex Context", demo_complex_context),
        ("Theme Comparison", demo_theme_comparison),
        ("Fallback Mode", demo_fallback_mode),
    ]

    for i, (name, demo_func) in enumerate(demos, 1):
        print(f"\nRunning Demo {i}/{len(demos)}: {name}")
        print("Press Enter to continue...")
        input()

        try:
            await demo_func()
        except KeyboardInterrupt:
            print("\n\nDemo interrupted by user")
            break
        except Exception as e:
            print(f"\nError in demo: {e}")

    print("\n" + "=" * 80)
    print(" DEMONSTRATION COMPLETE ".center(80, "="))
    print("=" * 80)
    print("\nThe Enhanced Terminal Channel provides:")
    print("✅ Beautiful Rich panels and formatting")
    print("✅ Colored agent prefixes for easy identification")
    print("✅ Advanced input with history and editing")
    print("✅ Multiple themes (modern, classic, minimal)")
    print("✅ Graceful fallback for non-TTY environments")
    print("✅ Full backward compatibility")


if __name__ == "__main__":
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        print("\n\nDemo cancelled by user")