"""Command for fake install tool"""

import random
import time
from rich.console import Console

from diona.project.command import CommandModel, CommandParameter
from .generator import generate_batch_instructions
from .executor import execute_batch_instructions
from .config import MANAGER_MODELS
from .constants import DEFAULT_MANAGER, DEFAULT_SPEED, DEFAULT_MIN_PKGS, DEFAULT_MAX_PKGS


console = Console()


class FakeInstallCommand(CommandModel):
    """Fake install command"""
    name = "fakeinstall"
    description = "Simulate infinite package installation process"
    parameters = [
        CommandParameter(
            name="manager",
            type="string",
            description="Package manager type",
            required=False,
            default=DEFAULT_MANAGER
        ),
        CommandParameter(
            name="speed",
            type="float",
            description="Execution speed multiplier",
            required=False,
            default=DEFAULT_SPEED
        ),
        CommandParameter(
            name="min_pkgs",
            type="integer",
            description="Minimum number of packages per batch",
            required=False,
            default=DEFAULT_MIN_PKGS
        ),
        CommandParameter(
            name="max_pkgs",
            type="integer",
            description="Maximum number of packages per batch",
            required=False,
            default=DEFAULT_MAX_PKGS
        ),
    ]
    
    @staticmethod
    def implementation(*args):
        """Command implementation"""
        # Parse arguments
        if len(args) > 0:
            manager = args[0]
        else:
            manager = DEFAULT_MANAGER
        
        if len(args) > 1:
            try:
                speed = float(args[1])
            except ValueError:
                speed = DEFAULT_SPEED
        else:
            speed = DEFAULT_SPEED
        
        if len(args) > 2:
            try:
                min_pkgs = int(args[2])
            except ValueError:
                min_pkgs = DEFAULT_MIN_PKGS
        else:
            min_pkgs = DEFAULT_MIN_PKGS
        
        if len(args) > 3:
            try:
                max_pkgs = int(args[3])
            except ValueError:
                max_pkgs = DEFAULT_MAX_PKGS
        else:
            max_pkgs = DEFAULT_MAX_PKGS
        
        # Validate manager
        if manager not in MANAGER_MODELS:
            console.print(f"[red]Error: Invalid manager '{manager}'. Available managers: {', '.join(MANAGER_MODELS.keys())}[/]")
            return
        
        # Validate package count range
        if min_pkgs < 1:
            min_pkgs = 1
        if max_pkgs < min_pkgs:
            max_pkgs = min_pkgs
        
        # Start simulation
        # console.print("[bold cyan]🚀 无限摸鱼模式启动！[/]")
        batch_count = 0
        
        # Get list of available managers
        available_managers = list(MANAGER_MODELS.keys())
        
        try:
            while True:
                batch_count += 1
                num = random.randint(min_pkgs, max_pkgs)
                
                # Randomly switch manager with 30% probability
                if random.random() < 0.3 and len(available_managers) > 1:
                    manager = random.choice(available_managers)
                    # console.print(f"[dim]{time.strftime('%H:%M:%S')} 切换到 {manager} 包管理器[/]")
                
                # console.print(f"[dim]{time.strftime('%H:%M:%S')} 开始第 {batch_count} 批安装 ({num} 个包)[/]")
                
                # Generate instructions
                sequence = generate_batch_instructions(manager, num)
                # Execute instructions
                execute_batch_instructions(sequence, speed, MANAGER_MODELS[manager])
                
                # Sleep between batches
                sleep_time = random.uniform(1.0, 3.2) / speed
                time.sleep(sleep_time)
        except KeyboardInterrupt:
            # console.print("\n[bold red]👋 摸鱼结束，下班！[/]")
            pass
