"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.stringifyReusableDraftFile = stringifyReusableDraftFile;
exports.parseReusableDraftFileJson = parseReusableDraftFileJson;
exports.readReusableDraftFile = readReusableDraftFile;
exports.writeReusableDraftFile = writeReusableDraftFile;
exports.writeMachineLocalReusableDraft = writeMachineLocalReusableDraft;
const node_fs_1 = require("node:fs");
const promises_1 = require("node:fs/promises");
const node_path_1 = __importDefault(require("node:path"));
const zod_1 = require("zod");
const paths_1 = require("../core/paths");
const provider_resolution_1 = require("../platform/provider-resolution");
function stringifyReusableDraftFile(draftFile) {
    return `${JSON.stringify(draftFile, null, 2)}\n`;
}
function parseReusableDraftFileJson(input) {
    let parsedJson;
    try {
        parsedJson = JSON.parse(input.text);
    }
    catch {
        throw new Error(input.invalidDraftFileMessage);
    }
    try {
        return input.parse(parsedJson);
    }
    catch (error) {
        if (error instanceof zod_1.z.ZodError) {
            throw new Error(input.invalidDraftFileMessage);
        }
        throw error;
    }
}
async function readReusableDraftFile(draftFilePath) {
    return draftFilePath === "-"
        ? (0, node_fs_1.readFileSync)(0, "utf8")
        : (0, promises_1.readFile)(draftFilePath, "utf8");
}
async function writeReusableDraftFile(draftFilePath, contents) {
    await (0, promises_1.mkdir)(node_path_1.default.dirname(draftFilePath), { recursive: true });
    await (0, promises_1.writeFile)(draftFilePath, contents, "utf8");
}
async function writeMachineLocalReusableDraft(input) {
    const storageSegments = input.trackedProject === undefined
        ? ["local", slugifyDraftTitle(input.cwd ?? "") || "unknown"]
        : (0, provider_resolution_1.getTrackedProjectStorageSegments)(input.trackedProject);
    const draftFilePath = node_path_1.default.join((0, paths_1.getControlPlaneHomePath)(input.homeDirectory), "drafts", ...storageSegments, buildReusableDraftFileName(input));
    await writeReusableDraftFile(draftFilePath, input.draftJson);
    return draftFilePath;
}
function buildReusableDraftFileName(input) {
    const timestamp = input.preparedAt.replaceAll(/[^0-9A-Za-z]+/gu, "-");
    const slug = slugifyDraftTitle(input.title ?? "");
    return `${input.command}-${timestamp}${slug ? `-${slug}` : ""}.json`;
}
function slugifyDraftTitle(value) {
    return value
        .trim()
        .toLowerCase()
        .replaceAll(/[^0-9a-z]+/gu, "-")
        .replaceAll(/^-|-$/gu, "")
        .slice(0, 48);
}
