/**
 * AI Task Registry
 */

import { createNameValidationTask, TASK_ID as NAME_TASK_ID } from './nameValidationTask.js';
import { createDescriptionValidationTask, TASK_ID as DESC_TASK_ID } from './descriptionValidationTask.js';
import { createSanityCheckTask, TASK_ID as SANITY_TASK_ID } from './sanityCheckTask.js';

export { createNameValidationTask, createDescriptionValidationTask, createSanityCheckTask };

export const TASK_IDS = Object.freeze({
  VALIDATE_NAME: NAME_TASK_ID,
  VALIDATE_DESCRIPTION: DESC_TASK_ID,
  SANITY_CHECK: SANITY_TASK_ID,
});

export class TaskRegistry {
  constructor() {
    this.tasks = new Map();
  }

  register(task) {
    if (!task?.id) throw new Error('Task must have an id');
    if (typeof task.run !== 'function') throw new Error(`Task ${task.id} must have a run function`);
    if (this.tasks.has(task.id)) throw new Error(`Task ${task.id} is already registered`);
    this.tasks.set(task.id, task);
    return this;
  }

  get(taskId) {
    return this.tasks.get(taskId) || null;
  }

  has(taskId) {
    return this.tasks.has(taskId);
  }

  async runTask(taskId, payload = {}) {
    const task = this.get(taskId);
    if (!task) throw new Error(`Unknown task: ${taskId}`);
    try {
      const result = await task.run(payload);
      return { success: true, taskId, ...result };
    } catch (error) {
      return {
        success: false,
        taskId,
        error: error.message,
        code: error.code,
      };
    }
  }

  list() {
    return Array.from(this.tasks.keys());
  }

  size() {
    return this.tasks.size;
  }
}

let registry = null;

export function getRegistry() {
  if (!registry) registry = new TaskRegistry();
  return registry;
}

export function resetRegistry() {
  registry = null;
}

export function registerAllTasks(logger = console) {
  const reg = getRegistry();

  if (!reg.has(TASK_IDS.VALIDATE_NAME)) {
    reg.register(createNameValidationTask());
    logger.info(`[Tasks] Registered: ${TASK_IDS.VALIDATE_NAME}`);
  }
  if (!reg.has(TASK_IDS.VALIDATE_DESCRIPTION)) {
    reg.register(createDescriptionValidationTask());
    logger.info(`[Tasks] Registered: ${TASK_IDS.VALIDATE_DESCRIPTION}`);
  }
  if (!reg.has(TASK_IDS.SANITY_CHECK)) {
    reg.register(createSanityCheckTask());
    logger.info(`[Tasks] Registered: ${TASK_IDS.SANITY_CHECK}`);
  }

  return reg;
}
