import { promises as fs } from "node:fs";
import path from "node:path";
import { reflexHome } from "../home.js";
import { DEFAULT_TEMPLATES, TEMPLATE_NAMES, } from "./defaults.js";
const PROMPTS_DIR = path.join(reflexHome(), "prompts");
function pathFor(name) {
    return path.join(PROMPTS_DIR, `${name}.md`);
}
function isTemplateName(s) {
    return TEMPLATE_NAMES.includes(s);
}
export function templatePath(name) {
    return pathFor(name);
}
/**
 * Load `<name>` template body. If the file is missing, scaffold it with the
 * built-in default and return that. Always returns the on-disk content after
 * the call so subsequent reads see the same bytes.
 */
export async function loadTemplate(name) {
    const target = pathFor(name);
    try {
        return await fs.readFile(target, "utf8");
    }
    catch (err) {
        if (!isNotFound(err))
            throw err;
    }
    // First touch — write the default so the user can edit on disk too.
    await fs.mkdir(PROMPTS_DIR, { recursive: true });
    await fs.writeFile(target, DEFAULT_TEMPLATES[name], "utf8");
    return DEFAULT_TEMPLATES[name];
}
export async function saveTemplate(name, body) {
    await fs.mkdir(PROMPTS_DIR, { recursive: true });
    await fs.writeFile(pathFor(name), body, "utf8");
}
export async function resetTemplate(name) {
    await saveTemplate(name, DEFAULT_TEMPLATES[name]);
    return DEFAULT_TEMPLATES[name];
}
export function assertTemplateName(s) {
    if (!isTemplateName(s)) {
        throw new Error(`Unknown template: ${s}`);
    }
    return s;
}
function isNotFound(err) {
    return (typeof err === "object" &&
        err !== null &&
        "code" in err &&
        err.code === "ENOENT");
}
//# sourceMappingURL=store.js.map