from rich.console import Console
import os
import shutil
import subprocess
import time
from pathlib import Path

console = Console()

def save_current_config(ctng_dir: Path, aux_dir: Path):
    """
    Salva o .config atual da toolchain em welcome/nfdos/aux/.config
    """
    src = ctng_dir / ".config"
    dst = aux_dir / ".config"

    if src.exists():
        try:
            shutil.copyfile(src, dst)
            console.print(f"[green]✔ .config atual salvo em {dst}[/green]")
        except Exception as e:
            console.print(f"[red]✖ Falha ao salvar .config: {e}[/red]")
    else:
        console.print("[yellow]⚠ Nenhum .config encontrado para salvar.[/yellow]")


def apply_profile_config(aux_dir: Path, ctng_dir: Path):
    """
    Se existir um .config personalizado em aux, aplica-o antes da build.
    """
    aux_config = aux_dir / ".config"
    if aux_config.exists():
        try:
            shutil.copyfile(aux_config, ctng_dir / ".config")
            console.print("[green]✔ Aplicado .config personalizado do perfil NFDOS.[/green]")
        except Exception as e:
            console.print(f"[red]✖ Falha ao aplicar .config personalizado: {e}[/red]")
    else:
        console.print("[yellow]⚠ Nenhum .config personalizado encontrado em aux/.[/yellow]")

def sanitize_env():
    for var in ["CFLAGS", "CPPFLAGS", "LDFLAGS", "CXXFLAGS"]:
        if var in os.environ:
            del os.environ[var]
            console.print(f"[yellow]Removido {var} do ambiente para evitar conflitos.[/yellow]")

def run():
    while True:
        console.clear()
        console.rule("[bold yellow]Bootloader NFDOS[/bold yellow]")
        console.print("1. Compilar Bootloader e gerar ISO")
        console.print("2. Gerir Bootloader (limpar)")
        console.print("0. Voltar")

        choice = console.input("\n[cyan]nfdos> [/cyan]")

        base_dir = Path(__file__).resolve().parents[1]
        bootloader_dir = base_dir / "_nfdos" / "bootloader"
        os.chdir(bootloader_dir)

        if choice == "1":
            os.system("make run")

        elif choice == "2":
            console.print("[yellow]Limpando build anterior...[/yellow]")
            subprocess.run(["make", "clean"], check=True)
            console.print("[green]✔ Bootloader limpo.[/green]")
            time.sleep(5)

        elif choice == "0":
            break
        else:
            console.print("[red]Opção inválida![/red]")

        time.sleep(1)


