"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.discoverExtensionManifests = discoverExtensionManifests;
const fs = __importStar(require("fs/promises"));
const path = __importStar(require("path"));
const skillLoader_1 = require("./skillLoader");
async function discoverExtensionManifests(projectDir) {
    const [plugins, skills] = await Promise.all([
        discoverPluginManifests(path.join(projectDir, '.harness', 'plugins')),
        discoverSkillManifests(path.join(projectDir, '.harness', 'skills')),
    ]);
    return [...plugins, ...skills].sort((a, b) => a.name.localeCompare(b.name) || a.filePath.localeCompare(b.filePath));
}
async function discoverPluginManifests(pluginsDir) {
    const files = await findManifestFiles(pluginsDir);
    const manifests = [];
    for (const filePath of files) {
        try {
            const raw = await fs.readFile(filePath, 'utf-8');
            const parsed = filePath.endsWith('.json') ? JSON.parse(raw) : parseSimpleYaml(raw);
            const name = stringField(parsed.name) || path.basename(path.dirname(filePath));
            manifests.push({
                kind: 'plugin',
                name,
                description: stringField(parsed.description),
                version: stringField(parsed.version),
                source: 'project',
                filePath,
                enabled: parsed.enabled !== false,
                providesTools: stringList(parsed.providesTools ?? parsed.provides_tools),
                providesHooks: stringList(parsed.providesHooks ?? parsed.provides_hooks),
                triggers: [],
            });
        }
        catch {
            // Ignore malformed extension manifests during discovery.
        }
    }
    return manifests;
}
async function discoverSkillManifests(skillsDir) {
    const skills = await (0, skillLoader_1.loadSkillsDir)(skillsDir);
    return skills.map((skill) => ({
        kind: 'skill',
        name: skill.name,
        description: skill.description,
        version: '',
        source: 'project',
        filePath: skill.filePath,
        enabled: true,
        providesTools: [],
        providesHooks: [],
        triggers: skill.triggers,
    }));
}
async function findManifestFiles(root) {
    const results = [];
    try {
        const entries = await fs.readdir(root, { withFileTypes: true });
        for (const entry of entries) {
            const entryPath = path.join(root, entry.name);
            if (entry.isDirectory())
                results.push(...await findManifestFiles(entryPath));
            else if (entry.name === 'plugin.json' || entry.name === 'plugin.yaml' || entry.name === 'plugin.yml')
                results.push(entryPath);
        }
    }
    catch {
        return [];
    }
    return results;
}
function parseSimpleYaml(content) {
    const result = {};
    const lines = content.split(/\r?\n/);
    for (let index = 0; index < lines.length; index++) {
        const line = lines[index];
        const match = line.match(/^([A-Za-z_][A-Za-z0-9_]*):\s*(.*)$/);
        if (!match)
            continue;
        const key = match[1];
        const value = match[2].trim();
        if (value) {
            result[key] = value.replace(/^['"]|['"]$/g, '');
            continue;
        }
        const values = [];
        while (index + 1 < lines.length) {
            const listMatch = lines[index + 1].match(/^\s*-\s*(.+)$/);
            if (!listMatch)
                break;
            values.push(listMatch[1].trim().replace(/^['"]|['"]$/g, ''));
            index++;
        }
        result[key] = values;
    }
    return result;
}
function stringField(value) {
    return typeof value === 'string' ? value.trim() : '';
}
function stringList(value) {
    if (!Array.isArray(value))
        return [];
    return value.map((item) => typeof item === 'string' ? item.trim() : '').filter(Boolean);
}
//# sourceMappingURL=extensionManifest.js.map