#!/usr/bin/env python3
"""
Genesis Main Dashboard - Operational
Fixed import issues for autonomous operation
"""

import importlib.util
import sys
import os
import threading
import time
from datetime import datetime

def load_module(name, file_path):
    """Load a module from file path"""
    spec = importlib.util.spec_from_file_location(name, file_path)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module

class GenesisMainDashboard:
    def __init__(self):
        # Load modules
        base_dir = os.path.dirname(os.path.abspath(__file__))
        
        cost_tracker_module = load_module("cost_tracker", os.path.join(base_dir, "cost-tracker.py"))
        agent_monitor_module = load_module("agent_monitor", os.path.join(base_dir, "agent-monitor.py"))
        
        self.cost_tracker = cost_tracker_module.GenesisCostTracker()
        self.agent_monitor = agent_monitor_module.GenesisAgentMonitor()
        self.running = False
        
    def start_dashboard(self):
        """Start the complete Genesis monitoring dashboard"""
        
        print("🚀 GENESIS MAIN DASHBOARD ACTIVATION")
        print("===================================")
        print("")
        
        self.running = True
        
        # Start monitoring threads
        cost_thread = threading.Thread(target=self._cost_monitoring_loop, daemon=True)
        agent_thread = threading.Thread(target=self._agent_monitoring_loop, daemon=True)
        
        cost_thread.start()
        agent_thread.start()
        
        print("✅ Cost Monitoring: Active")
        print("✅ Agent Monitoring: Active") 
        print("✅ Dashboard: Operational")
        print("")
        
        try:
            # Main dashboard loop
            while self.running:
                self._display_status()
                time.sleep(30)  # Update every 30 seconds
                
        except KeyboardInterrupt:
            print("\n🛑 Shutting down Genesis Dashboard...")
            self.running = False
            
    def _cost_monitoring_loop(self):
        """Background cost monitoring"""
        while self.running:
            try:
                # Sample cost tracking event
                self.cost_tracker.log_cost_event(
                    agent_id="dashboard-monitor",
                    operation="monitoring",
                    input_tokens=100,
                    output_tokens=50,
                    model_used="gemini-2.0-flash-exp"
                )
                time.sleep(300)  # Log every 5 minutes
            except Exception as e:
                print(f"Cost monitoring error: {e}")
                time.sleep(60)
                
    def _agent_monitoring_loop(self):
        """Background agent monitoring"""
        while self.running:
            try:
                status = self.agent_monitor.get_all_agent_status()
                # Monitor agent health
                time.sleep(30)  # Check every 30 seconds
            except Exception as e:
                print(f"Agent monitoring error: {e}")
                time.sleep(60)
                
    def _display_status(self):
        """Display current system status"""
        timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        
        try:
            # Get summaries
            cost_summary = self.cost_tracker.get_session_summary(time_window_hours=1)
            agent_status = self.agent_monitor.get_all_agent_status()
            
            print(f"\n📊 GENESIS STATUS - {timestamp}")
            print("=" * 50)
            print(f"💰 Hourly Cost: ${cost_summary['total_cost']:.6f}")
            print(f"💰 Savings: ${cost_summary['total_savings']:.4f} ({cost_summary['savings_percentage']:.1f}%)")
            print(f"🤖 Agents Running: {agent_status['summary']['agents_running']}/{agent_status['summary']['total_agents']}")
            print(f"📈 Progress: {agent_status['summary']['overall_progress']:.1f}%")
            
        except Exception as e:
            print(f"Status display error: {e}")

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