import { existsSync, readdirSync } from 'node:fs';
import { join } from 'node:path';
import { readRunMetaBySlug } from '../../../core/workflow/run/run-meta.js';
import { TaskRunner } from '../../../infra/task/index.js';
const RESUMABLE_STATUSES = new Set(['aborted', 'failed']);
function collectTaskRunSlugs(projectDir) {
    const runner = new TaskRunner(projectDir);
    return new Set(runner.listAllTaskItems()
        .map((task) => task.runSlug)
        .filter((slug) => typeof slug === 'string' && slug.trim() !== ''));
}
function resolveRunTimestamp(meta) {
    return meta.updatedAt ?? meta.endTime ?? meta.startTime;
}
function compareRunsDesc(left, right) {
    const timestampOrder = resolveRunTimestamp(right.meta).localeCompare(resolveRunTimestamp(left.meta));
    if (timestampOrder !== 0) {
        return timestampOrder;
    }
    return right.slug.localeCompare(left.slug);
}
export function findLatestResumableDirectRun(projectDir) {
    const runsDir = join(projectDir, '.takt', 'runs');
    if (!existsSync(runsDir)) {
        return null;
    }
    const taskRunSlugs = collectTaskRunSlugs(projectDir);
    const runs = readdirSync(runsDir, { withFileTypes: true })
        .filter((entry) => entry.isDirectory())
        .flatMap((entry) => {
        if (taskRunSlugs.has(entry.name)) {
            return [];
        }
        const meta = readRunMetaBySlug(projectDir, entry.name);
        if (!meta || !RESUMABLE_STATUSES.has(meta.status)) {
            return [];
        }
        return [{ slug: entry.name, meta }];
    })
        .sort(compareRunsDesc);
    return runs[0] ?? null;
}
//# sourceMappingURL=directRunFinder.js.map