/**
 * Wizard principal do Fluig MCP — orquestrador dos steps
 */

const { R, B, DIM, GREEN, AMBER, BLUE, TEAL, PINK, PURPLE, MUTED } = require("./colors");
const {
  banner, bannerMini, print,
  boxTop, boxMid, boxEmpty, boxSep, boxBot,
  DOT_R, DOT_Y, DOT_G, COLS,
  ok, warn, info,
} = require("./banner");
const { checkPython } = require("./steps/check-python");
const { collectCredentials } = require("./steps/credentials");
const { testConnection } = require("./steps/connection");
const { saveConfig } = require("./steps/save-config");
const { selectAndInstallSkills } = require("./steps/skills");

function clr() {
  process.stderr.write(process.platform === "win32" ? "\x1bc" : "\x1b[2J\x1b[H");
}

function telaInicial() {
  banner();

  // Terminal demo box
  print(`  ${DOT_R} ${DOT_Y} ${DOT_G}  ${MUTED}fluig-dev-mcp \u00B7 preview${R}`);
  boxTop(COLS - 2);

  const lines = [
    [`${GREEN}\u203A${R}`, "mcp fluig-dev setup"],
    [null,                  `${GREEN}\u2713${R} Dependencias verificadas`],
    [null,                  `${GREEN}\u2713${R} Credenciais OAuth configuradas`],
    [null,                  `${GREEN}\u2713${R} Conexao testada com sucesso`],
    [null,                  `${TEAL}  ~142 tools carregadas (Dev + API)${R}`],
    ["",                    ""],
    [`${GREEN}\u203A${R}`, `claude ${DIM}"lista os datasets do processo Admissao"${R}\u2588`],
  ];

  for (const [prompt, text] of lines) {
    if (prompt === null) {
      boxMid(`  ${text}`, COLS - 2, "left");
    } else if (prompt === "") {
      boxEmpty(COLS - 2);
    } else {
      boxMid(`  ${prompt} ${text}`, COLS - 2, "left");
    }
  }

  boxBot(COLS - 2);
  print("");

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

function resumoFinal(config, conexaoOk, skillsResult) {
  print("");
  boxTop();
  boxEmpty();
  boxMid(`${GREEN}${B}Setup Concluido!${R}`);
  boxEmpty();
  boxSep();

  // Connection info
  const serverDisplay = config.FLUIG_SERVER || "\u2014";
  const keyDisplay = config.FLUIG_CONSUMER_KEY
    ? config.FLUIG_CONSUMER_KEY.substring(0, 8) + "********"
    : "\u2014";
  const connDisplay = conexaoOk
    ? `${GREEN}${B}Conectado${R}`
    : `${AMBER}Nao testada${R}`;

  boxMid(`${MUTED}Servidor${R}  ${TEAL}${serverDisplay}${R}`, undefined, "left");
  boxMid(`${MUTED}OAuth${R}     ${MUTED}${keyDisplay}${R}`, undefined, "left");
  boxMid(`${MUTED}Conexao${R}   ${connDisplay}`, undefined, "left");

  boxSep();

  // Tools summary
  boxMid(`${B}Tools disponiveis${R}`);
  boxSep();

  const 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 (const [color, count, name, desc] of tools) {
    boxMid(`  ${color}${B}${count.padStart(3)}${R}  ${color}${name.padEnd(12)}${R} ${MUTED}${desc}${R}`, undefined, "left");
  }

  boxSep();
  boxMid(`${GREEN}${B}~142 tools no total${R}`);
  boxSep();

  // Skills instaladas
  if (skillsResult && skillsResult.installed && skillsResult.installed.length) {
    boxMid(`${B}Skills instaladas: ${GREEN}${skillsResult.installed.length}${R}`);
  }

  boxSep();

  // Architecture
  boxMid(`${B}Arquitetura${R}`);
  boxSep();
  boxMid(`  ${BLUE}\u25A0 Camada 1 \u00B7 Dev Tools${R}    ${MUTED}Style Guide, scaffold, knowledge${R}`, undefined, "left");
  boxMid(`    ${MUTED}Sempre ativas \u2014 nao precisam de OAuth${R}`, undefined, "left");
  boxMid("", undefined, "left");
  boxMid(`  ${AMBER}\u25A0 Camada 2 \u00B7 API Tools${R}   ${MUTED}REST Fluig via OAuth 1.0${R}`, undefined, "left");
  boxMid(`    ${MUTED}Ativadas quando credenciais configuradas${R}`, undefined, "left");

  boxSep();
  boxMid(`${MUTED}Reinicie o Claude Code para carregar as tools.${R}`);
  boxEmpty();
  boxBot();

  print("");
  print(`  ${MUTED}Fluig Dev MCP \u00B7 Future Station \u00B7 ${PURPLE}@future-station/fluig-mcp${R}`);
  print("");
}

async function runWizard() {
  const { default: inquirer } = await import("inquirer");

  clr();
  telaInicial();

  const { start } = await inquirer.prompt([
    {
      type: "confirm",
      name: "start",
      message: "Iniciar configuracao?",
      default: true,
    },
  ]);

  if (!start) {
    print(`\n  ${AMBER}Cancelado.${R}\n`);
    return;
  }

  clr();
  bannerMini();

  // Step 0: Python check
  const pythonInfo = checkPython();

  clr();
  bannerMini();

  // Step 1: Credenciais
  const config = await collectCredentials();

  clr();
  bannerMini();

  // Step 2: Testar conexao
  let conexaoOk = false;
  if (config.FLUIG_SERVER && config.FLUIG_CONSUMER_KEY) {
    conexaoOk = await testConnection(config);
    if (!conexaoOk) {
      const { continuar } = await inquirer.prompt([
        {
          type: "confirm",
          name: "continuar",
          message: "Conexao falhou. Salvar mesmo assim?",
          default: false,
        },
      ]);
      if (!continuar) {
        warn("Corrija as credenciais e execute novamente.");
        print("");
        return;
      }
    }
  } else {
    warn("Campos vazios — pulando teste de conexao");
  }

  // Step 3: Salvar
  await saveConfig(config, pythonInfo);

  clr();
  bannerMini();

  // Step 4: Skills
  const skillsResult = await selectAndInstallSkills();

  // Resumo
  clr();
  bannerMini();
  resumoFinal(config, conexaoOk, skillsResult);
}

module.exports = { runWizard };
