const path = require('node:path');
const { exec } = require('node:child_process');
const fs = require('fs-extra');
const kleur = require('kleur');
const ui = require('../utils/ui');
const { printCompactHeader } = require('../utils/brand');
const { createTranslator, detectDefaultLanguage } = require('../utils/i18n');

const DOCS_FILE = path.join(__dirname, '..', '..', 'docs', 'cli-reference.md');

function openInBrowser(url) {
  const cmd = process.platform === 'darwin'
    ? `open "${url}"`
    : process.platform === 'win32'
      ? `start "" "${url}"`
      : `xdg-open "${url}"`;
  exec(cmd);
}

async function runDocs(options = {}) {
  const t = createTranslator(options.language || detectDefaultLanguage());

  printCompactHeader(t);
  ui.intro('Kasy CLI — Documentação');

  if (await fs.pathExists(DOCS_FILE)) {
    const content = await fs.readFile(DOCS_FILE, 'utf8');
    const lines = content.split('\n').slice(0, 60);
    ui.note(`${kleur.dim(lines.join('\n'))}\n\n${kleur.dim(`... (arquivo completo: ${DOCS_FILE})`)}`);
  }

  const commandsBody = [
    `${kleur.bold('kasy new')}       — Criar novo projeto`,
    `${kleur.bold('kasy add')}       — Adicionar módulo`,
    `${kleur.bold('kasy doctor')}    — Verificar ambiente`,
    `${kleur.bold('kasy run')}       — Executar app`,
    `${kleur.bold('kasy deploy')}    — Deploy do projeto`,
    `${kleur.bold('kasy ios')}       — Release iOS (configure / release / build)`,
    `${kleur.bold('kasy codemagic')} — Build iOS na nuvem`,
    `${kleur.bold('kasy features')}  — Listar features`,
    `${kleur.bold('kasy validate')}  — Validar projeto`,
  ].join('\n');
  ui.note(commandsBody, kleur.cyan('Comandos disponíveis'));

  ui.outro(kleur.dim('Para detalhes de um comando: kasy help <comando>'));
}

module.exports = { runDocs };
