// tools/publish-registry.ts — SPEC-162: Handler for publish_registry tool
// Generates a .well-known/planu.json manifest from project specs.
import { readFile, mkdir, writeFile } from 'node:fs/promises';
import { join } from 'node:path';
import { listSpecs } from '../storage/spec-store.js';
import { generateManifest } from '../engine/well-known/manifest-generator.js';
import { formatSuccess, formatError } from './response-helpers.js';
/** Default output path when not specified. */
const DEFAULT_OUTPUT_BASE = process.cwd();
/**
 * Reads the project name from planu.json if it exists in the given base dir.
 * Falls back to the projectId when planu.json is not found or lacks a name.
 */
async function resolveProjectName(basePath, projectId) {
    try {
        const planuJson = join(basePath, 'planu.json');
        const raw = await readFile(planuJson, 'utf-8');
        const parsed = JSON.parse(raw);
        if (typeof parsed.name === 'string' && parsed.name.trim().length > 0) {
            return parsed.name.trim();
        }
    }
    catch {
        // planu.json not found or invalid — use projectId as name
    }
    return projectId;
}
/**
 * Handle publish_registry tool invocations.
 * Generates .well-known/planu.json in the specified output directory.
 */
export async function handlePublishRegistry(args) {
    const { projectId, outputPath, includePrivate = false } = args;
    const basePath = outputPath ?? DEFAULT_OUTPUT_BASE;
    const specs = await listSpecs(projectId);
    if (specs.length === 0) {
        return {
            content: [
                {
                    type: 'text',
                    text: formatError(`No specs found for project "${projectId}".`, 'Run list_specs to verify the projectId, or create specs first with create_spec.'),
                },
            ],
            isError: true,
        };
    }
    const projectName = await resolveProjectName(basePath, projectId);
    const manifest = generateManifest({ projectName, specs, includePrivate });
    const wellKnownDir = join(basePath, '.well-known');
    const manifestPath = join(wellKnownDir, 'planu.json');
    await mkdir(wellKnownDir, { recursive: true });
    await writeFile(manifestPath, JSON.stringify(manifest, null, 2), 'utf-8');
    const privateNote = includePrivate ? ' (including private/draft specs)' : '';
    const body = [
        `**Project**: ${manifest.name}`,
        `**Specs included**: ${String(manifest.specCount)}${privateNote}`,
        `**Capabilities**: ${manifest.capabilities.join(', ')}`,
        `**Generated at**: ${manifest.generatedAt}`,
        '',
        `Manifest written to: \`${manifestPath}\``,
        '',
        'Teams can discover this registry by reading `.well-known/planu.json` at your project root.',
    ].join('\n');
    return {
        content: [
            {
                type: 'text',
                text: formatSuccess('Registry manifest published', body, [
                    'Share the manifest path with other teams to enable spec discovery.',
                    'Use discover_registry to read and validate a manifest from another project.',
                ]),
            },
        ],
    };
}
//# sourceMappingURL=publish-registry.js.map