"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.resolveSystemPrompts = resolveSystemPrompts;
const promises_1 = require("node:fs/promises");
const node_path_1 = __importDefault(require("node:path"));
const file_readers_1 = require("../core/file-readers");
const paths_1 = require("../core/paths");
const paths_2 = require("./paths");
async function resolveSystemPrompts(input) {
    const entries = await Promise.all(input.names.map((name) => resolveSystemPrompt({
        repoRoot: input.repoRoot,
        configuredPath: input.config.paths.systemPrompts[name],
        name,
    })));
    return Object.fromEntries(entries
        .filter((entry) => entry !== null)
        .map((entry) => [entry.name, entry]));
}
async function resolveSystemPrompt(input) {
    const configuredPath = input.configuredPath;
    if (configuredPath !== undefined) {
        return readConfiguredSystemPrompt({
            repoRoot: input.repoRoot,
            configuredPath,
            name: input.name,
        });
    }
    const repositoryPath = node_path_1.default.join((0, paths_2.getRepoSystemPromptsDirectoryPath)(input.repoRoot), `${input.name}.md`);
    const repositoryContent = await (0, file_readers_1.readTextFileIfExists)(repositoryPath);
    if (repositoryContent !== null) {
        return {
            name: input.name,
            content: repositoryContent,
            source: node_path_1.default.posix.join(".alpaca", "system-prompts", `${input.name}.md`),
        };
    }
    const packagePath = node_path_1.default.join((0, paths_1.getPackageSystemPromptsDirectory)(), `${input.name}.md`);
    const packageContent = await (0, file_readers_1.readTextFileIfExists)(packagePath);
    if (packageContent === null) {
        throw new Error(`Missing packaged system prompt file: ${packagePath}`);
    }
    return {
        name: input.name,
        content: packageContent,
        source: node_path_1.default.posix.join("package-assets", "system", "system-prompts", `${input.name}.md`),
    };
}
async function readConfiguredSystemPrompt(input) {
    const normalizedPath = (0, paths_2.normalizeSystemPromptPath)(input.configuredPath);
    if (normalizedPath === null) {
        throw new Error(`Invalid system prompt path for ${input.name}: ${input.configuredPath}`);
    }
    const absolutePath = node_path_1.default.resolve(input.repoRoot, normalizedPath);
    const relativePath = node_path_1.default.relative(input.repoRoot, absolutePath);
    if (relativePath.startsWith("..") || node_path_1.default.isAbsolute(relativePath)) {
        throw new Error(`System prompt path for ${input.name} must stay inside the repository: ${input.configuredPath}`);
    }
    return {
        name: input.name,
        content: await (0, promises_1.readFile)(absolutePath, "utf8"),
        source: normalizedPath,
    };
}
