/**
 * Task management commands
 * Wrapper for bin/task-manager.js (CommonJS) to ESM
 */

import { spawn } from 'child_process';
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';
import chalk from 'chalk';

const __dirname = dirname(fileURLToPath(import.meta.url));
const taskManagerPath = join(__dirname, '..', '..', 'bin', 'task-manager.js');

/**
 * Execute task-manager.js with given arguments
 */
function executeTaskManager(args) {
  return new Promise((resolve, reject) => {
    const child = spawn('node', [taskManagerPath, ...args], {
      stdio: 'inherit',
      shell: true
    });

    child.on('close', (code) => {
      if (code === 0) {
        resolve();
      } else {
        reject(new Error(`Task manager exited with code ${code}`));
      }
    });

    child.on('error', (error) => {
      reject(error);
    });
  });
}

/**
 * Complete tasks command
 */
export async function taskDoneCommand(featureName, taskIds, options) {
  try {
    const args = ['done', featureName, ...taskIds];
    await executeTaskManager(args);
  } catch (error) {
    console.error(chalk.red(`Error: ${error.message}`));
    process.exit(1);
  }
}

/**
 * Start task command
 */
export async function taskStartCommand(featureName, taskId, options) {
  try {
    const args = ['start', featureName, taskId];
    await executeTaskManager(args);
  } catch (error) {
    console.error(chalk.red(`Error: ${error.message}`));
    process.exit(1);
  }
}

/**
 * Get next task command
 */
export async function taskNextCommand(featureName, options) {
  try {
    const args = ['next', featureName];
    await executeTaskManager(args);
  } catch (error) {
    console.error(chalk.red(`Error: ${error.message}`));
    process.exit(1);
  }
}
