"""Instruction executor for fake install tool"""

import time
import random
from typing import List
from rich.console import Console
from rich.progress import Progress

from .models import Instruction
from .utils import random_sleep, random_warning_message


console = Console()


def print_log(level: str, message: str):
    """Print log message with appropriate color"""
    if level == "INFO":
        console.print(f"[blue]INFO:[/] {message}")
    elif level == "WARN":
        console.print(f"[yellow]WARN:[/] {message}")
    elif level == "SUCCESS":
        console.print(f"[green]SUCCESS:[/] {message}")
    else:
        console.print(message)


def execute_batch_instructions(sequence: List[Instruction], speed: float, model: dict):
    """Execute a batch of instructions"""
    # Initialize progress bar
    progress = Progress()
    
    # Initialize final success message
    final_success = None
    
    # First pass: process non-install-item instructions
    for instr in sequence:
        if instr.type == "prefix":
            # Print prefix with manager color
            color = model.get("color", "cyan")
            console.print(f"[{color} bold]{instr.template}[/]")
        elif instr.type == "log":
            # Print log message
            print_log(instr.level, instr.template)
            # Random sleep
            time.sleep(random_sleep(0.2, 0.8, speed))
        elif instr.type == "success":
            # Store success message for later
            final_success = instr.template
    
    # Collect install items
    install_items = [instr for instr in sequence if instr.type == "install_item"]
    
    # Process install items with progress bar
    if install_items:
        total = len(install_items)
        # Get progress description
        progress_desc = model.get("progress_desc_template", "Installing packages...")
        if "{num}" in progress_desc:
            progress_desc = progress_desc.format(num=total)
        
        # Start progress bar
        with progress:
            task_id = progress.add_task(progress_desc, total=total)
            
            for item_instr in install_items:
                # Print install item
                if item_instr.data:
                    line_desc = item_instr.template.format(**item_instr.data)
                    console.print(line_desc)
                    
                    # Simulate installation progress with text animation
                    package_name = item_instr.data.get('pkg', item_instr.data.get('image', 'package'))
                    install_duration = random.uniform(3, 5) / speed
                    start_time = time.time()
                    
                    # Animation characters
                    animation_chars = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏']
                    animation_length = len(animation_chars)
                    
                    while time.time() - start_time < install_duration:
                        elapsed = time.time() - start_time
                        progress_percentage = min(100, (elapsed / install_duration) * 100)
                        animation_index = int((elapsed / install_duration) * animation_length) % animation_length
                        
                        # Clear the line and print updated progress
                        console.print(f"\r[cyan]{animation_chars[animation_index]}[/] Installing {package_name}... {progress_percentage:.0f}%", end="")
                        time.sleep(0.1)  # Update every 100ms
                    
                    # Print completion message
                    console.print(f"\r[green]✓[/] Installing {package_name}... 100%")
                    
                    # Print success message
                    if "item_success_template" in model:
                        success_template = model["item_success_template"]
                        success_line = success_template.format(**item_instr.data)
                        console.print(success_line)
                
                # Update main progress bar
                progress.update(task_id, advance=1)
                
                # Randomly insert warning
                if random.random() < 0.1:  # 10% chance
                    warning = random_warning_message()
                    console.print(f"[yellow]{warning}[/]")
                
                # Short sleep between packages
                time.sleep(random_sleep(0.1, 0.3, speed))
    
    # Print final success message
    if final_success:
        console.print(final_success)
    
    # Print separator
    # console.print("─" * 40)
