// @crash-shield-ignore-file — config/cache reader for Planu-controlled JSON; writer is this codebase, shape guaranteed by build/seed.
// tools/skill-registry/search.ts — Handler for skill_search tool (SPEC-150, updated SPEC-606)
import { searchAllRegistries } from '../../engine/skill-registry/index.js';
import { searchSkillsUniversal } from '../../engine/skill-discovery/index.js';
import { formatSuccess, toolResult } from '../response-helpers.js';
import { ti } from '../../i18n/index.js';
import { readFileSync } from 'node:fs';
import { join, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
const __dirname = dirname(fileURLToPath(import.meta.url));
const DEFAULT_REGISTRIES = [
    {
        id: 'builtin',
        name: 'Planu Built-in Skills',
        url: 'local://skill-catalog',
        type: 'api',
        priority: 0,
        enabled: true,
    },
    {
        id: 'anthropic',
        name: 'Anthropic Official Skills',
        url: 'https://github.com/anthropics/skills',
        type: 'github',
        priority: 1,
        enabled: true,
    },
    {
        id: 'agentskill',
        name: 'AgentSkill.sh',
        url: 'https://agentskill.sh',
        type: 'api',
        priority: 2,
        enabled: true,
    },
    {
        id: 'skillssh',
        name: 'Skills.sh',
        url: 'https://skills.sh',
        type: 'npm',
        priority: 3,
        enabled: true,
    },
];
export function loadRegistries() {
    // Try compiled path first (dist/config/), then source path (src/config/)
    const compiledPath = join(__dirname, '../../config/skill-registries.json');
    const sourcePath = join(__dirname, '../../../src/config/skill-registries.json');
    for (const configPath of [compiledPath, sourcePath]) {
        let raw;
        try {
            raw = readFileSync(configPath, 'utf-8');
        }
        catch {
            // File not found at this path — try next
            continue;
        }
        if (!raw.trim()) {
            // Empty file — skip, try next path
            continue;
        }
        try {
            return JSON.parse(raw);
        }
        catch {
            console.warn('[skill_search] skill-registries.json is corrupted, using defaults');
            return DEFAULT_REGISTRIES;
        }
    }
    return DEFAULT_REGISTRIES;
}
export async function handleSkillSearch(params) {
    try {
        const registries = loadRegistries();
        // Guard: query must be a non-empty string to avoid returning unfiltered catalog dumps
        const query = typeof params.query === 'string' ? params.query.trim() : '';
        if (query.length === 0) {
            return toolResult(formatSuccess('No query provided', 'Provide a search term to find skills. Example: `skill_search({ query: "testing", projectPath: "..." })`'), { results: [], count: 0 });
        }
        const limit = Math.max(1, Math.min(params.limit ?? 10, 50));
        // SPEC-606: When sources are specified, delegate to the universal discovery engine.
        // Otherwise, use the existing registry-based search for backward compatibility.
        if (params.sources && params.sources.length > 0) {
            const universalResults = await searchSkillsUniversal(query, {
                stack: params.stack,
                limit,
                sources: params.sources,
            });
            const lines = [];
            if (universalResults.length === 0) {
                lines.push(`No skills found matching **"${query}"** in sources: ${params.sources.join(', ')}.`);
                lines.push('');
                lines.push('Try a broader query or remove the sources filter.');
            }
            else {
                lines.push('| # | Skill | Source | Description |');
                lines.push('|---|-------|--------|-------------|');
                universalResults.forEach((r, i) => {
                    const desc = r.description.length > 80 ? r.description.slice(0, 77) + '...' : r.description;
                    lines.push(`| ${String(i + 1)} | **${r.name}** | ${r.source} | ${desc} |`);
                });
                lines.push('');
                lines.push('Install with: `skill_install({ name: "skill-name", projectPath: "..." })`');
            }
            const markdown = formatSuccess(`Found ${String(universalResults.length)} skill${universalResults.length !== 1 ? 's' : ''} (universal search)`, lines.join('\n'));
            return toolResult(markdown, { results: universalResults, count: universalResults.length });
        }
        const searchParams = {
            query,
            registry: params.registry,
            stack: params.stack,
            limit,
        };
        const enabledCount = registries.filter((r) => {
            if (!r.enabled) {
                return false;
            }
            if (searchParams.registry &&
                searchParams.registry !== 'all' &&
                r.id !== searchParams.registry) {
                return false;
            }
            return true;
        }).length;
        const results = await searchAllRegistries(searchParams, registries);
        const lines = [];
        if (results.length === 0) {
            if (enabledCount === 0) {
                lines.push('No skill registries are enabled. Check your `skill-registries.json` configuration.');
            }
            else {
                lines.push(`No skills found matching **"${query}"**.`);
                lines.push('');
                lines.push('Suggestions:');
                lines.push('- Try a broader search term (e.g., "test" instead of "unit-testing")');
                lines.push('- Omit the `registry` filter to search all registries');
                lines.push('- Check network connectivity to skill registries');
                lines.push('- Use `sources: ["github"]` for broader universal search (SPEC-606)');
            }
        }
        else {
            lines.push('| # | Skill | Source | Description |');
            lines.push('|---|-------|--------|-------------|');
            results.forEach((r, i) => {
                const desc = r.description.length > 80 ? r.description.slice(0, 77) + '...' : r.description;
                lines.push(`| ${String(i + 1)} | **${r.name}** | ${r.source} | ${desc} |`);
            });
            lines.push('');
            lines.push('Install with: `skill_install({ name: "skill-name", projectPath: "..." })`');
        }
        const markdown = formatSuccess(`Found ${String(results.length)} skill${results.length !== 1 ? 's' : ''}`, lines.join('\n'));
        return toolResult(markdown, { results, count: results.length });
    }
    catch (error) {
        const msg = error instanceof Error ? error.message : String(error);
        return toolResult(ti('errors.internalError', { message: msg }) + (msg ? ` ${msg}` : ''), undefined, true);
    }
}
//# sourceMappingURL=search.js.map