/**
 * RunMeta — 実行メタデータの管理モジュール
 *
 * ランのメタデータ（task, workflow, status, 開始・終了時刻など）を
 * .takt/runs/{slug}/meta.json へ書き出す責務を担う。
 */
import { writeFileAtomic, ensureDir } from '../../../infra/config/index.js';
export class RunMetaManager {
    runMeta;
    metaAbs;
    finalized = false;
    constructor(runPaths, task, workflowName, directResume) {
        this.metaAbs = runPaths.metaAbs;
        this.runMeta = {
            task,
            workflow: workflowName,
            runSlug: runPaths.slug,
            runRoot: runPaths.runRootRel,
            reportDirectory: runPaths.reportsRel,
            contextDirectory: runPaths.contextRel,
            logsDirectory: runPaths.logsRel,
            status: 'running',
            startTime: new Date().toISOString(),
            ...(directResume ? {
                sourceRunSlug: directResume.sourceRunSlug,
                resumeMode: directResume.resumeMode,
            } : {}),
        };
        ensureDir(runPaths.runRootAbs);
        this.writeRunMeta(this.runMeta);
    }
    updateStep(stepName, iteration, resumePoint) {
        this.runMeta.currentStep = stepName;
        this.runMeta.currentIteration = iteration;
        delete this.runMeta.phase;
        this.runMeta.resumePoint = resumePoint;
        this.writeRunMeta(this.runMeta);
    }
    updatePhase(stepName, iteration, phase) {
        this.runMeta.currentStep = stepName;
        this.runMeta.currentIteration = iteration;
        this.runMeta.phase = phase;
        this.writeRunMeta(this.runMeta);
    }
    updateResumePoint(resumePoint) {
        this.runMeta.resumePoint = resumePoint;
        this.writeRunMeta(this.runMeta);
    }
    finalize(status, iterations) {
        this.writeRunMeta({
            ...this.runMeta,
            status,
            endTime: new Date().toISOString(),
            ...(iterations != null ? { iterations } : {}),
        });
        this.finalized = true;
    }
    get isFinalized() {
        return this.finalized;
    }
    writeRunMeta(meta) {
        const updatedAt = new Date().toISOString();
        const { resumePoint, sourceRunSlug, resumeMode, ...baseMeta } = meta;
        const serialized = {
            ...baseMeta,
            updatedAt,
            ...(resumePoint ? { resume_point: resumePoint } : {}),
            ...(sourceRunSlug ? { source_run_slug: sourceRunSlug } : {}),
            ...(resumeMode ? { resume_mode: resumeMode } : {}),
        };
        this.runMeta.updatedAt = updatedAt;
        writeFileAtomic(this.metaAbs, JSON.stringify(serialized, null, 2));
    }
}
//# sourceMappingURL=runMeta.js.map