import os
import requests
import zipfile
from pathlib import Path
from rich.console import Console
from rich.progress import Progress

console = Console()


class PluginInstaller:
    def __init__(self):
        self.server_url = os.environ.get('PLUGIN_SERVER_URL', 'http://localhost:5000/api')
        self.plugins_dir = Path.home() / '.feather' / 'plugins'
        self.plugins_dir.mkdir(parents=True, exist_ok=True)
    
    def install(self, plugin_name: str):
        """Download and install a plugin from the server"""
        console.print(f"[cyan]Installing plugin: {plugin_name}[/cyan]")
        
        try:
            response = requests.get(f"{self.server_url}/plugins/{plugin_name}/download")
            
            if response.status_code == 404:
                console.print(f"[red]Plugin '{plugin_name}' not found on server[/red]")
                return False
            
            if response.status_code != 200:
                console.print(f"[red]Failed to download plugin: HTTP {response.status_code}[/red]")
                return False
            
            plugin_path = self.plugins_dir / plugin_name
            plugin_path.mkdir(parents=True, exist_ok=True)
            
            zip_path = plugin_path / f"{plugin_name}.zip"
            with open(zip_path, 'wb') as f:
                f.write(response.content)
            
            with zipfile.ZipFile(zip_path, 'r') as zip_ref:
                zip_ref.extractall(plugin_path)
            
            zip_path.unlink()
            
            console.print(f"[green]✓ Plugin '{plugin_name}' installed successfully[/green]")
            return True
            
        except requests.exceptions.ConnectionError:
            console.print(f"[yellow]Warning: Could not connect to plugin server at {self.server_url}[/yellow]")
            console.print(f"[yellow]Plugin '{plugin_name}' will be loaded from local plugins/ directory if available[/yellow]")
            return False
        except Exception as e:
            console.print(f"[red]Error installing plugin: {e}[/red]")
            return False
