/**
 * Server-side content-gate route handler factory.
 *
 * A lightweight LLM gate that decides whether a piece of client text is worth
 * running through document-style validation rules. Used by the thread form to
 * suppress validation noise on conversational client replies ("I don't have
 * those receipts") while still running validation when the client actually
 * submits document-like content.
 *
 * The gate response is never shown to the client — it only controls whether
 * the full validation pipeline fires.
 *
 * Usage:
 *   import { create_content_gate_route } from 'hazo_collab_forms/lib';
 *   export const POST = create_content_gate_route({ hazo_connect_adapter: getHazoConnect() });
 */
import 'server-only';
import { get_config } from './config.js';
// ============================================================================
// Helpers
// ============================================================================
function substitute_variables(prompt, variables) {
    return prompt.replace(/\{\{(\w+)\}\}/g, (_, key) => variables[key] ?? `{{${key}}}`);
}
function parse_gate_response(text) {
    const cleaned = text.trim();
    const try_parse = (candidate) => {
        try {
            const parsed = JSON.parse(candidate);
            return {
                has_content: parsed?.has_content === true,
                reason: typeof parsed?.reason === 'string' ? parsed.reason : '',
            };
        }
        catch {
            return null;
        }
    };
    const direct = try_parse(cleaned);
    if (direct)
        return direct;
    const fence = cleaned.match(/```(?:json)?\s*\n?([\s\S]*?)\n?```/);
    if (fence) {
        const parsed = try_parse(fence[1].trim());
        if (parsed)
            return parsed;
    }
    const braces = cleaned.match(/\{[\s\S]*\}/);
    if (braces) {
        const parsed = try_parse(braces[0]);
        if (parsed)
            return parsed;
    }
    // Fail-closed: if we can't parse, assume no content — keeps AI invisible
    return { has_content: false, reason: 'gate response unparseable; defaulting to false' };
}
// ============================================================================
// Route Handler Factory
// ============================================================================
export function create_content_gate_route(options) {
    const sqlite_path = options?.sqlite_path ?? get_config('hazo_connect', 'prompt_sqlite_path') ?? 'data/prompt_library.sqlite';
    const hazo_connect_adapter = options?.hazo_connect_adapter;
    const on_error = options?.on_error ?? ((err, ctx) => console.error(`[content-gate] ${ctx}:`, err));
    const prompt_area = options?.prompt_area ?? 'thread_form';
    const prompt_key = options?.prompt_key ?? 'gate_meaningful_content';
    let llm_api_module = null;
    let init_promise = null;
    async function get_llm_api() {
        if (!llm_api_module) {
            try {
                const module_id = 'hazo_llm_api/server';
                llm_api_module = await import(/* webpackIgnore: true */ module_id);
            }
            catch {
                throw new Error('hazo_llm_api is required for the content gate. Install it: npm install hazo_llm_api');
            }
        }
        return llm_api_module;
    }
    async function ensure_initialized() {
        const api = await get_llm_api();
        if (!api.is_initialized()) {
            if (!init_promise) {
                const init_config = {};
                if (hazo_connect_adapter)
                    init_config.hazo_connect = hazo_connect_adapter;
                else
                    init_config.sqlite_path = sqlite_path;
                init_promise = api.initialize_llm_api(init_config).then(() => { });
            }
            await init_promise;
        }
    }
    return async function POST(request) {
        try {
            const body = await request.json();
            const { text } = body;
            if (!text || typeof text !== 'string') {
                return Response.json({ success: false, error: 'text is required' }, { status: 400 });
            }
            await ensure_initialized();
            const api = await get_llm_api();
            const connect = api.get_hazo_connect?.() ?? null;
            if (!connect) {
                return Response.json({ success: false, error: 'hazo_llm_api hazo_connect is not available — cannot load prompts from hazo_prompts' }, { status: 500 });
            }
            const lookup = await connect.get_by_area_key(prompt_area, prompt_key);
            const db_prompt = lookup.success ? lookup.data?.prompt_text_full : undefined;
            if (!db_prompt) {
                return Response.json({ success: false, error: `Prompt ${prompt_area}/${prompt_key} not found in hazo_prompts. Seed it before calling this route (see test-app/scripts/seed-prompts.mjs).` }, { status: 500 });
            }
            const prompt_text = substitute_variables(db_prompt, { text });
            const llm_response = await api.hazo_llm_text_text({ prompt: prompt_text });
            if (!llm_response.success || !llm_response.text) {
                return Response.json({ success: false, error: llm_response.error ?? 'LLM call failed' }, { status: 500 });
            }
            const { has_content, reason } = parse_gate_response(llm_response.text);
            return Response.json({ success: true, has_content, reason });
        }
        catch (error) {
            on_error(error, 'unhandled error');
            return Response.json({ success: false, error: error instanceof Error ? error.message : 'Unknown error' }, { status: 500 });
        }
    };
}
//# sourceMappingURL=content_gate_handler.js.map