import { existsSync, readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import { isPathInside, isValidReportDirName } from '../../../shared/utils/index.js';
import { getErrorMessage } from '../../../shared/utils/error.js';
import { buildRunPaths } from './run-paths.js';
function normalizeRunMeta(raw) {
    return {
        ...raw,
        resumePoint: raw.resumePoint ?? raw.resume_point,
        sourceRunSlug: raw.sourceRunSlug ?? raw.source_run_slug,
        resumeMode: raw.resumeMode ?? raw.resume_mode,
    };
}
function emitRunMetaWarning(metaPath, error, onWarning) {
    onWarning?.(`Failed to parse run metadata at ${metaPath}: ${getErrorMessage(error)}`);
    return null;
}
export function readRunMeta(metaPath, onWarning) {
    if (!existsSync(metaPath)) {
        return null;
    }
    const raw = readFileSync(metaPath, 'utf-8').trim();
    if (!raw) {
        return null;
    }
    try {
        return normalizeRunMeta(JSON.parse(raw));
    }
    catch (error) {
        return emitRunMetaWarning(metaPath, error, onWarning);
    }
}
export function readRunMetaBySlug(cwd, slug, onWarning) {
    if (!isValidReportDirName(slug)) {
        return null;
    }
    const runsDir = resolve(cwd, '.takt', 'runs');
    const metaPath = resolve(runsDir, slug, 'meta.json');
    if (!isPathInside(runsDir, metaPath)) {
        return null;
    }
    const meta = readRunMeta(metaPath, onWarning);
    if (!meta) {
        return null;
    }
    const runPaths = buildRunPaths(cwd, slug);
    return {
        ...meta,
        runSlug: slug,
        runRoot: runPaths.runRootRel,
        reportDirectory: runPaths.reportsRel,
        contextDirectory: runPaths.contextRel,
        logsDirectory: runPaths.logsRel,
    };
}
function resolveRunningStep(meta) {
    if (!meta) {
        return undefined;
    }
    if (meta.status !== 'running') {
        return undefined;
    }
    if (meta.currentStep) {
        return meta.currentStep;
    }
    return undefined;
}
export function findRunningStepByRunSlug(cwd, runSlug, onWarning) {
    return resolveRunningStep(readRunMetaBySlug(cwd, runSlug, onWarning));
}
//# sourceMappingURL=run-meta.js.map