import os
import sys
import time
import subprocess
from pathlib import Path
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
from rich.console import Console

console = Console()


class HotReloadHandler(FileSystemEventHandler):
    """Handle file changes for hot reload"""
    
    def __init__(self, app_file: str):
        self.app_file = app_file
        self.process = None
        self.last_restart = 0
        self.debounce_seconds = 1
    
    def start_app(self):
        """Start the application"""
        if self.process:
            console.print("[yellow]Stopping app...[/yellow]")
            self.process.terminate()
            self.process.wait()
        
        console.print("[cyan]Starting app...[/cyan]")
        self.process = subprocess.Popen(
            [sys.executable, self.app_file],
            stdout=sys.stdout,
            stderr=sys.stderr
        )
    
    def on_modified(self, event):
        """Handle file modification"""
        if event.is_directory:
            return
        
        if not event.src_path.endswith('.py'):
            return
        
        current_time = time.time()
        if current_time - self.last_restart < self.debounce_seconds:
            return
        
        self.last_restart = current_time
        console.print(f"[yellow]File changed: {event.src_path}[/yellow]")
        console.print("[cyan]Restarting application...[/cyan]")
        self.start_app()


class DevServer:
    """Development server with hot reload"""
    
    def __init__(self, app_file: str = 'app.py', watch_dirs: list = None):
        self.app_file = Path(app_file)
        self.watch_dirs = watch_dirs or ['.']
        self.handler = HotReloadHandler(str(self.app_file))
        self.observer = Observer()
    
    def run(self):
        """Run the development server"""
        if not self.app_file.exists():
            console.print(f"[red]Error: {self.app_file} not found[/red]")
            return
        
        console.print("[green]FeatherOS Development Server[/green]")
        console.print("[cyan]Watching for file changes...[/cyan]")
        
        for watch_dir in self.watch_dirs:
            self.observer.schedule(self.handler, watch_dir, recursive=True)
        
        self.observer.start()
        self.handler.start_app()
        
        try:
            while True:
                time.sleep(1)
        except KeyboardInterrupt:
            console.print("\n[yellow]Stopping development server...[/yellow]")
            self.observer.stop()
            if self.handler.process:
                self.handler.process.terminate()
        
        self.observer.join()


def run_dev_server(app_file: str = 'app.py'):
    """Run the development server with hot reload"""
    server = DevServer(app_file)
    server.run()
