import sys
import os

def limpar():
    os.system("clear")


def render_uds(texto):
    linhas = texto.split("\n")
    botoes = []

    for linha in linhas:
        l = linha.strip()

        # Título principal
        if l.startswith("JF ") or l.startswith("H1 "):
            print("\n=== " + l.split(" ", 1)[1] + " ===")

        # Subtítulo
        elif l.startswith("JF2 ") or l.startswith("H2 "):
            print("\n-- " + l.split(" ", 1)[1] + " --")

        # Texto
        elif l.startswith("TX ") or l.startswith("P "):
            print(l.split(" ", 1)[1])

        # Botão simples
        elif l.startswith("BTN{") and l.endswith("}"):
            texto_botao = l[4:-1]
            botoes.append(("BTN", texto_botao))
            print(f"[{len(botoes)}] {texto_botao}")

        # Navegação
        elif l.startswith("GO "):
            destino = l.replace("GO ", "")
            botoes.append(("GO", destino))
            print(f"[{len(botoes)}] Ir para -> {destino}")

        # Separador
        elif l == "Hug":
            print("----------------------")

    return botoes


def executar_arquivo(caminho):
    try:
        with open(caminho, "r", encoding="utf-8") as f:
            conteudo = f.read()
    except:
        print("Erro ao abrir arquivo:", caminho)
        input("Enter...")
        return

    while True:
        limpar()
        print(f"=== UDS Runtime ===")
        print(f"Arquivo: {caminho}\n")

        botoes = render_uds(conteudo)

        print("\nEscolha um número ou digite 'sair':")
        escolha = input("> ")

        if escolha.lower() == "sair":
            break

        if escolha.isdigit():
            i = int(escolha) - 1

            if 0 <= i < len(botoes):
                tipo, valor = botoes[i]

                if tipo == "BTN":
                    print(f"\n>> Você clicou: {valor}")
                    input("\n(Enter pra voltar)")

                elif tipo == "GO":
                    executar_arquivo(valor)
            else:
                print("Opção inválida")
                input()
        else:
            print("Entrada inválida")
            input()


def main():
    if len(sys.argv) < 2:
        print("Uso: python uds.run.py arquivo.UDSn")
        return

    arquivo = sys.argv[1]
    executar_arquivo(arquivo)


if __name__ == "__main__":
    main()