"""Comando patch para build8bp."""

import re
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 PatchCommand(RichCommand):
    """Comando patch con ejemplos."""
    examples = [
        "build8bp patch --asm-path ./8BP_V43/ASM",
        "export BP8_ASM_PATH=./8BP_V43/ASM && build8bp patch"
    ]

@click.command(cls=PatchCommand)
@click.option(
    '--asm-path',
    type=click.Path(exists=True),
    help=f'Ruta a los scripts ASM (o usa ${DEFAULT_ASM_PATH_ENV})'
)
def patch(asm_path: str):
    """Aplicar parches de sintaxis para ABASM a los archivos ASM."""
    
    asm_dir = get_asm_path(asm_path)
    
    console.print("\n[bold blue]═══════════════════════════════════════[/bold blue]")
    console.print("[bold blue]  BUILD8BP - Patch[/bold blue]")
    console.print("[bold blue]═══════════════════════════════════════[/bold blue]\n")
    
    console.print(f"[cyan]Directorio ASM:[/cyan] {asm_dir}")
    
    # Patrones de corrección
    patches = [
        (r'\band a,', 'and ', 'and a, → and '),
        (r'\bor a,', 'or ', 'or a, → or '),
        (r'\bxor a,', 'xor ', 'xor a, → xor '),
        (r'\bdjnz,', 'djnz ', 'djnz, → djnz '),
        (r'\bifnot\s+(\S+)\s*=\s*(\S+)', r'if \1 != \2', 'ifnot → if !=')
    ]
    
    files_to_patch = [
        "8bitsDePoder_v043_001.asm",
        "make_graficos_mygame.asm"
    ]
    
    total_changes = 0
    
    for filename in files_to_patch:
        file_path = asm_dir / filename
        if not file_path.exists():
            console.print(f"[yellow]⊘ No encontrado: {filename}[/yellow]")
            continue
        
        # Crear backup
        backup_path = file_path.with_suffix('.asm.backup')
        if not backup_path.exists():
            shutil.copy2(file_path, backup_path)
            console.print(f"[green]📋 Backup creado: {backup_path.name}[/green]")
        
        content = file_path.read_text()
        original_content = content
        file_changes = 0
        
        for pattern, replacement, description in patches:
            matches = len(re.findall(pattern, content))
            if matches > 0:
                content = re.sub(pattern, replacement, content)
                file_changes += matches
        
        if file_changes > 0:
            file_path.write_text(content)
            total_changes += file_changes
            console.print(f"[green]✓ {filename}: {file_changes} correcciones[/green]")
        else:
            console.print(f"[dim]• {filename}: Sin cambios[/dim]")
    
    console.print(f"\n[bold green]Total: {total_changes} correcciones aplicadas\n[/bold green]")
