"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.collectPromptVersionEvidence = collectPromptVersionEvidence;
const node_fs_1 = __importDefault(require("node:fs"));
const paths_1 = require("../paths");
function collectPromptVersionEvidence(options) {
    return {
        promptMarkdown: readPromptMarkdownEvidence(options.promptPath, options.promptContent),
        promptManifest: readPromptManifestEvidence({
            repositoryRoot: options.repositoryRoot,
            manifestPath: options.manifestPath,
            canonicalPromptPath: options.canonicalPromptPath
        })
    };
}
function readPromptMarkdownEvidence(promptPath, promptContent) {
    const values = readSimpleFrontMatter(promptContent);
    return {
        path: promptPath,
        promptVersion: toPositiveInteger(values.prompt_version),
        layer: readOptionalString(values.layer),
        action: readOptionalString(values.action)
    };
}
function readPromptManifestEvidence(options) {
    const manifestAbsolutePath = (0, paths_1.resolveRepositoryRelativePath)(options.repositoryRoot, options.manifestPath);
    if (!node_fs_1.default.existsSync(manifestAbsolutePath)) {
        return {
            path: options.manifestPath,
            promptManifestVersion: null,
            promptVersion: null,
            entryPath: options.canonicalPromptPath,
            entryVersion: null,
            entryLayer: null,
            entryAction: null,
            warning: `Prompt manifest '${options.manifestPath}' is missing.`
        };
    }
    let parsedManifest;
    try {
        parsedManifest = JSON.parse(node_fs_1.default.readFileSync(manifestAbsolutePath, "utf8"));
    }
    catch {
        return {
            path: options.manifestPath,
            promptManifestVersion: null,
            promptVersion: null,
            entryPath: options.canonicalPromptPath,
            entryVersion: null,
            entryLayer: null,
            entryAction: null,
            warning: `Prompt manifest '${options.manifestPath}' is malformed JSON.`
        };
    }
    if (!isPlainObject(parsedManifest)) {
        return {
            path: options.manifestPath,
            promptManifestVersion: null,
            promptVersion: null,
            entryPath: options.canonicalPromptPath,
            entryVersion: null,
            entryLayer: null,
            entryAction: null,
            warning: `Prompt manifest '${options.manifestPath}' must be object-shaped JSON.`
        };
    }
    const entries = Array.isArray(parsedManifest.prompts) ? parsedManifest.prompts : null;
    if (entries === null) {
        return {
            path: options.manifestPath,
            promptManifestVersion: toPositiveInteger(parsedManifest.prompt_manifest_version),
            promptVersion: toPositiveInteger(parsedManifest.prompt_version),
            entryPath: options.canonicalPromptPath,
            entryVersion: null,
            entryLayer: null,
            entryAction: null,
            warning: `Prompt manifest '${options.manifestPath}' is missing required 'prompts' array.`
        };
    }
    const normalizedEntryPath = options.canonicalPromptPath.replace(/\\/g, "/");
    const matchedEntry = entries.find((entry) => {
        if (!isPlainObject(entry) || typeof entry.path !== "string") {
            return false;
        }
        return entry.path.replace(/\\/g, "/") === normalizedEntryPath;
    });
    if (!isPlainObject(matchedEntry)) {
        return {
            path: options.manifestPath,
            promptManifestVersion: toPositiveInteger(parsedManifest.prompt_manifest_version),
            promptVersion: toPositiveInteger(parsedManifest.prompt_version),
            entryPath: normalizedEntryPath,
            entryVersion: null,
            entryLayer: null,
            entryAction: null,
            warning: `Prompt manifest entry '${normalizedEntryPath}' is missing from '${options.manifestPath}'.`
        };
    }
    return {
        path: options.manifestPath,
        promptManifestVersion: toPositiveInteger(parsedManifest.prompt_manifest_version),
        promptVersion: toPositiveInteger(parsedManifest.prompt_version),
        entryPath: normalizedEntryPath,
        entryVersion: toPositiveInteger(matchedEntry.version),
        entryLayer: readOptionalString(matchedEntry.layer),
        entryAction: readOptionalString(matchedEntry.action),
        warning: null
    };
}
function readSimpleFrontMatter(content) {
    const lines = content.split(/\r?\n/);
    if (lines[0] !== "---") {
        return {};
    }
    const closingIndex = lines.findIndex((line, index) => index > 0 && line === "---");
    if (closingIndex === -1) {
        return {};
    }
    const values = {};
    for (let index = 1; index < closingIndex; index += 1) {
        const match = lines[index].match(/^([A-Za-z0-9_]+):\s*(.*)$/);
        if (match === null) {
            continue;
        }
        values[match[1]] = stripYamlQuotes(match[2].trim());
    }
    return values;
}
function stripYamlQuotes(value) {
    if ((value.startsWith("\"") && value.endsWith("\""))
        || (value.startsWith("'") && value.endsWith("'"))) {
        return value.slice(1, -1);
    }
    return value;
}
function toPositiveInteger(value) {
    if (typeof value === "number" && Number.isInteger(value) && value > 0) {
        return value;
    }
    if (typeof value === "string" && /^[1-9][0-9]*$/.test(value)) {
        return Number(value);
    }
    return null;
}
function readOptionalString(value) {
    return typeof value === "string" && value.trim() !== "" ? value : null;
}
function isPlainObject(value) {
    return typeof value === "object" && value !== null && !Array.isArray(value);
}
