export const AGENT_STATUSES = [
  'created',
  'active',
  'paused',
  'busy',
  'terminated',
  'heartbeat ok',
  'last cron tick complete',
];

export const TASK_STATUSES = [
  'backlog',
  'todo',
  'in_progress',
  'in_review',
  'blocked',
  'done',
  'cancelled',
];

export const TASK_PRIORITIES = [
  'low',
  'medium',
  'high',
  'urgent',
];

export const RUN_STATUSES = [
  'queued',
  'running',
  'waiting_approval',
  'succeeded',
  'failed',
  'cancelled',
  'timed_out',
];

export const TASK_EVENT_TYPES = [
  'task.created',
  'task.updated',
  'task.assigned',
  'task.reassigned',
  'task.status_changed',
  'task.comment_added',
  'task.blocked',
  'task.unblocked',
  'task.completed',
  'task.cancelled',
  'task.child_created',
];

export const AGENT_RUN_EVENT_TYPES = [
  'lifecycle',
  'tool_start',
  'tool_result',
  'log',
  'warning',
  'error',
  'approval_required',
  'delegation_proposed',
  'delegation_completed',
];

export const LIVE_EVENT_TYPES = [
  'activity.logged',
  'task.updated',
  'task.comment.added',
  'task.assigned',
  'task.reassigned',
  'agent.status',
  'agent.run.queued',
  'agent.run.status',
  'agent.run.event',
  'agent.run.log',
];

const LEGAL_TASK_TRANSITIONS = {
  backlog: ['todo', 'cancelled'],
  todo: ['in_progress', 'blocked', 'cancelled', 'done'],
  in_progress: ['in_review', 'blocked', 'todo', 'done', 'cancelled'],
  in_review: ['in_progress', 'done', 'blocked', 'cancelled'],
  blocked: ['todo', 'in_progress', 'cancelled'],
  done: ['in_review'],
  cancelled: ['todo'],
};

export function isTerminalTaskStatus(status) {
  return status === 'done' || status === 'cancelled';
}

export function isActiveRunStatus(status) {
  return ['queued', 'running', 'waiting_approval'].includes(status);
}

export function normalizeTaskStatus(status, fallback = 'todo') {
  return TASK_STATUSES.includes(status) ? status : fallback;
}

export function normalizeTaskPriority(priority, fallback = 'medium') {
  return TASK_PRIORITIES.includes(priority) ? priority : fallback;
}

export function normalizeRunStatus(status, fallback = 'queued') {
  return RUN_STATUSES.includes(status) ? status : fallback;
}

export function normalizeLiveEventType(type, fallback = 'activity.logged') {
  return LIVE_EVENT_TYPES.includes(type) ? type : fallback;
}

export function isLegalTaskTransition(fromStatus, toStatus) {
  if (!fromStatus || fromStatus === toStatus) return true;
  return Boolean(LEGAL_TASK_TRANSITIONS[fromStatus]?.includes(toStatus));
}

export function assertLegalTaskTransition(fromStatus, toStatus) {
  if (!isLegalTaskTransition(fromStatus, toStatus)) {
    throw new Error(`Illegal task transition: ${fromStatus} -> ${toStatus}`);
  }
}
