#!/usr/bin/env python3
import subprocess
import platform
import psutil
import logging
import os
from typing import Dict, List, Optional

class MacOSCLIEnhanced:
    def __init__(self, log_path='/var/log/m_cli_enhanced.log'):
        # Configure logging
        logging.basicConfig(
            filename=log_path, 
            level=logging.INFO, 
            format='%(asctime)s - %(levelname)s: %(message)s'
        )
        self.logger = logging.getLogger(__name__)
    
    def system_info(self) -> Dict[str, str]:
        """Gather comprehensive system information"""
        return {
            "os_version": platform.mac_ver()[0],
            "machine": platform.machine(),
            "processor": platform.processor(),
            "memory_total": f"{psutil.virtual_memory().total / (1024**3):.2f} GB",
            "cpu_cores": os.cpu_count()
        }
    
    def disk_usage(self, path: str = '/') -> Dict[str, str]:
        """Get disk usage statistics"""
        usage = psutil.disk_usage(path)
        return {
            "total": f"{usage.total / (1024**3):.2f} GB",
            "used": f"{usage.used / (1024**3):.2f} GB",
            "free": f"{usage.free / (1024**3):.2f} GB",
            "percent": f"{usage.percent}%"
        }
    
    def network_diagnostics(self) -> Dict[str, str]:
        """Run network connectivity tests"""
        try:
            # Test internet connectivity
            result = subprocess.run(
                ['ping', '-c', '4', '8.8.8.8'], 
                capture_output=True, 
                text=True, 
                timeout=10
            )
            return {
                "internet_connectivity": "ONLINE" if result.returncode == 0 else "OFFLINE",
                "ping_output": result.stdout
            }
        except subprocess.TimeoutExpired:
            return {"internet_connectivity": "TIMEOUT"}
        except Exception as e:
            self.logger.error(f"Network test failed: {e}")
            return {"internet_connectivity": "ERROR"}
    
    def performance_monitor(self) -> Dict[str, float]:
        """Get current system performance metrics"""
        return {
            "cpu_percent": psutil.cpu_percent(),
            "memory_percent": psutil.virtual_memory().percent,
            "disk_percent": psutil.disk_usage('/').percent
        }
    
    def system_cleanup(self, dry_run: bool = True) -> Dict[str, List[str]]:
        """
        Perform system cleanup operations
        
        :param dry_run: If True, only list potential cleanup actions
        :return: Dictionary of cleanup actions
        """
        cleanup_actions = {
            "temp_files": [
                "/tmp/*",
                "~/Library/Caches/*"
            ],
            "log_files": [
                "/var/log/*.log",
                "~/Library/Logs/*"
            ]
        }
        
        if not dry_run:
            for category, paths in cleanup_actions.items():
                for path in paths:
                    try:
                        subprocess.run(['rm', '-rf', os.path.expanduser(path)], check=True)
                        self.logger.info(f"Cleaned up {path}")
                    except Exception as e:
                        self.logger.error(f"Failed to clean {path}: {e}")
        
        return cleanup_actions
    
    def cli_interface(self):
        """Interactive CLI for system utilities"""
        while True:
            print("\nMacOS CLI Enhanced")
            print("1. System Information")
            print("2. Disk Usage")
            print("3. Network Diagnostics")
            print("4. Performance Monitor")
            print("5. System Cleanup (Dry Run)")
            print("6. Exit")
            
            choice = input("Choose an option: ")
            
            try:
                if choice == '1':
                    print(json.dumps(self.system_info(), indent=2))
                elif choice == '2':
                    print(json.dumps(self.disk_usage(), indent=2))
                elif choice == '3':
                    print(json.dumps(self.network_diagnostics(), indent=2))
                elif choice == '4':
                    print(json.dumps(self.performance_monitor(), indent=2))
                elif choice == '5':
                    print(json.dumps(self.system_cleanup(dry_run=True), indent=2))
                elif choice == '6':
                    break
            except Exception as e:
                print(f"An error occurred: {e}")

def main():
    cli = MacOSCLIEnhanced()
    cli.cli_interface()

if __name__ == "__main__":
    main()