#!/usr/bin/env python3
"""
Genesis Master Dashboard Controller
Integrated real-time monitoring with cost tracking, agent monitoring, and reporting
"""

import threading
import time
import os
import sys
from datetime import datetime

# Fix import paths
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

from cost_tracker import GenesisCostTracker
from agent_monitor import GenesisAgentMonitor  
from hourly_reporter import GenesisHourlyReporter

class GenesisDashboard:
    def __init__(self):
        self.cost_tracker = GenesisCostTracker()
        self.agent_monitor = GenesisAgentMonitor()
        self.reporter = GenesisHourlyReporter()
        self.running = False
        
    def start_dashboard(self):
        """Start the complete Genesis monitoring dashboard"""
        
        print("🚀 GENESIS COMPREHENSIVE DASHBOARD STARTUP")
        print("==========================================")
        print("")
        
        self.running = True
        
        # Start automated hourly reporting
        print("📊 Starting automated hourly reporting...")
        report_thread = self.reporter.start_automated_reporting()
        
        print("🤖 Starting real-time agent monitoring...")
        print("💰 Cost tracking active")
        print("📈 Dashboard operational")
        print("")
        print("🎯 Dashboard Controls:")
        print("   c - Show cost summary")
        print("   a - Show agent status") 
        print("   r - Generate immediate report")
        print("   s - Show system status")
        print("   q - Quit dashboard")
        print("")
        
        # Main dashboard loop
        try:
            while self.running:
                command = input("Genesis Dashboard> ").strip().lower()
                
                if command == 'c':
                    self.show_cost_summary()
                elif command == 'a':
                    self.show_agent_status()
                elif command == 'r':
                    self.generate_immediate_report()
                elif command == 's':
                    self.show_system_status()
                elif command == 'q':
                    self.running = False
                    break
                else:
                    print("Unknown command. Use: c, a, r, s, or q")
                    
        except KeyboardInterrupt:
            self.running = False
        
        print("\n👋 Genesis Dashboard shutting down...")
        
    def show_cost_summary(self):
        """Show real-time cost summary"""
        print("\n💰 COST SUMMARY")
        print("===============")
        
        # Last hour
        hour_summary = self.cost_tracker.get_session_summary(1)
        print(f"Last Hour:")
        print(f"  Tokens: {hour_summary['total_tokens']:,}")
        print(f"  Cost: ${hour_summary['total_cost']:.4f} (Gemini)")
        print(f"  Savings: ${hour_summary['total_savings']:.2f} ({hour_summary['savings_percentage']:.1f}%)")
        
        # Last 24 hours
        day_summary = self.cost_tracker.get_session_summary(24)
        print(f"\nLast 24 Hours:")
        print(f"  Tokens: {day_summary['total_tokens']:,}")
        print(f"  Cost: ${day_summary['total_cost']:.2f} (Gemini)")
        print(f"  vs Claude: ${day_summary['total_claude_equivalent']:.0f}")
        print(f"  Savings: ${day_summary['total_savings']:.0f} ({day_summary['savings_percentage']:.1f}%)")
        print("")
        
    def show_agent_status(self):
        """Show real-time agent status"""
        print("\n🤖 AGENT STATUS")
        print("===============")
        
        status = self.agent_monitor.get_all_agent_status()
        summary = status['summary']
        
        print(f"Overall Progress: {summary['overall_progress']}%")
        print(f"Running: {summary['agents_running']} | Complete: {summary['agents_complete']} | Pending: {summary['agents_not_started']}")
        print("")
        
        for agent_id, agent_status in status['agents'].items():
            focus = self.agent_monitor.agents[agent_id]['focus']
            print(f"{agent_id}: {agent_status['progress']} ({agent_status['completion_percentage']}%)")
            print(f"  Focus: {focus}")
            print(f"  Process: {'🟢 Running' if agent_status['process_status']['running'] else '🔴 Stopped'}")
            print("")
    
    def generate_immediate_report(self):
        """Generate immediate hourly report"""
        print("\n📊 GENERATING IMMEDIATE REPORT")
        print("==============================")
        
        report_file = self.reporter.generate_hourly_report()
        print(f"✅ Report generated: {report_file}")
        print("")
        
    def show_system_status(self):
        """Show overall system status"""
        print("\n🎯 SYSTEM STATUS")
        print("================")
        
        # Check critical components
        components = {
            'Gemini Proxy': self.check_gemini_proxy(),
            'Dragonfly Memory': self.check_dragonfly(),
            'Parallel Agents': self.check_parallel_agents(),
            'Cost Tracking': True,  # Always true if we're running
            'Reporting System': True
        }
        
        for component, status in components.items():
            status_icon = '✅' if status else '❌'
            print(f"  {status_icon} {component}")
        
        # Overall health
        all_good = all(components.values())
        health = "🟢 EXCELLENT" if all_good else "🟡 PARTIAL" if any(components.values()) else "🔴 CRITICAL"
        print(f"\nOverall Health: {health}")
        print("")
        
    def check_gemini_proxy(self) -> bool:
        """Check if Gemini proxy is running"""
        try:
            import requests
            response = requests.get("http://localhost:8082/health", timeout=5)
            return response.status_code == 200
        except:
            return False
            
    def check_dragonfly(self) -> bool:
        """Check if Dragonfly is running"""
        try:
            import subprocess
            result = subprocess.run(['docker', 'exec', 'genesis-dragonfly', 'redis-cli', '-p', '6380', '-a', 'Genesis2025!', 'ping'], 
                                 capture_output=True, text=True, timeout=5)
            return 'PONG' in result.stdout
        except:
            return False
            
    def check_parallel_agents(self) -> bool:
        """Check if any parallel agents are running"""
        status = self.agent_monitor.get_all_agent_status()
        return status['summary']['agents_running'] > 0 or status['summary']['agents_complete'] > 0

if __name__ == "__main__":
    dashboard = GenesisDashboard()
    dashboard.start_dashboard()
