/**
 * Content-writing generation with legacy plugin-ai fallback.
 *
 * Brand voice analyze/fix and co-author share the governed Settings > AI path
 * first. When that path is not fully configured (no default model, missing key,
 * etc.) we fall back to @actuate-media/plugin-ai so existing installs keep
 * working.
 */
import { generateTextForFeature, } from './runtime.js';
async function importAIPlugin() {
    const mod = '@actuate-media/' + 'plugin-ai';
    return import(/* webpackIgnore: true */ mod);
}
function setupHint(code) {
    switch (code) {
        case 'no_model':
            return ('No default AI model is selected. In Settings > AI, choose a default model ' +
                'in the AI Assistant card and click Save changes.');
        case 'no_key':
            return ('No API key is available for the connected provider. Add a key under ' +
                'Provider connections or set the provider API key env var on your host.');
        case 'no_provider':
            return ('No AI provider can serve the selected model. Check Provider connections, ' +
                'refresh models, and save your default model.');
        default:
            return ('AI is not fully configured for content writing. Open Settings > AI, connect ' +
                'a provider, choose a default model, and click Save changes.');
    }
}
export async function generateContentWritingWithFallback(db, input) {
    const FEATURE = 'ai.features.contentWriting';
    const result = await generateTextForFeature(db, FEATURE, input);
    if (result.ok) {
        return { ok: true, text: result.text };
    }
    if (result.code === 'feature_disabled') {
        return { ok: false, httpStatus: 403, message: result.message };
    }
    if (result.code === 'budget_exceeded') {
        return { ok: false, httpStatus: 429, message: result.message };
    }
    if (result.code === 'provider_error') {
        return { ok: false, httpStatus: 502, message: `AI provider error: ${result.message}` };
    }
    if (result.code === 'no_provider' || result.code === 'no_model' || result.code === 'no_key') {
        try {
            const aiModule = await importAIPlugin();
            if (typeof aiModule.generate !== 'function') {
                return { ok: false, httpStatus: 501, message: setupHint(result.code) };
            }
            const parts = [input.system?.trim(), input.prompt.trim()].filter(Boolean);
            const text = await aiModule.generate(parts.join('\n\n'));
            if (!text?.trim()) {
                return { ok: false, httpStatus: 502, message: 'AI returned an empty response.' };
            }
            return { ok: true, text: text.trim() };
        }
        catch {
            return { ok: false, httpStatus: 503, message: setupHint(result.code) };
        }
    }
    return { ok: false, httpStatus: 502, message: result.message };
}
//# sourceMappingURL=content-writing-generate.js.map