import * as path from 'node:path';
import { nowIso } from './naming.js';
export function buildClaimedTaskRecord(task) {
    return {
        ...task,
        status: 'running',
        started_at: nowIso(),
        owner_pid: process.pid,
        run_slug: undefined,
    };
}
export function buildRecoveredTaskRecordWithRetryMetadata(task, retryMetadata) {
    const nextTask = retryMetadata.preserveExisting ? { ...task } : clearRetryMetadata(task);
    return {
        ...nextTask,
        status: 'pending',
        started_at: null,
        completed_at: null,
        owner_pid: null,
        run_slug: undefined,
        ...(retryMetadata.startStep ? { start_step: retryMetadata.startStep } : {}),
    };
}
export function buildTerminalTaskRecord(task, updates, retryMetadata) {
    const nextTask = retryMetadata?.preserveExisting ? { ...task } : clearRetryMetadata(task);
    const nextRetryMetadata = retryMetadata?.preserveExisting ? undefined : retryMetadata;
    return {
        ...nextTask,
        ...updates,
        ...(nextRetryMetadata?.startStep ? { start_step: nextRetryMetadata.startStep } : {}),
        ...(nextRetryMetadata?.resumePoint ? { resume_point: nextRetryMetadata.resumePoint } : {}),
        ...(nextRetryMetadata?.currentIteration !== undefined
            ? { exceeded_current_iteration: nextRetryMetadata.currentIteration }
            : {}),
    };
}
export function buildRetryTaskRecord(task, status, startStep, retryNote, resumePoint, workflow, taskDir) {
    const taskSpecSource = taskDir
        ? { content: undefined, content_file: undefined, task_dir: taskDir }
        : {};
    return {
        ...task,
        ...(workflow ? { workflow } : {}),
        ...taskSpecSource,
        status,
        started_at: status === 'running' ? nowIso() : null,
        completed_at: null,
        owner_pid: status === 'running' ? process.pid : null,
        run_slug: undefined,
        failure: undefined,
        start_step: startStep,
        retry_note: retryNote,
        resume_point: resumePoint,
    };
}
export function normalizeTaskRef(taskRef) {
    if (!taskRef.includes(path.sep)) {
        return taskRef;
    }
    const base = path.basename(taskRef);
    if (base.includes('_')) {
        return base.slice(base.indexOf('_') + 1);
    }
    return base;
}
export function generateTaskName(slug, existingNames) {
    const base = slug || `task-${Date.now()}`;
    let candidate = base;
    let counter = 1;
    while (existingNames.includes(candidate)) {
        candidate = `${base}-${counter}`;
        counter += 1;
    }
    return candidate;
}
function clearRetryMetadata(task) {
    const retryMetadataKeys = new Set([
        'start_step',
        'resume_point',
        'exceeded_current_iteration',
        'exceeded_max_steps',
    ]);
    return Object.fromEntries(Object.entries(task).filter(([key]) => !retryMetadataKeys.has(key)));
}
//# sourceMappingURL=taskRecordMutations.js.map