// tools/registry/publish.ts — AC-7: Publish a spec to the registry
import { readFile } from 'node:fs/promises';
import { join } from 'node:path';
import { homedir } from 'node:os';
/** Load stored credentials or return null if not authenticated. */
async function loadCredentials() {
    try {
        const credPath = join(homedir(), '.planu', 'credentials.json');
        const raw = await readFile(credPath, 'utf-8');
        return JSON.parse(raw);
    }
    catch {
        return null;
    }
}
/** Check that credentials are valid and not expired. */
/* v8 ignore start -- defensive guard, loadCredentials always provides both */
function isCredentialValid(cred) {
    if (!cred.token || !cred.expiresAt) {
        return false;
    }
    return new Date(cred.expiresAt) > new Date();
}
/* v8 ignore stop */
/**
 * Handle registry_publish tool invocation.
 * Validates and publishes a spec to the registry. Requires authentication.
 */
export async function handleRegistryPublish(args) {
    try {
        // Check authentication first
        const credentials = await loadCredentials();
        if (!credentials) {
            return {
                content: [
                    {
                        type: 'text',
                        text: 'Not authenticated. Run registry_login first to store credentials.',
                    },
                ],
                isError: true,
            };
        }
        if (!isCredentialValid(credentials)) {
            return {
                content: [
                    {
                        type: 'text',
                        text: 'Credentials expired. Run registry_login to refresh your token.',
                    },
                ],
                isError: true,
            };
        }
        const specPath = args.specPath;
        const org = args.org ?? credentials.user;
        if (!specPath) {
            return {
                content: [{ type: 'text', text: 'Missing required field: specPath' }],
                isError: true,
            };
        }
        const { createRegistryClient, validateForPublish, packSpec } = await import('../../engine/spec-registry/index.js');
        // Step 1: Validate spec structure
        const validation = await validateForPublish(specPath);
        if (!validation.valid) {
            return {
                content: [
                    {
                        type: 'text',
                        text: `Spec validation failed:\n${validation.errors.map((e) => `  - ${e}`).join('\n')}`,
                    },
                ],
                isError: true,
            };
        }
        // Step 2: Pack spec files
        const tarball = await packSpec(specPath);
        // Step 3: Upload to registry
        const client = createRegistryClient(credentials.token);
        const result = await client.publishSpec(tarball, { org });
        return {
            content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
        };
    }
    catch (error) {
        /* v8 ignore start -- unexpected runtime errors */
        const message = error instanceof Error ? error.message : String(error);
        return {
            content: [{ type: 'text', text: `Registry publish failed: ${message}` }],
            isError: true,
        };
        /* v8 ignore stop */
    }
}
//# sourceMappingURL=publish.js.map