// tools/discover-registry.ts — SPEC-162: Handler for discover_registry tool
// Reads and validates a .well-known/planu.json manifest from a local file path.
import { readFile } from 'node:fs/promises';
import { parseManifest } from '../engine/well-known/discovery.js';
import { formatSuccess, formatError } from './response-helpers.js';
/**
 * Handle discover_registry tool invocations.
 * Reads and parses a .well-known/planu.json manifest from a local path.
 */
export async function handleDiscoverRegistry(args) {
    const { manifestPath } = args;
    let rawJson;
    try {
        rawJson = await readFile(manifestPath, 'utf-8');
    }
    catch (err) {
        const isNotFound = err instanceof Error && 'code' in err && err.code === 'ENOENT';
        const hint = isNotFound
            ? 'The file does not exist. Check the path or run publish_registry first to generate a manifest.'
            : 'Check that the file is readable and the path is correct.';
        return {
            content: [
                {
                    type: 'text',
                    text: formatError(`Could not read manifest at "${manifestPath}".`, hint),
                },
            ],
            isError: true,
        };
    }
    const result = parseManifest(manifestPath, rawJson);
    if (!result.valid || result.manifest === undefined) {
        const errorList = (result.errors ?? ['Unknown validation error'])
            .map((e) => `- ${e}`)
            .join('\n');
        return {
            content: [
                {
                    type: 'text',
                    text: formatError(`Invalid manifest at "${manifestPath}".`, `Fix the following validation errors:\n${errorList}`),
                },
            ],
            isError: true,
        };
    }
    const { manifest } = result;
    const specList = manifest.specs.length === 0
        ? '_No specs in this manifest._'
        : manifest.specs
            .slice(0, 10)
            .map((s) => `- **${s.id}** — ${s.title} (\`${s.status}\`)`)
            .join('\n') +
            (manifest.specs.length > 10
                ? `\n- _...and ${String(manifest.specs.length - 10)} more_`
                : '');
    const body = [
        `**Project**: ${manifest.name}`,
        `**Manifest version**: v${String(manifest.version)}`,
        `**Total specs**: ${String(manifest.specCount)}`,
        `**Capabilities**: ${manifest.capabilities.length > 0 ? manifest.capabilities.join(', ') : 'none'}`,
        `**Generated at**: ${manifest.generatedAt}`,
        '',
        '### Specs',
        specList,
    ].join('\n');
    return {
        content: [
            {
                type: 'text',
                text: formatSuccess('Registry discovered', body, [
                    'Use registry_install to import specific specs from this registry.',
                    'Share your own manifest with publish_registry.',
                ]),
            },
        ],
        structuredContent: { manifest },
    };
}
//# sourceMappingURL=discover-registry.js.map