import fs from "node:fs";
import path from "node:path";
import { assertGraphInvariants, createInitialState } from "./graph.js";
import { defaultPrompts } from "./prompts.js";
export function ccflowDir(repoRoot) {
    return path.join(repoRoot, ".ccflow");
}
export function statePath(repoRoot) {
    return path.join(ccflowDir(repoRoot), "ccflow.json");
}
export function promptsPath(repoRoot) {
    return path.join(ccflowDir(repoRoot), "prompts.json");
}
export function sessionsDir(repoRoot) {
    return path.join(ccflowDir(repoRoot), "sessions");
}
export function jobsDir(repoRoot) {
    return path.join(ccflowDir(repoRoot), "jobs");
}
export function logsDir(repoRoot) {
    return path.join(ccflowDir(repoRoot), "logs");
}
export function ensureCcflowDirs(repoRoot) {
    for (const dir of [ccflowDir(repoRoot), sessionsDir(repoRoot), jobsDir(repoRoot), logsDir(repoRoot)]) {
        fs.mkdirSync(dir, { recursive: true });
    }
}
export function loadOrInitState(input) {
    ensureCcflowDirs(input.repoRoot);
    const file = statePath(input.repoRoot);
    if (fs.existsSync(file)) {
        const state = JSON.parse(fs.readFileSync(file, "utf8"));
        assertGraphInvariants(state);
        return state;
    }
    const state = createInitialState(input);
    saveState(state);
    return state;
}
export function loadState(repoRoot) {
    const state = JSON.parse(fs.readFileSync(statePath(repoRoot), "utf8"));
    assertGraphInvariants(state);
    return state;
}
export function saveState(state) {
    assertGraphInvariants(state);
    ensureCcflowDirs(state.repoRoot);
    writeJsonAtomic(statePath(state.repoRoot), state);
}
export function loadPrompts(repoRoot) {
    const file = promptsPath(repoRoot);
    if (!fs.existsSync(file))
        return defaultPrompts;
    return JSON.parse(fs.readFileSync(file, "utf8"));
}
export function ensurePrompts(repoRoot) {
    ensureCcflowDirs(repoRoot);
    const file = promptsPath(repoRoot);
    if (!fs.existsSync(file)) {
        writeJsonAtomic(file, defaultPrompts);
    }
}
export function saveSession(repoRoot, node) {
    ensureCcflowDirs(repoRoot);
    writeJsonAtomic(path.join(sessionsDir(repoRoot), `${node.id}.json`), {
        nodeId: node.id,
        cc: node.cc,
        updatedAt: node.updatedAt,
    });
}
export function saveJob(repoRoot, job) {
    ensureCcflowDirs(repoRoot);
    writeJsonAtomic(path.join(jobsDir(repoRoot), `${job.jobId}.json`), job);
}
export function writeJsonAtomic(file, value) {
    fs.mkdirSync(path.dirname(file), { recursive: true });
    const temp = `${file}.${process.pid}.tmp`;
    fs.writeFileSync(temp, `${JSON.stringify(value, null, 2)}\n`);
    fs.renameSync(temp, file);
}
