"use strict";
/**
 * HonchoMemoryProvider — cloud memory backend via Honcho.dev REST API.
 *
 * v1.11.0 — Core ↔ Agent Bridge (Eternal Memory).
 *
 * Configuration (env):
 *   - HONCHO_API_KEY    (required)   — Bearer token
 *   - HONCHO_APP_ID     (required)   — workspace/app identifier
 *   - HONCHO_BASE_URL   (optional)   — defaults to https://api.honcho.dev/v1
 *   - HONCHO_USER_ID    (optional)   — defaults to "openlife-core"
 *   - HONCHO_TIMEOUT_MS (optional)   — defaults to 8000
 *
 * Graceful degradation: any error (missing env, network, 5xx) returns the
 * empty/no-op result. Callers in MemoryOrchestrator fall back to local on
 * transient errors. This provider NEVER throws to the caller — it logs and
 * returns benign defaults so memory writes/reads never crash the daemon.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.HonchoMemoryProvider = void 0;
function readConfig() {
    const apiKey = (process.env.HONCHO_API_KEY || '').trim();
    const appId = (process.env.HONCHO_APP_ID || '').trim();
    if (!apiKey || !appId)
        return null;
    return {
        apiKey,
        appId,
        baseUrl: (process.env.HONCHO_BASE_URL || 'https://api.honcho.dev/v1').replace(/\/$/, ''),
        userId: (process.env.HONCHO_USER_ID || 'openlife-core').trim(),
        timeoutMs: Number(process.env.HONCHO_TIMEOUT_MS || 8000),
    };
}
class HonchoMemoryProvider {
    name() {
        return 'honcho';
    }
    static isAvailable() {
        return readConfig() !== null;
    }
    async search(input) {
        const cfg = readConfig();
        if (!cfg)
            return [];
        try {
            const url = `${cfg.baseUrl}/apps/${encodeURIComponent(cfg.appId)}/users/${encodeURIComponent(cfg.userId)}/messages/search`;
            const body = await this.postJson(url, cfg, {
                query: input.query,
                limit: input.topK || 5,
            });
            const items = Array.isArray(body?.results) ? body.results : (Array.isArray(body) ? body : []);
            return items
                .map((item) => this.toMemoryRecord(item))
                .filter((r) => r !== null);
        }
        catch (err) {
            console.warn('[HONCHO] search failed:', err instanceof Error ? err.message : String(err));
            return [];
        }
    }
    async save(record) {
        const cfg = readConfig();
        if (!cfg)
            return;
        try {
            const url = `${cfg.baseUrl}/apps/${encodeURIComponent(cfg.appId)}/users/${encodeURIComponent(cfg.userId)}/messages`;
            await this.postJson(url, cfg, {
                content: record.content,
                metadata: {
                    id: record.id,
                    type: record.type,
                    namespace: record.namespace,
                    summary: record.summary,
                    tags: record.tags,
                    dedupeKey: record.dedupeKey,
                    keep: record.keep,
                    createdAt: record.createdAt,
                },
            });
        }
        catch (err) {
            console.warn('[HONCHO] save failed:', err instanceof Error ? err.message : String(err));
            // Swallow — write-through cache in orchestrator already wrote to local.
        }
    }
    async postJson(url, cfg, body) {
        const controller = new AbortController();
        const timer = setTimeout(() => controller.abort(), cfg.timeoutMs);
        try {
            const res = await fetch(url, {
                method: 'POST',
                headers: {
                    'Authorization': `Bearer ${cfg.apiKey}`,
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(body),
                signal: controller.signal,
            });
            if (!res.ok) {
                throw new Error(`honcho_http_${res.status}`);
            }
            return await res.json();
        }
        finally {
            clearTimeout(timer);
        }
    }
    toMemoryRecord(raw) {
        const meta = (raw.metadata && typeof raw.metadata === 'object') ? raw.metadata : {};
        const content = typeof raw.content === 'string'
            ? raw.content
            : (typeof meta.content === 'string' ? meta.content : null);
        if (!content)
            return null;
        return {
            id: String(meta.id || raw.id || `honcho-${Date.now()}`),
            type: (meta.type || 'semantic'),
            namespace: meta.namespace || {},
            content,
            summary: meta.summary,
            tags: Array.isArray(meta.tags) ? meta.tags : [],
            dedupeKey: meta.dedupeKey,
            keep: meta.keep === true,
            createdAt: meta.createdAt || raw.created_at || new Date().toISOString(),
        };
    }
}
exports.HonchoMemoryProvider = HonchoMemoryProvider;
