/**
 * Background Task Queue — orchestrates queued task execution.
 *
 * Tasks run in isolated git worktrees via forked agents.
 * API calls are serialized to avoid rate limits.
 * Each task has a token budget ceiling.
 */

import { logForDebugging } from '../../utils/debug.js'
import {
  enqueueTask,
  cancelTask,
  listTasks,
  formatQueueStatus,
  updateTask,
  getNextPendingTask,
  pruneOldTasks,
} from './queue.js'

/**
 * Queue a new background task.
 * Returns the task ID for tracking.
 */
export async function queueTask(
  prompt: string,
  tokenBudget?: number,
): Promise<string> {
  const task = await enqueueTask(prompt, tokenBudget)

  // Try to start execution if capacity available
  void processQueue()

  return task.id
}

/**
 * Process the task queue — start next pending task if capacity allows.
 * This is a fire-and-forget operation.
 */
async function processQueue(): Promise<void> {
  const nextTask = await getNextPendingTask()
  if (!nextTask) return

  logForDebugging(`Starting queued task: ${nextTask.id}`)

  await updateTask(nextTask.id, {
    status: 'running',
    startedAt: Date.now(),
  })

  // TODO: Execute in a git worktree via runForkedAgent()
  // This is a placeholder for the full implementation which requires:
  // 1. Creating a worktree (git worktree add)
  // 2. Spawning a forked agent in the worktree
  // 3. Tracking token usage against budget
  // 4. Generating a result summary
  // 5. Cleaning up on completion/failure
  //
  // For now, mark as failed with a placeholder message
  await updateTask(nextTask.id, {
    status: 'failed',
    completedAt: Date.now(),
    error:
      'Background task execution not yet fully implemented. Use /queue status to track.',
  })

  // Prune old tasks periodically
  void pruneOldTasks()
}

// Re-export queue management functions
export {
  cancelTask,
  listTasks,
  formatQueueStatus,
} from './queue.js'
