"use strict";
/**
 * SupermemoryMemoryProvider — cloud memory backend via Supermemory.ai REST API.
 *
 * v1.11.0 — Core ↔ Agent Bridge (Eternal Memory).
 *
 * Configuration (env):
 *   - SUPERMEMORY_API_KEY    (required) — Bearer token
 *   - SUPERMEMORY_BASE_URL   (optional) — defaults to https://api.supermemory.ai/v3
 *   - SUPERMEMORY_TIMEOUT_MS (optional) — defaults to 8000
 *
 * Same graceful-degradation contract as HonchoMemoryProvider: missing env or
 * network errors return empty/no-op results, never throw.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.SupermemoryMemoryProvider = void 0;
function readConfig() {
    const apiKey = (process.env.SUPERMEMORY_API_KEY || '').trim();
    if (!apiKey)
        return null;
    return {
        apiKey,
        baseUrl: (process.env.SUPERMEMORY_BASE_URL || 'https://api.supermemory.ai/v3').replace(/\/$/, ''),
        timeoutMs: Number(process.env.SUPERMEMORY_TIMEOUT_MS || 8000),
    };
}
class SupermemoryMemoryProvider {
    name() {
        return 'supermemory';
    }
    static isAvailable() {
        return readConfig() !== null;
    }
    async search(input) {
        const cfg = readConfig();
        if (!cfg)
            return [];
        try {
            const body = await this.postJson(`${cfg.baseUrl}/search`, cfg, {
                q: 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('[SUPERMEMORY] search failed:', err instanceof Error ? err.message : String(err));
            return [];
        }
    }
    async save(record) {
        const cfg = readConfig();
        if (!cfg)
            return;
        try {
            await this.postJson(`${cfg.baseUrl}/memories`, cfg, {
                content: record.content,
                customId: record.id,
                metadata: {
                    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('[SUPERMEMORY] save failed:', err instanceof Error ? err.message : String(err));
        }
    }
    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(`supermemory_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 : null;
        if (!content)
            return null;
        return {
            id: String(raw.customId || raw.id || `supermemory-${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 || new Date().toISOString(),
        };
    }
}
exports.SupermemoryMemoryProvider = SupermemoryMemoryProvider;
