"""Comando rollback para build8bp."""

import shutil
from pathlib import Path
import click
from rich.console import Console
from ..utils import get_asm_path, DEFAULT_ASM_PATH_ENV, RichCommand

console = Console()


class RollbackCommand(RichCommand):
    """Comando rollback con ejemplos."""
    examples = [
        "build8bp rollback --asm-path ./8BP_V43/ASM",
        "export BP8_ASM_PATH=./8BP_V43/ASM && build8bp rollback"
    ]

@click.command(cls=RollbackCommand)
@click.option(
    '--asm-path',
    type=click.Path(exists=True),
    help=f'Ruta a los scripts ASM (o usa ${DEFAULT_ASM_PATH_ENV})'
)
def rollback(asm_path: str):
    """Restaurar archivos ASM desde los backups."""
    
    asm_dir = get_asm_path(asm_path)
    
    console.print("\n[bold blue]═══════════════════════════════════════[/bold blue]")
    console.print("[bold blue]  BUILD8BP - Rollback[/bold blue]")
    console.print("[bold blue]═══════════════════════════════════════[/bold blue]\n")
    
    console.print(f"[cyan]Directorio ASM:[/cyan] {asm_dir}")
    
    # Buscar archivos .backup
    backup_files = list(asm_dir.glob("*.backup"))
    
    if not backup_files:
        console.print("[yellow]No se encontraron archivos de backup[/yellow]")
        return
    
    restored = 0
    for backup_file in backup_files:
        original_file = backup_file.with_suffix('')
        
        shutil.copy2(backup_file, original_file)
        console.print(f"[green]✓ Restaurado: {original_file.name}[/green]")
        restored += 1
    
    console.print(f"\n[bold green]Total: {restored} archivos restaurados\n[/bold green]")
