#!/usr/bin/env python3
"""
Setup interativo do Fluig MCP Server.
Configura credenciais, testa conexão e registra o servidor no Claude Code.

Visual inspirado em fluig-mcp-plan.html — dark theme, cores ANSI 256.
"""
import os
import sys
import subprocess
import json
import shutil

# ── CORES (ANSI 256 / True Color matching HTML palette) ──────────
R   = "\033[0m"
B   = "\033[1m"
DIM = "\033[2m"
IT  = "\033[3m"

# Palette do fluig-mcp-plan.html
BLUE   = "\033[38;2;79;156;249m"    # --accent  #4f9cf9
PURPLE = "\033[38;2;124;106;247m"   # --accent2 #7c6af7
GREEN  = "\033[38;2;62;207;142m"    # --green   #3ecf8e
AMBER  = "\033[38;2;245;166;35m"    # --amber   #f5a623
CORAL  = "\033[38;2;240;106;80m"    # --coral   #f06a50
PINK   = "\033[38;2;232;121;160m"   # --pink    #e879a0
TEAL   = "\033[38;2;45;212;191m"    # --teal    #2dd4bf
MUTED  = "\033[38;2;107;116;145m"   # --muted   #6b7491
TEXT   = "\033[38;2;226;230;240m"   # --text    #e2e6f0
BG2    = "\033[48;2;19;22;30m"      # --bg2     #13161e
BG3    = "\033[48;2;26;30;42m"      # --bg3     #1a1e2a

# Dots do terminal (estilo macOS)
DOT_R = "\033[38;2;255;95;87m●\033[0m"
DOT_Y = "\033[38;2;255;189;46m●\033[0m"
DOT_G = "\033[38;2;40;200;64m●\033[0m"

COLS = min(shutil.get_terminal_size((80, 24)).columns, 72)


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


# ── DRAWING HELPERS ──────────────────────────────────────────────

def hline(char="─", width=None):
    w = width or COLS
    print(f"{MUTED}{char * w}{R}")


def box_top(width=None):
    w = width or COLS
    print(f"{MUTED}╭{'─' * (w - 2)}╮{R}")


def box_mid(text, width=None, align="center"):
    w = width or COLS
    inner = w - 4
    stripped = _strip_ansi(text)
    if align == "center":
        pad_l = (inner - len(stripped)) // 2
        pad_r = inner - len(stripped) - pad_l
    else:
        pad_l = 1
        pad_r = inner - len(stripped) - 1
    print(f"{MUTED}│{R} {' ' * pad_l}{text}{' ' * pad_r} {MUTED}│{R}")


def box_empty(width=None):
    w = width or COLS
    print(f"{MUTED}│{' ' * (w - 2)}│{R}")


def box_sep(width=None):
    w = width or COLS
    print(f"{MUTED}├{'─' * (w - 2)}┤{R}")


def box_bot(width=None):
    w = width or COLS
    print(f"{MUTED}╰{'─' * (w - 2)}╯{R}")


def _strip_ansi(s):
    import re
    return re.sub(r'\033\[[^m]*m', '', s)


def terminal_bar():
    """Barra estilo terminal macOS."""
    title = f"{MUTED}fluig-dev-mcp · setup{R}"
    pad = COLS - 20
    print(f"  {DOT_R} {DOT_Y} {DOT_G}  {title}")


def section_label(num, text):
    label = f"{BLUE}{B}{num:02d}{R} {MUTED}·{R} {BLUE}{text.upper()}{R}"
    stripped_len = len(f"{num:02d} · {text.upper()}")
    line_len = COLS - stripped_len - 2
    print(f"\n{label} {MUTED}{'─' * max(line_len, 4)}{R}\n")


def badge(text, color=BLUE):
    return f"{color}{B}⌈ {text} ⌋{R}"


def pill(text, color=GREEN):
    return f" {color}●{R} {text}"


def ok(msg):
    print(f"  {GREEN}✓{R}  {msg}")


def warn(msg):
    print(f"  {AMBER}⚠{R}  {msg}")


def erro(msg):
    print(f"  {CORAL}✗{R}  {msg}")


def info(msg):
    print(f"  {BLUE}→{R}  {msg}")


def ask(prompt, default="", secret=False):
    sufixo = f" {MUTED}[{default}]{R}" if default else ""
    try:
        if secret:
            import getpass
            valor = getpass.getpass(f"  {BLUE}›{R} {B}{prompt}{R}{sufixo}: ")
        else:
            valor = input(f"  {BLUE}›{R} {B}{prompt}{R}{sufixo}: ").strip()
    except (KeyboardInterrupt, EOFError):
        print(f"\n\n  {AMBER}Setup cancelado.{R}\n")
        sys.exit(0)
    return valor if valor else default


def confirmar(prompt):
    try:
        resp = input(f"\n  {PURPLE}?{R} {B}{prompt}{R} {MUTED}(s/n){R} ").strip().lower()
    except (KeyboardInterrupt, EOFError):
        return False
    return resp in ("s", "sim", "y", "yes")


# ── BANNER ───────────────────────────────────────────────────────

def banner():
    logo = f"""{PURPLE}{B}
    ╔═══╗ ╔╗       ╔╗        ╔═╗╔═╗ ╔═══╗ ╔═══╗
    ║╔══╝ ║║       ╠╣  ╔══╗  ║║╚╝║║ ║╔═╗║ ║╔═╗║
    ║╚══╗ ║║ ╔╗╔╗ ╔╣║ ╔╝╔╗╗ ║╔╗╔╗║ ║║ ╚╝ ║╚═╝║
    ║╔══╝ ║║ ║║║║ ╠╣║ ║╔╝║║ ║║║║║║ ║║ ╔╗ ║╔══╝
    ║║    ║╚╗║╚╝║ ║║╚╗║╚═╝║ ║║║║║║ ║╚═╝║ ║║
    ╚╝    ╚═╝╚══╝ ╚╝═╝╚═══╝ ╚╝╚╝╚╝ ╚═══╝ ╚╝{R}"""

    tag = f"{BLUE}Setup Wizard{R} {MUTED}·{R} {TEAL}v2.0{R}"
    sub = f"{MUTED}Servidor MCP para desenvolvimento TOTVS Fluig{R}"
    fs  = f"{DIM}by Future Station{R}"

    print(logo)
    print()
    print(f"    {tag}  {fs}")
    print(f"    {sub}")
    print()


def banner_mini():
    print(f"\n  {PURPLE}{B}Fluig MCP{R} {MUTED}·{R} {BLUE}Setup{R}\n")


# ── STEP DISPLAY ─────────────────────────────────────────────────

def step_header(n, total, titulo):
    bar_full = COLS - 4
    filled = int(bar_full * n / total)
    empty = bar_full - filled

    print()
    box_top()
    box_mid(f"{BLUE}{B}Passo {n}/{total}{R} {MUTED}—{R} {B}{titulo}{R}")
    box_mid(f"{GREEN}{'█' * filled}{MUTED}{'░' * empty}{R}")
    box_bot()
    print()


# ── PASSO 1: DEPENDENCIAS ────────────────────────────────────────

def passo_dependencias():
    step_header(1, 5, "Verificando dependencias")

    pacotes = {
        "mcp":     ("mcp>=1.26.0",       "FastMCP SDK"),
        "httpx":   ("httpx>=0.27.0",      "HTTP async client"),
        "authlib": ("authlib>=1.3.0",     "OAuth 1.0 signing"),
        "dotenv":  ("python-dotenv>=1.0.0", "Env configuration"),
    }

    faltando = []

    for pkg, (pip_name, desc) in pacotes.items():
        try:
            __import__(pkg)
            ok(f"{TEAL}{pkg:<12}{R} {MUTED}{desc}{R}")
        except ImportError:
            faltando.append(pkg)
            warn(f"{AMBER}{pkg:<12}{R} {MUTED}{desc} — nao instalado{R}")

    if faltando:
        print()
        if confirmar("Instalar dependencias faltando agora?"):
            print()
            req = os.path.join(os.path.dirname(__file__), "requirements.txt")
            resultado = subprocess.run(
                [sys.executable, "-m", "pip", "install", "-r", req],
                capture_output=True, text=True,
            )
            if resultado.returncode == 0:
                ok("Dependencias instaladas com sucesso!")
            else:
                erro("Falha ao instalar. Execute manualmente:")
                info(f"pip install -r requirements.txt")
                info(resultado.stderr[-300:] if resultado.stderr else "")
        else:
            warn("Instale manualmente: pip install -r requirements.txt")


# ── PASSO 2: CREDENCIAIS ─────────────────────────────────────────

def passo_credenciais():
    step_header(2, 5, "Configuracao do servidor Fluig")

    box_top()
    box_mid(f"{AMBER}{B}Voce precisara de:{R}", align="left")
    box_sep()
    box_mid(f"{MUTED}URL do servidor Fluig{R}", align="left")
    box_mid(f"{MUTED}Consumer Key + Consumer Secret  {DIM}(OAuth App){R}", align="left")
    box_mid(f"{MUTED}Access Token + Token Secret     {DIM}(Painel OAuth){R}", align="left")
    box_sep()
    box_mid(f"{DIM}Painel de Controle → OAuth → Aplicacoes{R}", align="left")
    box_bot()
    print()

    servidor = ask("URL do servidor Fluig", "https://seu-servidor.fluig.com")
    servidor = servidor.rstrip("/")

    print()
    print(f"  {MUTED}── Credenciais OAuth 1.0 ──{R}\n")
    consumer_key    = ask("Consumer Key")
    consumer_secret = ask("Consumer Secret", secret=True)
    access_token    = ask("Access Token")
    token_secret    = ask("Token Secret", secret=True)

    return {
        "FLUIG_SERVER": servidor,
        "FLUIG_CONSUMER_KEY": consumer_key,
        "FLUIG_CONSUMER_SECRET": consumer_secret,
        "FLUIG_ACCESS_TOKEN": access_token,
        "FLUIG_TOKEN_SECRET": token_secret,
    }


# ── PASSO 3: TESTAR CONEXAO ──────────────────────────────────────

def passo_testar_conexao(config):
    step_header(3, 5, "Testando conexao com o Fluig")

    try:
        import httpx
        from authlib.integrations.httpx_client import OAuth1Auth

        auth = OAuth1Auth(
            client_id=config["FLUIG_CONSUMER_KEY"],
            client_secret=config["FLUIG_CONSUMER_SECRET"],
            token=config["FLUIG_ACCESS_TOKEN"],
            token_secret=config["FLUIG_TOKEN_SECRET"],
        )

        url = f"{config['FLUIG_SERVER']}/api/v2/datasets"
        info(f"{MUTED}Conectando em {url[:55]}...{R}")
        print()

        resp = httpx.get(url, auth=auth, timeout=15, params={"limit": 1})

        if resp.status_code == 200:
            ok(f"Conexao estabelecida! {GREEN}HTTP {resp.status_code}{R}")
            try:
                dados = resp.json()
                if isinstance(dados, dict) and "content" in dados:
                    ok(f"Datasets acessiveis no servidor")
                elif isinstance(dados, list):
                    ok(f"{len(dados)} datasets encontrados")
            except Exception:
                pass
            return True
        elif resp.status_code == 401:
            erro(f"HTTP 401 — Credenciais invalidas ou expiradas")
            warn("Verifique Consumer Key/Secret e Access Token/Secret")
            return False
        elif resp.status_code == 403:
            warn(f"HTTP 403 — Conexao OK mas sem permissao neste endpoint")
            return True
        else:
            warn(f"HTTP {resp.status_code} — Resposta inesperada")
            return False

    except Exception as e:
        if "Connect" in type(e).__name__:
            erro(f"Nao foi possivel conectar em: {config['FLUIG_SERVER']}")
            warn("Verifique se a URL esta correta e o servidor acessivel")
        elif "Timeout" in type(e).__name__:
            erro("Timeout — servidor demorou mais de 15s para responder")
        elif "Import" in type(e).__name__:
            warn("httpx/authlib nao disponiveis. Instale as dependencias.")
        else:
            erro(f"Erro: {e}")
        return False


# ── PASSO 4: SALVAR E REGISTRAR ──────────────────────────────────

def passo_salvar_e_registrar(config):
    step_header(4, 5, "Salvando configuracao")

    # Salvar .env
    env_path = os.path.join(os.path.dirname(__file__), ".env")
    conteudo = "\n".join([f"{k}={v}" for k, v in config.items()])

    with open(env_path, "w", encoding="utf-8") as f:
        f.write(conteudo + "\n")

    ok(f".env salvo em {TEAL}{env_path}{R}")

    # Registrar no Claude Code
    print()
    server_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "server.py")
    cmd = f'claude mcp add fluig -- {sys.executable} "{server_path}"'

    if confirmar("Registrar automaticamente no Claude Code?"):
        resultado = subprocess.run(
            ["claude", "mcp", "add", "fluig", "--", sys.executable, server_path],
            capture_output=True, text=True,
        )
        if resultado.returncode == 0:
            ok("Registrado no Claude Code!")
        else:
            if "already" in resultado.stderr.lower() or "exists" in resultado.stderr.lower():
                warn("MCP 'fluig' ja registrado (nao alterado)")
                info("Para atualizar: claude mcp remove fluig && ...")
            else:
                warn("Registro automatico falhou")
                info("Registre manualmente:")
    else:
        info("Para registrar manualmente:")

    print(f"\n  {MUTED}{cmd}{R}\n")


# ── PASSO 5: SKILLS ──────────────────────────────────────────────

def passo_instalar_skills():
    step_header(5, 5, "Instalar Skills Fluig")

    SKILLS = [
        ("fluig-datasets",           "Datasets customizados", GREEN),
        ("fluig-eventos-formulario",  "Eventos de formulario", PINK),
        ("fluig-eventos-processo",    "Eventos de processo", TEAL),
        ("fluig-formularios",         "Formularios HTML + Style Guide", CORAL),
        ("fluig-integracoes",         "Integracoes REST / ServiceManager", AMBER),
        ("fluig-process-reader",      "Leitura de arquivos .process", BLUE),
        ("fluig-scripts-avancados",   "Scripts avancados (subprocesso, etc.)", PURPLE),
        ("fluig-widgets",             "Widgets WCM + SuperWidget", TEAL),
    ]

    DESTINOS = [
        ("claude_global",   "Claude Code global",    f"~/.claude/skills/",       GREEN),
        ("claude_projeto",  "Claude Code projeto",   f"{{projeto}}/.claude/skills/", BLUE),
        ("codex_global",    "Codex CLI global",      f"~/.codex/instructions.md",    AMBER),
        ("codex_projeto",   "Codex CLI projeto",     f"{{projeto}}/.codex/",         CORAL),
        ("copilot",         "GitHub Copilot",        f".github/copilot-instructions.md", PURPLE),
        ("cursor",          "Cursor",                f".cursor/rules/*.mdc",         PINK),
    ]

    # Skills grid
    box_top()
    box_mid(f"{B}Skills disponiveis{R}")
    box_sep()

    for i, (nome, desc, cor) in enumerate(SKILLS, 1):
        num = f"{cor}{B}{i}{R}"
        name_display = f"{cor}{nome}{R}"
        desc_display = f"{MUTED}{desc}{R}"
        box_mid(f"  {num}  {name_display:<45} {desc_display}", align="left")

    box_bot()
    print()

    resp_skills = ask(
        "Quais instalar? (numeros, 'todas' ou Enter p/ pular)",
        default="",
    )
    if not resp_skills.strip():
        info("Skills ignoradas.")
        return

    # Selecionar skills
    if resp_skills.strip().lower() == "todas":
        skills_sel = [s[0] for s in SKILLS]
    else:
        try:
            indices = [int(x.strip()) - 1 for x in resp_skills.split(",")]
            skills_sel = [SKILLS[i][0] for i in indices if 0 <= i < len(SKILLS)]
        except (ValueError, IndexError):
            warn("Selecao invalida — pulando.")
            return

    if not skills_sel:
        warn("Nenhuma skill selecionada.")
        return

    # Destinos grid
    print()
    box_top()
    box_mid(f"{B}Destinos de instalacao{R}")
    box_sep()

    for i, (key, name, path, cor) in enumerate(DESTINOS, 1):
        num = f"{cor}{B}{i}{R}"
        name_d = f"{cor}{name}{R}"
        path_d = f"{MUTED}{path}{R}"
        box_mid(f"  {num}  {name_d:<40} {path_d}", align="left")

    box_bot()
    print()

    resp_dest = ask(
        "Em quais destinos? (numeros, 'todos')",
        default="1",
    )

    if resp_dest.strip().lower() == "todos":
        destinos_sel = [d[0] for d in DESTINOS]
    else:
        try:
            indices = [int(x.strip()) - 1 for x in resp_dest.split(",")]
            destinos_sel = [DESTINOS[i][0] for i in indices if 0 <= i < len(DESTINOS)]
        except (ValueError, IndexError):
            warn("Selecao invalida — usando claude_global.")
            destinos_sel = ["claude_global"]

    # Caminho de projeto
    precisam_projeto = {"claude_projeto", "codex_projeto", "copilot", "cursor"}
    caminho_projeto = ""
    if any(d in precisam_projeto for d in destinos_sel):
        caminho_projeto = ask("Caminho absoluto do projeto", default=os.getcwd())

    # Agente e regras
    instalar_agente = False
    instalar_regras = False
    if "claude_global" in destinos_sel or "claude_projeto" in destinos_sel:
        print()
        instalar_agente = confirmar("Instalar tambem o agente fluig-developer?")
        instalar_regras = confirmar("Instalar tambem as regras ES5 / nomenclatura / seguranca?")

    # Executar
    print()
    info("Instalando skills...")
    print()

    try:
        sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
        from tools.dev.skills_installer import (
            _listar_skills_disponiveis,
            _instalar_claude_code, _instalar_codex,
            _instalar_copilot, _instalar_cursor,
            _instalar_agente, _instalar_regras as _inst_regras,
            _skills_dir,
        )
        from pathlib import Path

        home = str(Path.home())
        skills_disponiveis = {s["nome"]: s["caminho"] for s in _listar_skills_disponiveis()}

        if not skills_disponiveis:
            warn(f"Pasta de skills nao encontrada: {_skills_dir()}")
            warn("Configure FLUIG_SKILLS_SOURCE no .env")
            return

        for skill_nome in skills_sel:
            if skill_nome not in skills_disponiveis:
                warn(f"Skill '{skill_nome}' nao encontrada — pulando")
                continue

            skill_path = skills_disponiveis[skill_nome]
            print(f"  {TEAL}{B}{skill_nome}{R}")

            for dest in destinos_sel:
                try:
                    if dest == "claude_global":
                        r = _instalar_claude_code(skill_nome, skill_path, os.path.join(home, ".claude"))
                        ok(f"claude_global   {r}")
                    elif dest == "claude_projeto" and caminho_projeto:
                        r = _instalar_claude_code(skill_nome, skill_path, os.path.join(caminho_projeto, ".claude"))
                        ok(f"claude_projeto  {r}")
                    elif dest == "codex_global":
                        r = _instalar_codex(skill_nome, skill_path, os.path.join(home, ".codex"))
                        ok(f"codex_global    {r}")
                    elif dest == "codex_projeto" and caminho_projeto:
                        r = _instalar_codex(skill_nome, skill_path, os.path.join(caminho_projeto, ".codex"))
                        ok(f"codex_projeto   {r}")
                    elif dest == "copilot" and caminho_projeto:
                        r = _instalar_copilot(skill_nome, skill_path, caminho_projeto)
                        ok(f"copilot         {r}")
                    elif dest == "cursor" and caminho_projeto:
                        r = _instalar_cursor(skill_nome, skill_path, caminho_projeto)
                        ok(f"cursor          {r}")
                except Exception as e:
                    erro(f"{dest}: {e}")

        # Agente e regras
        if instalar_agente:
            print(f"\n  {PURPLE}{B}Agente fluig-developer{R}")
            if "claude_global" in destinos_sel:
                from tools.dev.skills_installer import _instalar_agente as _ag
                ok("global   " + _ag(os.path.join(home, ".claude")))
            if "claude_projeto" in destinos_sel and caminho_projeto:
                from tools.dev.skills_installer import _instalar_agente as _ag
                ok("projeto  " + _ag(os.path.join(caminho_projeto, ".claude")))

        if instalar_regras:
            print(f"\n  {PURPLE}{B}Regras{R}")
            if "claude_global" in destinos_sel:
                for r in _inst_regras(os.path.join(home, ".claude")):
                    ok("global   " + r)
            if "claude_projeto" in destinos_sel and caminho_projeto:
                for r in _inst_regras(os.path.join(caminho_projeto, ".claude")):
                    ok("projeto  " + r)

        print()
        ok(f"{GREEN}{B}{len(skills_sel)} skill(s) instalada(s)!{R}")

    except Exception as e:
        erro(f"Erro na instalacao: {e}")
        import traceback
        warn(traceback.format_exc()[-400:])


# ── RESUMO FINAL ─────────────────────────────────────────────────

def resumo_final(config, conexao_ok):
    # Architecture boxes (like HTML layers)
    print()
    box_top()
    box_empty()
    box_mid(f"{GREEN}{B}Setup Concluido!{R}")
    box_empty()
    box_sep()

    # Connection info
    server_display = config["FLUIG_SERVER"]
    key_display = config["FLUIG_CONSUMER_KEY"][:8] + "********" if config["FLUIG_CONSUMER_KEY"] else "—"
    conn_display = f"{GREEN}{B}Conectado{R}" if conexao_ok else f"{AMBER}Nao testada{R}"

    box_mid(f"{MUTED}Servidor{R}  {TEAL}{server_display}{R}", align="left")
    box_mid(f"{MUTED}OAuth{R}     {MUTED}{key_display}{R}", align="left")
    box_mid(f"{MUTED}Conexao{R}   {conn_display}", align="left")

    box_sep()

    # Tools summary (styled like HTML layer cards)
    box_mid(f"{B}Tools disponiveis{R}")
    box_sep()

    tools = [
        (GREEN,  "28", "Dev Tools",  "scaffold, validacao, knowledge, skills"),
        (BLUE,   "55", "API Core",   "datasets, documentos, workflow, usuarios"),
        (AMBER,  "37", "Extended",   "cards, forms, alertas, busca, grupos"),
        (PINK,   "11", "Social",     "comunidades, posts, artigos, favoritos"),
        (PURPLE, "12", "Admin",      "config, permissoes, roles, jobs"),
    ]

    for color, count, name, desc in tools:
        line = f"  {color}{B}{count:>3}{R}  {color}{name:<12}{R} {MUTED}{desc}{R}"
        box_mid(line, align="left")

    box_sep()

    total_line = f"{GREEN}{B}~142 tools no total{R}"
    box_mid(total_line)

    box_sep()

    # Architecture diagram (like HTML two-layer card)
    box_mid(f"{B}Arquitetura{R}")
    box_sep()

    box_mid(f"  {BLUE}■ Camada 1 · Dev Tools{R}    {MUTED}Style Guide, scaffold, knowledge{R}", align="left")
    box_mid(f"    {MUTED}Sempre ativas — nao precisam de OAuth{R}", align="left")
    box_mid(f"", align="left")
    box_mid(f"  {AMBER}■ Camada 2 · API Tools{R}   {MUTED}REST Fluig via OAuth 1.0{R}", align="left")
    box_mid(f"    {MUTED}Ativadas quando credenciais configuradas{R}", align="left")

    box_sep()
    box_mid(f"{MUTED}Reinicie o Claude Code para carregar as tools.{R}")
    box_empty()
    box_bot()

    # Footer
    print()
    print(f"  {MUTED}Fluig Dev MCP · Future Station · {PURPLE}@future-station/fluig-mcp{R}")
    print()


# ── TELA INICIAL ─────────────────────────────────────────────────

def tela_inicial():
    """Tela de boas-vindas estilo terminal do HTML."""
    banner()

    # Terminal demo box
    print(f"  {DOT_R} {DOT_Y} {DOT_G}  {MUTED}fluig-dev-mcp · preview{R}")
    box_top(COLS - 2)

    lines = [
        (f"{GREEN}›{R}", f"mcp fluig-dev setup"),
        (None,           f"{GREEN}✓{R} Dependencias verificadas"),
        (None,           f"{GREEN}✓{R} Credenciais OAuth configuradas"),
        (None,           f"{GREEN}✓{R} Conexao testada com sucesso"),
        (None,           f"{TEAL}  ~142 tools carregadas (Dev + API){R}"),
        ("",             ""),
        (f"{GREEN}›{R}", f"claude {DIM}\"lista os datasets do processo Admissao\"{R}█"),
    ]

    for prompt, text in lines:
        if prompt is None:
            box_mid(f"  {text}", width=COLS - 2, align="left")
        elif prompt == "":
            box_empty(width=COLS - 2)
        else:
            box_mid(f"  {prompt} {text}", width=COLS - 2, align="left")

    box_bot(COLS - 2)
    print()

    print(f"  {MUTED}Este assistente ira configurar o Fluig MCP Server.{R}")
    print(f"  {MUTED}Pressione Ctrl+C a qualquer momento para cancelar.{R}")


# ── MAIN ─────────────────────────────────────────────────────────

def main():
    clr()
    tela_inicial()

    if not confirmar("Iniciar configuracao?"):
        print(f"\n  {AMBER}Cancelado.{R}\n")
        return

    clr()
    banner_mini()

    # Passo 1
    passo_dependencias()

    clr()
    banner_mini()

    # Passo 2
    config = passo_credenciais()

    clr()
    banner_mini()

    # Passo 3
    conexao_ok = False
    if all(config.values()):
        conexao_ok = passo_testar_conexao(config)
        if not conexao_ok:
            if not confirmar("Conexao falhou. Salvar mesmo assim?"):
                warn("Corrija as credenciais e execute novamente.")
                print()
                return
    else:
        warn("Campos vazios — pulando teste de conexao")

    # Passo 4
    passo_salvar_e_registrar(config)

    clr()
    banner_mini()

    # Passo 5
    passo_instalar_skills()

    # Resumo
    clr()
    banner_mini()
    resumo_final(config, conexao_ok)


if __name__ == "__main__":
    main()
