'use strict';

const { dim, isColorSupported } = require('./theme');

/**
 * Run sequential tasks with @clack/prompts tasks() UI.
 * Each task object: { title, task: async (message) => string, enabled? }
 *
 * Adds [N/M] step counter prefix (dim) to each title.
 * Falls back to createProgress() spinners when clack is unavailable or
 * when the terminal doesn't support color (clack emits cursor-control
 * ANSI sequences even with NO_COLOR).
 *
 * @param {Array} taskList - Array of task definitions
 * @returns {Promise<void>}
 */
async function runTasks(taskList) {
  // Filter to enabled tasks only (default enabled = true)
  const activeTasks = taskList.filter(t => t.enabled !== false);
  const total = activeTasks.length;

  // Use @clack/prompts tasks() only when TTY + color supported
  const isTTY = !!(process.stdout && process.stdout.isTTY);
  if (isTTY && isColorSupported) {
    try {
      const clack = await import('@clack/prompts');
      if (clack && clack.tasks) {
        await clack.tasks(
          activeTasks.map((t, i) => ({
            title: `${dim(`[${i + 1}/${total}]`)} ${t.title}`,
            task: t.task,
          }))
        );
        return;
      }
    } catch {
      // Fall through to plain fallback
    }
  }

  // Fallback: sequential createProgress() spinners (handles NO_COLOR, non-TTY)
  const { createProgress } = require('./progress');
  for (let i = 0; i < activeTasks.length; i++) {
    const t = activeTasks[i];
    const prefix = `[${i + 1}/${total}]`;
    const progress = createProgress();
    progress.start(`${prefix} ${t.title}`);
    try {
      const msg = await t.task((update) => {
        // message callback — in fallback mode, just log
        if (update) progress.start(`${prefix} ${update}`);
      });
      progress.success(`${prefix} ${t.title}`, msg || '');
    } catch (err) {
      progress.error(`${prefix} ${t.title}: ${err.message}`);
      throw err;
    }
  }
}

module.exports = { runTasks };
