#!/usr/bin/env python3
"""
Simple Monitoring Dashboard for Hotel MCP Server.

This script provides a real-time monitoring dashboard that displays
performance metrics, cache statistics, and system health.
"""
# flake8: noqa: E402,E226

import json
import os
import sys
import time
from datetime import datetime
from pathlib import Path

# Load environment variables
from dotenv import load_dotenv

# Add src to path for imports
sys.path.insert(0, str(Path(__file__).parent.parent / "src"))

load_dotenv()


def clear_screen():
    """Clear the terminal screen."""
    os.system("cls" if os.name == "nt" else "clear")


def format_duration(seconds: float) -> str:
    """Format duration in human-readable format."""
    if seconds < 1:
        return f"{seconds * 1000:.1f}ms"
    elif seconds < 60:
        return f"{seconds:.1f}s"
    else:
        minutes = int(seconds // 60)
        secs = seconds % 60
        return f"{minutes}m {secs:.1f}s"


def format_percentage(value: float) -> str:
    """Format percentage with color coding."""
    percentage = value * 100
    if percentage >= 90:
        return f"🟢 {percentage:.1f}%"
    elif percentage >= 70:
        return f"🟡 {percentage:.1f}%"
    else:
        return f"🔴 {percentage:.1f}%"


def display_header():
    """Display dashboard header."""
    print("🏨 Hotel MCP Server - Monitoring Dashboard")
    print("=" * 60)
    print(f"📅 {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    print()


def display_system_health():
    """Display system health information."""
    try:
        # Import here to avoid circular imports
        from hotel_mcp import health_check

        health_data = health_check()
        status = health_data.get("status", "unknown")

        status_icon = {"healthy": "🟢", "degraded": "🟡", "unhealthy": "🔴"}.get(
            status, "⚪"
        )

        print(f"🏥 System Health: {status_icon} {status.upper()}")

        # Display component status
        components = health_data.get("components", {})
        for component, status in components.items():
            component_icon = "🟢" if status in ["connected", "initialized"] else "🔴"
            print(f"   {component}: {component_icon} {status}")

        print()

    except Exception as e:
        print(f"🔴 System Health: Error - {e}")
        print()


def display_performance_metrics():
    """Display performance metrics."""
    try:
        from monitoring import get_monitoring_summary

        metrics = get_monitoring_summary()
        metrics_data = metrics.get("metrics", {})

        print("📊 Performance Metrics")
        print("-" * 30)

        # Display counters
        counters = metrics_data.get("counters", {})
        if counters:
            print("🔢 Tool Executions:")
            for tool, count in sorted(counters.items()):
                if "executions" in tool:
                    tool_name = tool.replace(".executions", "").replace("tool.", "")
                    print(f"   {tool_name}: {count}")

        # Display timers
        timers = metrics_data.get("timers", {})
        if timers:
            print("\n⏱️  Response Times:")
            for tool, stats in sorted(timers.items()):
                if "duration" in tool:
                    tool_name = tool.replace(".duration", "").replace("tool.", "")
                    avg_time = stats.get("avg", 0)
                    p95_time = stats.get("p95", 0)
                    print(
                        f"   {tool_name}: avg {format_duration(avg_time / 1000)}, p95 {format_duration(p95_time / 1000)}"
                    )

        print()

    except Exception as e:
        print(f"🔴 Performance Metrics: Error - {e}")
        print()


def display_cache_statistics():
    """Display cache statistics."""
    try:
        from cache import get_cache_summary

        cache_data = get_cache_summary()
        cache_stats = cache_data.get("cache_stats", {})

        print("💾 Cache Performance")
        print("-" * 30)

        # Cache hit rate
        hit_rate = cache_stats.get("hit_rate", 0)
        print(f"Hit Rate: {format_percentage(hit_rate)}")

        # Cache size
        size = cache_stats.get("size", 0)
        max_size = cache_stats.get("max_size", 1000)
        size_percentage = size / max_size if max_size > 0 else 0
        print(f"Size: {size}/{max_size} ({format_percentage(size_percentage)})")

        # Cache statistics
        stats = cache_stats.get("stats", {})
        hits = stats.get("hits", 0)
        misses = stats.get("misses", 0)
        evictions = stats.get("evictions", 0)

        print(f"Hits: {hits}")
        print(f"Misses: {misses}")
        print(f"Evictions: {evictions}")

        # Strategy
        strategy = cache_stats.get("strategy", "unknown")
        print(f"Strategy: {strategy}")

        print()

    except Exception as e:
        print(f"🔴 Cache Statistics: Error - {e}")
        print()


def display_recent_activity():
    """Display recent activity summary."""
    print("📈 Recent Activity")
    print("-" * 30)

    try:
        # This would show recent tool calls, errors, etc.
        # For now, we'll show a placeholder
        print("🔄 Last 5 minutes:")
        print("   • Tool calls: Monitoring in progress...")
        print("   • Errors: Monitoring in progress...")
        print("   • Cache hits: Monitoring in progress...")

    except Exception as e:
        print(f"🔴 Recent Activity: Error - {e}")

    print()


def display_recommendations():
    """Display optimization recommendations."""
    print("💡 Recommendations")
    print("-" * 30)

    try:
        from cache import get_cache_summary

        cache_data = get_cache_summary()
        cache_stats = cache_data.get("cache_stats", {})

        recommendations = []

        # Cache recommendations
        hit_rate = cache_stats.get("hit_rate", 0)
        if hit_rate < 0.5:
            recommendations.append("🔧 Consider increasing cache TTL")
        elif hit_rate > 0.9:
            recommendations.append("✅ Excellent cache performance")

        size = cache_stats.get("size", 0)
        max_size = cache_stats.get("max_size", 1000)
        if size > max_size * 0.9:
            recommendations.append("📈 Consider increasing cache size")

        # Performance recommendations
        # This would analyze response times and suggest optimizations
        recommendations.append("📊 Monitor response times regularly")

        if not recommendations:
            recommendations.append("✅ System is performing optimally")

        for rec in recommendations:
            print(f"   {rec}")

    except Exception as e:
        print(f"🔴 Recommendations: Error - {e}")

    print()


def display_footer():
    """Display dashboard footer."""
    print("-" * 60)
    print("🔄 Auto-refresh: 30s | 'q' to quit | 'r' to refresh now")


def run_dashboard():
    """Run the monitoring dashboard."""
    print("🏨 Starting Hotel MCP Monitoring Dashboard...")
    print("Press Ctrl+C to exit")
    time.sleep(2)

    try:
        while True:
            clear_screen()

            display_header()
            display_system_health()
            display_performance_metrics()
            display_cache_statistics()
            display_recent_activity()
            display_recommendations()
            display_footer()

            # Wait for 30 seconds or user input
            try:
                # This is a simple implementation
                # In a real dashboard, you'd use proper input handling
                time.sleep(30)
            except KeyboardInterrupt:
                break

    except KeyboardInterrupt:
        print("\n\n👋 Dashboard stopped by user")
    except Exception as e:
        print(f"\n\n❌ Dashboard error: {e}")


def run_single_report():
    """Run a single monitoring report."""
    clear_screen()

    display_header()
    display_system_health()
    display_performance_metrics()
    display_cache_statistics()
    display_recent_activity()
    display_recommendations()

    print("📄 Single report completed")


def main():
    """Main function."""
    import argparse

    parser = argparse.ArgumentParser(description="Hotel MCP Monitoring Dashboard")
    parser.add_argument(
        "--mode",
        choices=["dashboard", "report"],
        default="dashboard",
        help="Run mode: dashboard (continuous) or report (single)",
    )

    args = parser.parse_args()

    if args.mode == "dashboard":
        run_dashboard()
    else:
        run_single_report()


if __name__ == "__main__":
    main()
