"""
QEMU Web Server for VM Management and Display
"""

from aiohttp import web
import aiohttp
import asyncio
import os
from pathlib import Path
from qemu_manager import QEMUManager

routes = web.RouteTableDef()
qemu = QEMUManager()

@routes.get('/')
async def index(request):
    return web.FileResponse(Path(__file__).parent / 'templates' / 'viewer.html')

@routes.get('/status')
async def get_status(request):
    status = "running" if qemu.vm_process and qemu.vm_process.poll() is None else "stopped"
    return web.json_response({"status": status})

@routes.post('/start')
async def start_vm(request):
    if not qemu.vm_process or qemu.vm_process.poll() is not None:
        # Start VM with Ubuntu desktop ISO for testing
        iso_url = "https://releases.ubuntu.com/22.04/ubuntu-22.04.3-desktop-amd64.iso"
        await qemu.install_os(iso_url)
        return web.json_response({"status": "running"})
    return web.json_response({"status": "already_running"})

@routes.post('/stop')
async def stop_vm(request):
    if qemu.vm_process and qemu.vm_process.poll() is None:
        qemu.vm_process.terminate()
        await asyncio.sleep(1)
        if qemu.vm_process.poll() is None:
            qemu.vm_process.kill()
        return web.json_response({"status": "stopped"})
    return web.json_response({"status": "already_stopped"})

@routes.get('/ws')
async def websocket_handler(request):
    ws = web.WebSocketResponse()
    await ws.prepare(request)
    
    try:
        await qemu.start_frame_streaming(ws)
    except Exception as e:
        print(f"Streaming error: {e}")
    finally:
        await ws.close()
    
    return ws

if __name__ == '__main__':
    app = web.Application()
    app.add_routes(routes)
    web.run_app(app, host='127.0.0.1', port=8080)