/**
 * Debug / verbose helpers.
 *
 * Enabled by either:
 *   - `--verbose` flag (set globally in bin/kasy.js via process.argv parsing)
 *   - `KASY_DEBUG=1` environment variable
 *
 * Use `debugLog(...)` for diagnostic output that should only show when the
 * user opts in. Use `attachDebugToError(err, context)` before throwing/rejecting
 * to attach extra info (stdout/stderr/command) that surfaces in --verbose mode.
 */

'use strict';

const kleur = require('kleur');

function isVerbose() {
  if (process.env.KASY_DEBUG === '1' || process.env.KASY_DEBUG === 'true') return true;
  return process.argv.includes('--verbose');
}

/**
 * Strip --verbose from argv before commander parses it, since commander does
 * not know about this flag. Returns a new argv with --verbose removed.
 */
function stripVerboseFlag(argv) {
  return argv.filter((arg) => arg !== '--verbose');
}

function debugLog(...args) {
  if (!isVerbose()) return;
  console.error(kleur.dim(`[debug] ${args.map(String).join(' ')}`));
}

/**
 * Attach raw command output to an error so --verbose mode can surface it.
 * The original error message stays clean for end users.
 */
function attachDebugToError(err, { command, stdout, stderr, cwd } = {}) {
  if (!err || typeof err !== 'object') return err;
  err.kasyDebug = {
    command: command || null,
    stdout: stdout != null ? String(stdout) : null,
    stderr: stderr != null ? String(stderr) : null,
    cwd: cwd || null,
  };
  return err;
}

/**
 * Print verbose context for an error if debug is on. Called from the global
 * error handler in bin/kasy.js.
 */
function printVerboseError(err) {
  if (!isVerbose() || !err) return;
  console.error('');
  console.error(kleur.dim('─── verbose error context ───'));
  if (err.stack) console.error(kleur.dim(err.stack));
  if (err.kasyDebug) {
    const d = err.kasyDebug;
    if (d.command) console.error(kleur.dim(`command: ${d.command}`));
    if (d.cwd)     console.error(kleur.dim(`cwd:     ${d.cwd}`));
    if (d.stdout)  console.error(kleur.dim('stdout:\n' + d.stdout));
    if (d.stderr)  console.error(kleur.dim('stderr:\n' + d.stderr));
  }
  console.error(kleur.dim('─────────────────────────────'));
}

module.exports = {
  isVerbose,
  stripVerboseFlag,
  debugLog,
  attachDebugToError,
  printVerboseError,
};
