#!/usr/bin/env python3
import os
import sys
import subprocess
import time
import logging
from rich.console import Console
from rich.table import Table
from rich.panel import Panel

# Import menus do TUI
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from tui import menu_build, menu_docs, menu_logs  # pylint: disable=wrong-import-position, import-error

console = Console()

# Logging
logging.basicConfig(
    filename=os.path.expanduser("~/.nfdos.log"),
    level=logging.INFO,
    format="%(asctime)s [%(levelname)s] %(message)s"
)

def clear():
    os.system("clear" if os.name == "posix" else "cls")

def header():
    clear()
    console.print(
        Panel.fit(
            "[bold white]NFDOS — Text User Interface (TUI)[/bold white]",
            title="[cyan]Sistema Operativo que Aprende a Aprender[/cyan]",
            border_style="cyan",
            padding=(1, 2),
        )
    )

def show_menu():
    table = Table(
        title="Menu Principal",
        show_header=True,
        header_style="bold cyan",
        title_style="bold white",
        box=None,
    )
    table.add_column("Opção", justify="center", style="bold yellow")
    table.add_column("Descrição", justify="left", style="white")
    table.add_row("1", "Compilar NFDOS")
    table.add_row("2", "Documentação NFDOS")
    table.add_row("3", "Ver logs do sistema")
    table.add_row("9", "Iniciar V-NFDOS (Holodeck)")
    table.add_row("0", "Sair")
    console.print(table)

def main():
    header()
    console.print("[green]✔[/green] Modo TUI inicializado com sucesso.\n")
    time.sleep(0.5)

    while True:
        show_menu()
        choice = console.input("\n[cyan]nfdos> [/cyan]").strip()

        if choice == "1":
            menu_build.run()
        elif choice == "2":
            menu_docs.run()
        elif choice == "3":
            menu_logs.run()
        elif choice == "9":
            subprocess.run([sys.executable, "vnfdos/neurotron_bridge.py"], check=True)
        elif choice == "0":
            console.print("\n[green]Saindo do NFDOS...[/green]")
            break
        else:
            console.print("[red]Opção inválida![/red]")

        console.input("\n[magenta]Pressione Enter para continuar...[/magenta]")
        header()

if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        console.print("\n[yellow]Encerrado pelo utilizador.[/yellow]\n")

