import { toTaskInfo } from './mapper.js';
import { buildRetryTaskRecord, normalizeTaskRef } from './taskRecordMutations.js';
function replaceTaskAtIndex(tasks, index, updated) {
    return tasks.map((task, taskIndex) => (taskIndex === index ? updated : task));
}
export class TaskRetryService {
    projectDir;
    tasksFile;
    store;
    constructor(projectDir, tasksFile, store) {
        this.projectDir = projectDir;
        this.tasksFile = tasksFile;
        this.store = store;
    }
    requeueFailedTask(taskRef, startStep, retryNote) {
        return this.requeueTask(taskRef, ['failed'], startStep, retryNote);
    }
    startReExecution(taskRef, allowedStatuses, startStep, retryNote, resumePoint, workflow, taskDir) {
        const taskName = normalizeTaskRef(taskRef);
        let found;
        this.store.update((current) => {
            const index = current.tasks.findIndex((task) => (task.name === taskName
                && allowedStatuses.includes(task.status)));
            if (index === -1) {
                const expectedStatuses = allowedStatuses.join(', ');
                throw new Error(`Task not found for re-execution: ${taskRef} (expected status: ${expectedStatuses})`);
            }
            const target = current.tasks[index];
            const updated = buildRetryTaskRecord(target, 'running', startStep, retryNote, resumePoint, workflow, taskDir);
            found = updated;
            return { tasks: replaceTaskAtIndex(current.tasks, index, updated) };
        });
        return toTaskInfo(this.projectDir, this.tasksFile, found);
    }
    requeueTask(taskRef, allowedStatuses, startStep, retryNote, resumePoint, workflow, taskDir) {
        const taskName = normalizeTaskRef(taskRef);
        this.store.update((current) => {
            const index = current.tasks.findIndex((task) => (task.name === taskName
                && allowedStatuses.includes(task.status)));
            if (index === -1) {
                const expectedStatuses = allowedStatuses.join(', ');
                throw new Error(`Task not found for requeue: ${taskRef} (expected status: ${expectedStatuses})`);
            }
            const target = current.tasks[index];
            const updated = buildRetryTaskRecord(target, 'pending', startStep, retryNote, resumePoint, workflow, taskDir);
            return { tasks: replaceTaskAtIndex(current.tasks, index, updated) };
        });
        return this.tasksFile;
    }
}
//# sourceMappingURL=taskRetryService.js.map