var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
import { readdir, readFile } from "fs/promises";
import path from "path";
import { fileURLToPath } from "url";
import { parse as parseYaml } from "yaml";
const PLUGIN_SKILLS_DIRECTORY_PATH = fileURLToPath(new URL("../../custom/skills/", import.meta.url));
const USER_PLUGIN_SKILLS_DIRECTORY_PATH_SEGMENTS = [
    "plugins",
    "adminforth-agent",
    "skills",
];
const SKILL_MARKDOWN_FILENAME = "SKILL.md";
const SKILL_FRONTMATTER_SEPARATOR = "\n---\n";
function parseSkillManifest(directoryName, markdown) {
    var _a, _b;
    const [frontmatterBlock, instructions = ""] = markdown.split("\r\n").join("\n").split(SKILL_FRONTMATTER_SEPARATOR, 2);
    const metadata = parseYaml(frontmatterBlock);
    return {
        directoryName,
        name: (_a = metadata.name) !== null && _a !== void 0 ? _a : directoryName,
        description: (_b = metadata.description) !== null && _b !== void 0 ? _b : "",
        instructions: instructions.trim(),
    };
}
function readSkillManifest(skillsDirectoryPath, directoryName) {
    return __awaiter(this, void 0, void 0, function* () {
        const markdown = yield readFile(path.join(skillsDirectoryPath, directoryName, SKILL_MARKDOWN_FILENAME), "utf8");
        return parseSkillManifest(directoryName, markdown);
    });
}
function listDirectorySkillManifests(skillsDirectoryPath) {
    return __awaiter(this, void 0, void 0, function* () {
        try {
            const entries = yield readdir(skillsDirectoryPath, { withFileTypes: true });
            return yield Promise.all(entries
                .filter((entry) => entry.isDirectory())
                .map((entry) => entry.name)
                .sort()
                .map((directoryName) => readSkillManifest(skillsDirectoryPath, directoryName)));
        }
        catch (error) {
            if (error.code === "ENOENT") {
                return [];
            }
            throw error;
        }
    });
}
function mergeSkillManifests(skillGroups) {
    return Array.from(new Map(skillGroups.flat().map((skill) => [
        `${skill.name}:${skill.directoryName}`,
        skill,
    ])).values());
}
export function getProjectSkillsDirectoryPath(customComponentsDir) {
    return path.resolve(customComponentsDir, "skills");
}
export function getProjectPluginSkillsDirectoryPath(customComponentsDir) {
    return path.resolve(customComponentsDir, ...USER_PLUGIN_SKILLS_DIRECTORY_PATH_SEGMENTS);
}
function getProjectSkillDirectoryPaths(customComponentsDir) {
    return [
        getProjectSkillsDirectoryPath(customComponentsDir),
        getProjectPluginSkillsDirectoryPath(customComponentsDir),
    ];
}
export function listBundledSkillManifests() {
    return __awaiter(this, void 0, void 0, function* () {
        return yield listDirectorySkillManifests(PLUGIN_SKILLS_DIRECTORY_PATH);
    });
}
export function listProjectSkillManifests(customComponentsDir) {
    return __awaiter(this, void 0, void 0, function* () {
        return mergeSkillManifests(yield Promise.all(getProjectSkillDirectoryPaths(customComponentsDir).map(listDirectorySkillManifests)));
    });
}
export function listSkillManifests(customComponentsDir) {
    return __awaiter(this, void 0, void 0, function* () {
        return mergeSkillManifests([
            yield listProjectSkillManifests(customComponentsDir),
            yield listBundledSkillManifests(),
        ]);
    });
}
export function loadSkillManifest(skillName, customComponentsDir) {
    return __awaiter(this, void 0, void 0, function* () {
        var _a;
        const manifests = yield listSkillManifests(customComponentsDir);
        return ((_a = manifests.find((manifest) => manifest.name === skillName || manifest.directoryName === skillName)) !== null && _a !== void 0 ? _a : null);
    });
}
export function loadSkillMarkdown(skillName, customComponentsDir) {
    return __awaiter(this, void 0, void 0, function* () {
        const manifest = yield loadSkillManifest(skillName, customComponentsDir);
        if (!manifest) {
            return null;
        }
        const directories = [
            ...getProjectSkillDirectoryPaths(customComponentsDir),
            PLUGIN_SKILLS_DIRECTORY_PATH,
        ];
        for (const skillsDirectoryPath of directories) {
            try {
                return yield readFile(path.join(skillsDirectoryPath, manifest.directoryName, SKILL_MARKDOWN_FILENAME), "utf8");
            }
            catch (error) {
                if (error.code !== "ENOENT") {
                    throw error;
                }
            }
        }
        return null;
    });
}
