/**
 * Step 4 — Selecionar e instalar skills
 */

const os = require("os");
const path = require("path");
const { R, B, DIM, GREEN, AMBER, TEAL, PURPLE, MUTED } = require("../colors");
const { stepHeader, ok, warn, erro, info, print } = require("../banner");
const { DESTINOS, SKILLS_INFO } = require("../skills/destinations");
const {
  findSkillsDir,
  listAvailableSkills,
  installClaudeCode,
  installCodex,
  installCopilot,
  installCursor,
  installAgent,
  installRules,
} = require("../skills/installer");

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

  stepHeader(5, 5, "Instalar Skills Fluig");

  const skillsDir = findSkillsDir();
  if (!skillsDir) {
    warn("Pasta de skills nao encontrada.");
    info("Configure FLUIG_SKILLS_SOURCE no .env se a pasta estiver em outro local.");
    return { installed: [] };
  }

  const availableSkills = listAvailableSkills();
  if (!availableSkills.length) {
    warn("Nenhuma skill disponivel para instalacao.");
    return { installed: [] };
  }

  const skillsMap = {};
  for (const s of availableSkills) {
    skillsMap[s.nome] = s.caminho;
  }

  // Selecionar skills
  const { selectedSkills } = await inquirer.prompt([
    {
      type: "checkbox",
      name: "selectedSkills",
      message: "Quais skills instalar?",
      choices: SKILLS_INFO.map((s) => ({
        name: `${s.nome}  ${DIM}${s.desc}${R}`,
        value: s.nome,
        checked: true,
      })),
    },
  ]);

  if (!selectedSkills.length) {
    info("Nenhuma skill selecionada — pulando.");
    return { installed: [] };
  }

  // Selecionar destinos
  const { selectedDests } = await inquirer.prompt([
    {
      type: "checkbox",
      name: "selectedDests",
      message: "Em quais destinos instalar?",
      choices: DESTINOS.map((d) => ({
        name: `${d.name}  ${DIM}${d.pathTemplate}${R}`,
        value: d.key,
        checked: d.key === "claude_global",
      })),
    },
  ]);

  if (!selectedDests.length) {
    info("Nenhum destino selecionado — pulando.");
    return { installed: [] };
  }

  // Caminho do projeto (se necessario)
  const needsProject = selectedDests.some((dk) => {
    const d = DESTINOS.find((x) => x.key === dk);
    return d && d.needsProject;
  });

  let projectPath = "";
  if (needsProject) {
    const resp = await inquirer.prompt([
      {
        type: "input",
        name: "projectPath",
        message: "Caminho absoluto do projeto",
        default: process.cwd(),
      },
    ]);
    projectPath = resp.projectPath.trim();
  }

  // Agente e regras (se Claude Code selecionado)
  const claudeSelected = selectedDests.includes("claude_global") || selectedDests.includes("claude_projeto");
  let doAgent = false;
  let doRules = false;

  if (claudeSelected) {
    const extras = await inquirer.prompt([
      {
        type: "confirm",
        name: "agent",
        message: "Instalar tambem o agente fluig-developer?",
        default: true,
      },
      {
        type: "confirm",
        name: "rules",
        message: "Instalar tambem as regras ES5 / nomenclatura / seguranca?",
        default: true,
      },
    ]);
    doAgent = extras.agent;
    doRules = extras.rules;
  }

  // Executar instalacao
  print("");
  info("Instalando skills...");
  print("");

  const home = os.homedir();
  const installed = [];
  const errors = [];

  for (const skillNome of selectedSkills) {
    if (!skillsMap[skillNome]) {
      warn(`Skill '${skillNome}' nao encontrada — pulando`);
      continue;
    }

    const skillPath = skillsMap[skillNome];
    print(`  ${TEAL}${B}${skillNome}${R}`);

    for (const destKey of selectedDests) {
      try {
        let result;
        if (destKey === "claude_global") {
          result = installClaudeCode(skillNome, skillPath, path.join(home, ".claude"));
        } else if (destKey === "claude_projeto" && projectPath) {
          result = installClaudeCode(skillNome, skillPath, path.join(projectPath, ".claude"));
        } else if (destKey === "codex_global") {
          result = installCodex(skillNome, skillPath, path.join(home, ".codex"));
        } else if (destKey === "codex_projeto" && projectPath) {
          result = installCodex(skillNome, skillPath, path.join(projectPath, ".codex"));
        } else if (destKey === "copilot" && projectPath) {
          result = installCopilot(skillNome, skillPath, projectPath);
        } else if (destKey === "cursor" && projectPath) {
          result = installCursor(skillNome, skillPath, projectPath);
        } else {
          continue;
        }
        const destName = DESTINOS.find((d) => d.key === destKey).name;
        ok(`${destName}   ${DIM}${result}${R}`);
        installed.push({ skill: skillNome, dest: destKey });
      } catch (e) {
        const destName = DESTINOS.find((d) => d.key === destKey).name;
        erro(`${destName}: ${e.message}`);
        errors.push(`${skillNome} / ${destName}: ${e.message}`);
      }
    }
  }

  // Agente
  if (doAgent) {
    print(`\n  ${PURPLE}${B}Agente fluig-developer${R}`);
    if (selectedDests.includes("claude_global")) {
      ok("global   " + installAgent(path.join(home, ".claude")));
    }
    if (selectedDests.includes("claude_projeto") && projectPath) {
      ok("projeto  " + installAgent(path.join(projectPath, ".claude")));
    }
  }

  // Regras
  if (doRules) {
    print(`\n  ${PURPLE}${B}Regras${R}`);
    if (selectedDests.includes("claude_global")) {
      for (const r of installRules(path.join(home, ".claude"))) {
        ok("global   " + r);
      }
    }
    if (selectedDests.includes("claude_projeto") && projectPath) {
      for (const r of installRules(path.join(projectPath, ".claude"))) {
        ok("projeto  " + r);
      }
    }
  }

  print("");
  if (!errors.length) {
    ok(`${GREEN}${B}${selectedSkills.length} skill(s) instalada(s)!${R}`);
  } else {
    warn(`${selectedSkills.length} skill(s) processada(s), ${errors.length} erro(s)`);
  }

  return { installed, errors };
}

/**
 * Menu standalone de skills (para fluig-mcp skills / fluig-skills)
 */
async function runSkillsMenu() {
  const { default: inquirer } = await import("inquirer");
  const { banner } = require("../banner");

  banner();
  await selectAndInstallSkills();
}

module.exports = { selectAndInstallSkills, runSkillsMenu };
