#!/usr/bin/env python3

"""
Genesis System Status Checker
Provides a comprehensive status report on all Genesis components
"""

import os
import sys
import subprocess
import json
from datetime import datetime
from pathlib import Path

class GenesisStatusChecker:
    def __init__(self):
        self.genesis_home = "/mnt/e/genesis-system"
        self.status_report = {}
        self.all_ready = True

    def check_python_packages(self):
        """Check if required Python packages are installed"""
        print("\n[Checking Python Packages]")
        print("-" * 50)

        packages = {
            'anthropic': 'Anthropic SDK',
            'docker': 'Docker SDK',
            'requests': 'HTTP Library',
            'python-dotenv': 'Environment Config',
        }

        self.status_report['python_packages'] = {}

        for package, description in packages.items():
            try:
                __import__(package)
                status = "✓ Ready"
                self.status_report['python_packages'][package] = 'ready'
                print(f"  {description:<25} {status}")
            except ImportError:
                status = "✗ Missing"
                self.status_report['python_packages'][package] = 'missing'
                print(f"  {description:<25} {status}")
                self.all_ready = False

    def check_system_tools(self):
        """Check if required system tools are available"""
        print("\n[Checking System Tools]")
        print("-" * 50)

        tools = {
            'docker': 'Docker daemon',
            'python3': 'Python interpreter',
            'pip': 'Python package manager',
            'git': 'Git version control',
        }

        self.status_report['system_tools'] = {}

        for tool, description in tools.items():
            try:
                subprocess.run(['which', tool], capture_output=True, check=True)
                status = "✓ Available"
                self.status_report['system_tools'][tool] = 'available'
                print(f"  {description:<25} {status}")
            except subprocess.CalledProcessError:
                status = "✗ Not found"
                self.status_report['system_tools'][tool] = 'not_found'
                print(f"  {description:<25} {status}")

    def check_genesis_directories(self):
        """Check if Genesis component directories exist"""
        print("\n[Checking Genesis Components]")
        print("-" * 50)

        components = {
            'master_controller.py': 'Master Controller',
            'config': 'Configuration',
            '.venv': 'Python Virtual Environment',
            'logs': 'Logs Directory',
        }

        self.status_report['components'] = {}

        for component_path, description in components.items():
            full_path = os.path.join(self.genesis_home, component_path)
            exists = os.path.exists(full_path)

            if exists:
                if os.path.isdir(full_path):
                    item_type = "directory"
                else:
                    item_type = "file"
                status = f"✓ Found ({item_type})"
                self.status_report['components'][component_path] = 'available'
            else:
                status = "✗ Not found"
                self.status_report['components'][component_path] = 'missing'

            print(f"  {description:<25} {status}")

    def check_mcp_servers(self):
        """Check MCP server status"""
        print("\n[Checking MCP Servers]")
        print("-" * 50)

        mcp_servers = {
            'docker': 'Docker MCP',
            'memory': 'Memory MCP',
            'n8n': 'n8n MCP',
            'slack': 'Slack MCP',
        }

        self.status_report['mcp_servers'] = {}

        for server_name, description in mcp_servers.items():
            # Check if server might be running (simplified check)
            # In a real scenario, this would check actual running processes
            status = "⚠ Status unknown"
            self.status_report['mcp_servers'][server_name] = 'unknown'
            print(f"  {description:<25} {status}")

        print("\n  Note: Run 'docker ps' to see running containers")

    def check_n8n_workflows(self):
        """Check n8n workflow status (if available)"""
        print("\n[Checking n8n Workflows]")
        print("-" * 50)

        self.status_report['n8n_workflows'] = {}

        # Try to connect to n8n API
        try:
            import requests
            n8n_url = "http://localhost:5678/api/v1/workflows"
            response = requests.get(n8n_url, timeout=2)

            if response.status_code == 200:
                workflows = response.json()
                count = len(workflows.get('data', []))
                print(f"  Active workflows:       {count}")
                self.status_report['n8n_workflows']['count'] = count
                self.status_report['n8n_workflows']['status'] = 'connected'
            else:
                print(f"  n8n API:                ⚠ Responded but unexpected status")
                self.status_report['n8n_workflows']['status'] = 'error'
        except Exception as e:
            print(f"  n8n API:                ✗ Not accessible")
            print(f"    (This is normal if n8n is not running)")
            self.status_report['n8n_workflows']['status'] = 'unavailable'

    def check_resource_usage(self):
        """Check system resource usage"""
        print("\n[Resource Usage]")
        print("-" * 50)

        self.status_report['resources'] = {}

        try:
            # Check disk space
            import shutil
            disk_usage = shutil.disk_usage(self.genesis_home)
            used_gb = disk_usage.used / (1024**3)
            total_gb = disk_usage.total / (1024**3)
            percent = (disk_usage.used / disk_usage.total) * 100

            print(f"  Disk space:             {used_gb:.2f}GB / {total_gb:.2f}GB ({percent:.1f}%)")
            self.status_report['resources']['disk'] = {
                'used_gb': round(used_gb, 2),
                'total_gb': round(total_gb, 2),
                'percent': round(percent, 1)
            }
        except Exception as e:
            print(f"  Disk space:             ⚠ Could not determine")
            self.status_report['resources']['disk'] = 'unknown'

        # Check memory if psutil available
        try:
            import psutil
            memory = psutil.virtual_memory()
            print(f"  Memory usage:           {memory.percent}%")
            self.status_report['resources']['memory'] = memory.percent
        except ImportError:
            print(f"  Memory usage:           ⚠ psutil not installed")
            self.status_report['resources']['memory'] = 'unknown'

    def check_environment(self):
        """Check environment variables"""
        print("\n[Environment Variables]")
        print("-" * 50)

        self.status_report['environment'] = {}

        env_vars = ['GEMINI_API_KEY', 'VIRTUAL_ENV', 'PYTHONPATH']

        for var in env_vars:
            value = os.getenv(var)
            if value:
                # Mask sensitive values
                if 'KEY' in var or 'TOKEN' in var or 'SECRET' in var:
                    display_value = value[:10] + "..." if len(value) > 10 else "***"
                else:
                    display_value = value
                status = "✓ Set"
                self.status_report['environment'][var] = 'set'
                print(f"  {var:<25} {status}")
            else:
                status = "✗ Not set"
                self.status_report['environment'][var] = 'not_set'
                print(f"  {var:<25} {status}")

    def generate_summary(self):
        """Generate and display summary report"""
        print("\n" + "=" * 50)
        print("GENESIS SYSTEM STATUS SUMMARY")
        print("=" * 50)

        timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        print(f"Timestamp: {timestamp}")

        # Count status
        total_checks = sum(len(v) for v in self.status_report.values() if isinstance(v, dict))

        print(f"\nOverall Status: {'✓ All Systems Ready' if self.all_ready else '⚠ Some Issues Detected'}")
        print(f"Total Checks: {total_checks}")

        print("\nQuick Actions:")
        print(f"  Start Genesis:    bash {self.genesis_home}/start_genesis.sh")
        print(f"  View logs:        tail -f {self.genesis_home}/logs/genesis.log")
        print(f"  Check Docker:     docker ps")

        print("\n" + "=" * 50)

    def run_all_checks(self):
        """Run all status checks"""
        print("\n╔════════════════════════════════════════════════════╗")
        print("║     GENESIS SYSTEM STATUS CHECK v1.0              ║")
        print("║     Powered by Claude DevOps                      ║")
        print("╚════════════════════════════════════════════════════╝")

        self.check_python_packages()
        self.check_system_tools()
        self.check_genesis_directories()
        self.check_environment()
        self.check_mcp_servers()
        self.check_n8n_workflows()
        self.check_resource_usage()
        self.generate_summary()


def main():
    checker = GenesisStatusChecker()

    try:
        checker.run_all_checks()
        sys.exit(0 if checker.all_ready else 1)
    except KeyboardInterrupt:
        print("\n\nStatus check interrupted by user")
        sys.exit(1)
    except Exception as e:
        print(f"\nError during status check: {e}")
        sys.exit(1)


if __name__ == "__main__":
    main()
