export type PetRuntimeState =
  | 'idle'
  | 'running'      // row 1: running-right
  | 'runningAlt'   // row 2: running-left
  | 'jumping'      // row 4: jumping (transient on tool fire)
  | 'dispatching'  // row 7: generic running (startup phase)
  | 'waiting'      // row 8: review (showing while asking the user)
  | 'done'         // row 3: waving (success flourish)
  | 'error';       // row 5: failed

export function petStateFromJobStatus(
  status: string | null | undefined,
  taskId?: number | null,
): PetRuntimeState {
  if (status === 'dispatching') return 'dispatching';
  if (status === 'running') {
    return taskId != null && Math.abs(taskId) % 2 === 1 ? 'runningAlt' : 'running';
  }
  if (status === 'waiting_human') return 'waiting';
  if (status === 'succeeded') return 'done';
  if (status === 'failed' || status === 'cancelled') return 'error';
  return 'idle';
}

// Codex Pets standard row order:
// 0:idle 1:running-right 2:running-left 3:waving 4:jumping 5:failed 6:waiting 7:running 8:review
const CODEX_STATE_ROW: Record<PetRuntimeState, number> = {
  idle: 0,
  running: 1,
  runningAlt: 2,
  done: 3,
  jumping: 4,
  error: 5,
  dispatching: 7,
  waiting: 8,
};

export function rowIndexForState(state: PetRuntimeState, rows: number): number {
  const row = CODEX_STATE_ROW[state] ?? 0;
  return Math.min(row, Math.max(0, rows - 1));
}

const TOOL_NAME_RE = /^(mcp__[a-zA-Z0-9_-]+__[a-zA-Z0-9_-]+|[A-Z][a-zA-Z0-9_]+)$/;

export function extractToolNameFromText(text: string | null | undefined): string | null {
  if (!text) return null;
  const colonIndex = text.indexOf(':');
  if (colonIndex > 0 && colonIndex <= 100) {
    const candidate = text.slice(0, colonIndex).trim();
    if (TOOL_NAME_RE.test(candidate)) return candidate;
  }
  return null;
}

export function extractLatestToolName(currentActivity: string | null | undefined): string | null {
  return extractToolNameFromText(currentActivity);
}
