/**
 * Task tool — manage a task list during agentic execution.
 *
 * Provides in-memory task tracking with create, update, list, and get
 * operations. Tasks persist for the duration of the agentic session.
 */

// In-memory task store (per-session)
let _nextId = 1;
const _tasks = new Map();

/**
 * Reset task store (for testing).
 */
export function _resetTasks() {
  _nextId = 1;
  _tasks.clear();
}

/**
 * Get all tasks (for testing/external access).
 */
export function _getTasks() {
  return new Map(_tasks);
}

export const definition = {
  name: 'Task',
  description: 'Manage tasks during the current session. Supports create, update, list, and get operations.',
  input_schema: {
    type: 'object',
    properties: {
      action: {
        type: 'string',
        enum: ['create', 'update', 'list', 'get', 'create_background'],
        description: 'The task operation to perform. Use create_background to create a persistent background task.'
      },
      // For create / create_background
      subject: { type: 'string', description: 'Task title (for create/create_background)' },
      description: { type: 'string', description: 'Task description (for create/update/create_background)' },
      // For create_background
      scheduledAt: { type: 'string', description: 'ISO datetime for scheduled execution (for create_background, optional)' },
      // For update/get
      taskId: { type: 'string', description: 'Task ID (for update/get)' },
      status: {
        type: 'string',
        enum: ['pending', 'in_progress', 'completed', 'deleted'],
        description: 'New status (for update)'
      }
    },
    required: ['action']
  }
};

export async function execute(input, context) {
  const { action } = input;

  if (!action) {
    return { content: 'Error: action is required', is_error: true };
  }

  switch (action) {
    case 'create': return createTask(input);
    case 'update': return updateTask(input);
    case 'list': return listTasks();
    case 'get': return getTask(input);
    case 'create_background': return createBackgroundTask(input, context);
    default:
      return { content: `Error: Unknown action "${action}". Use create, update, list, get, or create_background.`, is_error: true };
  }
}

function createTask(input) {
  const { subject, description } = input;

  if (!subject) {
    return { content: 'Error: subject is required for create', is_error: true };
  }

  const id = String(_nextId++);
  const task = {
    id,
    subject,
    description: description || '',
    status: 'pending',
    createdAt: new Date().toISOString()
  };
  _tasks.set(id, task);

  return {
    content: `Created task #${id}: ${subject}`,
    is_error: false
  };
}

function updateTask(input) {
  const { taskId, status, subject, description } = input;

  if (!taskId) {
    return { content: 'Error: taskId is required for update', is_error: true };
  }

  const task = _tasks.get(taskId);
  if (!task) {
    return { content: `Error: Task #${taskId} not found`, is_error: true };
  }

  if (status === 'deleted') {
    _tasks.delete(taskId);
    return { content: `Deleted task #${taskId}`, is_error: false };
  }

  if (status) task.status = status;
  if (subject) task.subject = subject;
  if (description) task.description = description;

  return {
    content: `Updated task #${taskId}: ${task.subject} [${task.status}]`,
    is_error: false
  };
}

function listTasks() {
  if (_tasks.size === 0) {
    return { content: 'No tasks.', is_error: false };
  }

  const lines = [];
  for (const [id, task] of _tasks) {
    lines.push(`#${id}. [${task.status}] ${task.subject}`);
  }

  return { content: lines.join('\n'), is_error: false };
}

function getTask(input) {
  const { taskId } = input;

  if (!taskId) {
    return { content: 'Error: taskId is required for get', is_error: true };
  }

  const task = _tasks.get(taskId);
  if (!task) {
    return { content: `Error: Task #${taskId} not found`, is_error: true };
  }

  const details = [
    `Task #${task.id}`,
    `Subject: ${task.subject}`,
    `Status: ${task.status}`,
    `Description: ${task.description || '(none)'}`,
    `Created: ${task.createdAt}`
  ].join('\n');

  return { content: details, is_error: false };
}

function createBackgroundTask(input, context) {
  const { subject, description, scheduledAt } = input;

  if (!subject) {
    return { content: 'Error: subject is required for create_background', is_error: true };
  }

  if (!context?.enqueueBackgroundTask) {
    return { content: 'Error: Background task queue not available', is_error: true };
  }

  const bgTaskId = context.enqueueBackgroundTask({
    subject,
    description: description || '',
    scheduledAt: scheduledAt || null
  });

  return {
    content: `Created background task #${bgTaskId}: ${subject}${scheduledAt ? ` (scheduled: ${scheduledAt})` : ''}`,
    is_error: false
  };
}
