import type { Command } from '../commands.js'
import type { LocalCommandCall } from '../types/command.js'
import {
  queueTask,
  cancelTask,
  formatQueueStatus,
} from '../services/taskQueue/index.js'

const call: LocalCommandCall = async (args) => {
  const trimmed = args.trim()

  // /queue status (or just /queue)
  if (!trimmed || trimmed.toLowerCase() === 'status') {
    const status = await formatQueueStatus()
    return { type: 'text', value: status }
  }

  // /queue cancel <id>
  if (trimmed.toLowerCase().startsWith('cancel ')) {
    const id = trimmed.slice(7).trim()
    if (!id) {
      return { type: 'text', value: 'Usage: /queue cancel <task-id>' }
    }
    const cancelled = await cancelTask(id)
    return {
      type: 'text',
      value: cancelled
        ? `Task ${id} cancelled.`
        : `Task ${id} not found or already finished.`,
    }
  }

  // /queue "some task description" — queue a new task
  const taskId = await queueTask(trimmed)
  return {
    type: 'text',
    value: `Task queued: ${taskId}\nUse /queue status to track progress.`,
  }
}

const queue = {
  type: 'local',
  name: 'queue',
  description: 'Queue background tasks or check queue status',
  argumentHint: '[<task>|status|cancel <id>]',
  supportsNonInteractive: true,
  load: () => Promise.resolve({ call }),
} satisfies Command

export default queue
