"""
QEMU Manager Runner Script
Helps manage QEMU VMs with frame rendering and OS management
"""

import asyncio
from qemu_manager_new import QEMUManager
from qemu_storage import QEMUStorage

async def main():
    # Initialize storage and QEMU manager
    storage = QEMUStorage()
    manager = QEMUManager(storage=storage)
    
    try:
        # Check if OS is already installed
        vm_state = storage.get_vm_state('status')
        
        installation = storage.get_vm_state('installation')
        if not installation or not installation.get('completed', False):
            # If no OS installed, download and install one
            print("No OS installation found. Starting fresh installation...")
            # Using TinyCore Linux as it's very small and fast to download
            iso_url = "http://www.tinycorelinux.net/13.x/x86/release/TinyCore-current.iso"
            vnc_port = await manager.install_os(iso_url)
            print(f"OS installation started. Connect to VNC on port {vnc_port} to view installation progress")
        else:
            # Boot existing OS
            print("Booting existing OS installation...")
            vnc_port = await manager.boot_os()
            print(f"OS booted. Connect to VNC on port {vnc_port} to view the OS")

        # Keep the script running while VM is active
        print("Press Ctrl+C to shutdown the VM")
        while True:
            await asyncio.sleep(1)
            
    except KeyboardInterrupt:
        print("\nShutting down VM...")
        await manager.shutdown()
        print("VM shutdown complete")
    except Exception as e:
        print(f"Error: {e}")
        await manager.shutdown()

if __name__ == "__main__":
    asyncio.run(main())