from rich.console import Console
from rich.table import Table
from pathlib import Path
import os, subprocess, json

console = Console()
BASE_DIR = Path(__file__).resolve().parents[2]
MODULES_FILE = BASE_DIR / "src" / "modules.json"
MODULES_DIR = BASE_DIR / "src" / "modules"

def load_modules():
    if MODULES_FILE.exists():
        with open(MODULES_FILE) as f:
            data = json.load(f)
        return data.get("modules", [])
    return []

def clone_module(mod):
    path = Path(mod["path"])
    if not path.exists():
        console.print(f"[cyan]📦 Clonando {mod['name']}...[/cyan]")
        subprocess.run(["git", "clone", mod["repo"], str(path)], check=True)
    else:
        console.print(f"[yellow]✔ {mod['name']} já existe localmente.[/yellow]")

def update_module(mod):
    path = Path(mod["path"])
    if path.exists():
        console.print(f"[blue]🔄 Atualizando {mod['name']}...[/blue]")
        subprocess.run(["git", "-C", str(path), "pull"], check=True)
    else:
        console.print(f"[red]⚠ Módulo {mod['name']} não encontrado![/red]")

def run_module(mod):
    path = Path(mod["path"])
    if not path.exists():
        console.print(f"[red]❌ Módulo {mod['name']} não encontrado.[/red]")
        return
    console.print(f"[green]🚀 Executando {mod['name']}...[/green]")
    subprocess.run(mod["entrypoint"], cwd=path, shell=True)

def menu():
    modules = load_modules()
    while True:
        console.clear()
        table = Table(title="NEORICALEX – System Manager")
        table.add_column("ID", justify="center")
        table.add_column("Módulo")
        table.add_column("Ação")

        for i, mod in enumerate(modules, start=1):
            table.add_row(str(i), mod["name"], mod["repo"])
        table.add_row("0", "Sair", "")

        console.print(table)
        choice = console.input("[cyan]\nSelecione um módulo> [/cyan]")

        if choice == "0":
            break
        if not choice.isdigit() or int(choice) > len(modules):
            continue

        mod = modules[int(choice)-1]
        console.print(f"[bold yellow]Selecionado:[/bold yellow] {mod['name']}")
        console.print("[1] Executar  [2] Atualizar  [3] Reinstalar  [0] Voltar")
        sub = console.input("[cyan]> [/cyan]")

        if sub == "1":
            run_module(mod)
        elif sub == "2":
            update_module(mod)
        elif sub == "3":
            if Path(mod["path"]).exists():
                subprocess.run(["rm", "-rf", mod["path"]])
            clone_module(mod)
        else:
            continue

if __name__ == "__main__":
    os.makedirs(MODULES_DIR, exist_ok=True)
    menu()
