"use strict";
/**
 * Shared Routes — Collection item list builders
 *
 * Builds SharedItem arrays for commands, skills, and agents with
 * a short-lived in-memory cache keyed by collection type.
 */
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 (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getSharedItems = exports.getSkillOrAgentItem = exports.getCommandItems = void 0;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const config_loader_facade_1 = require("../config/config-loader-facade");
const shared_routes_path_guards_1 = require("./shared-routes-path-guards");
const shared_routes_markdown_1 = require("./shared-routes-markdown");
const shared_routes_plugins_1 = require("./shared-routes-plugins");
const SHARED_ITEMS_CACHE_TTL_MS = 1000;
const sharedItemsCache = new Map();
// ---------------------------------------------------------------------------
// Per-type item builders
// ---------------------------------------------------------------------------
function getCommandItems(sharedDir, allowedRoots) {
    const markdownFiles = (0, shared_routes_markdown_1.collectMarkdownFiles)(sharedDir, allowedRoots);
    const items = [];
    for (const markdownFile of markdownFiles) {
        const description = (0, shared_routes_markdown_1.readMarkdownDescription)(markdownFile.resolvedPath, allowedRoots);
        if (!description) {
            continue;
        }
        const relativePath = path.relative(sharedDir, markdownFile.displayPath);
        const normalizedName = relativePath.split(path.sep).join('/').replace(/\.md$/i, '');
        if (!normalizedName) {
            continue;
        }
        items.push({
            name: normalizedName,
            description,
            path: markdownFile.displayPath,
            type: 'command',
        });
    }
    return items.sort((a, b) => a.name.localeCompare(b.name));
}
exports.getCommandItems = getCommandItems;
function getSkillOrAgentItem(type, entry, entryPath, resolvedEntryPath, allowedRoots, stats) {
    if (type === 'skills') {
        if (!stats.isDirectory()) {
            return null;
        }
        const description = (0, shared_routes_markdown_1.readMarkdownDescription)(path.join(resolvedEntryPath, 'SKILL.md'), allowedRoots);
        if (!description) {
            return null;
        }
        return { name: entry.name, description, path: entryPath, type: 'skill' };
    }
    // agents
    if (stats.isDirectory()) {
        const description = (0, shared_routes_markdown_1.readFirstMarkdownDescription)([
            path.join(resolvedEntryPath, 'prompt.md'),
            path.join(resolvedEntryPath, 'AGENT.md'),
            path.join(resolvedEntryPath, 'agent.md'),
        ], allowedRoots);
        if (!description) {
            return null;
        }
        return { name: entry.name, description, path: entryPath, type: 'agent' };
    }
    if (!stats.isFile() || !entry.name.toLowerCase().endsWith('.md')) {
        return null;
    }
    const description = (0, shared_routes_markdown_1.readMarkdownDescription)(resolvedEntryPath, allowedRoots);
    if (!description) {
        return null;
    }
    return { name: entry.name.replace(/\.md$/i, ''), description, path: entryPath, type: 'agent' };
}
exports.getSkillOrAgentItem = getSkillOrAgentItem;
// ---------------------------------------------------------------------------
// Public cache-backed entry point
// ---------------------------------------------------------------------------
function getSharedItems(type) {
    const ccsDir = (0, config_loader_facade_1.getCcsDir)();
    const sharedDir = path.join(ccsDir, 'shared', type);
    const now = Date.now();
    if (!fs.existsSync(sharedDir)) {
        sharedItemsCache.delete(type);
        return [];
    }
    const cached = sharedItemsCache.get(type);
    if (cached && cached.sharedDir === sharedDir && cached.expiresAt > now) {
        return cached.items;
    }
    const sharedDirRoot = (0, shared_routes_path_guards_1.safeRealPath)(sharedDir) ?? path.resolve(sharedDir);
    const allowedRoots = (0, shared_routes_path_guards_1.resolveAllowedRoots)(type, ccsDir, sharedDirRoot);
    if (type === 'commands') {
        const commandItems = getCommandItems(sharedDir, allowedRoots);
        sharedItemsCache.set(type, {
            items: commandItems,
            sharedDir,
            expiresAt: now + SHARED_ITEMS_CACHE_TTL_MS,
        });
        return commandItems;
    }
    if (type === 'plugins') {
        const pluginItems = (0, shared_routes_plugins_1.getPluginItems)(sharedDir, allowedRoots);
        sharedItemsCache.set(type, {
            items: pluginItems,
            sharedDir,
            expiresAt: now + SHARED_ITEMS_CACHE_TTL_MS,
        });
        return pluginItems;
    }
    // skills | agents
    const items = [];
    try {
        const entries = fs.readdirSync(sharedDir, { withFileTypes: true });
        for (const entry of entries) {
            try {
                const entryPath = path.join(sharedDir, entry.name);
                const resolvedEntryPath = (0, shared_routes_path_guards_1.safeRealPath)(entryPath);
                if (!resolvedEntryPath || !(0, shared_routes_path_guards_1.isPathWithinAny)(resolvedEntryPath, allowedRoots)) {
                    continue;
                }
                const stats = fs.statSync(resolvedEntryPath);
                const item = getSkillOrAgentItem(type, entry, entryPath, resolvedEntryPath, allowedRoots, stats);
                if (!item) {
                    continue;
                }
                items.push(item);
            }
            catch {
                // Fail soft per entry so one bad item does not hide valid results.
            }
        }
    }
    catch {
        // Directory read failed — return empty list
    }
    const sortedItems = items.sort((a, b) => a.name.localeCompare(b.name));
    sharedItemsCache.set(type, {
        items: sortedItems,
        sharedDir,
        expiresAt: now + SHARED_ITEMS_CACHE_TTL_MS,
    });
    return sortedItems;
}
exports.getSharedItems = getSharedItems;
//# sourceMappingURL=shared-routes-collections.js.map