"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.OmniMemory = void 0;
const child_process = __importStar(require("child_process"));
const util_1 = require("util");
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const LocalMemoryProvider_1 = require("./LocalMemoryProvider");
const MempalaceProvider_1 = require("./MempalaceProvider");
const MemoryOrchestrator_1 = require("./MemoryOrchestrator");
const ToolsetGuard_1 = require("../orchestrator/toolset/ToolsetGuard");
const exec = (0, util_1.promisify)(child_process.exec);
class OmniMemory {
    mempalacePath;
    localProvider;
    orchestrator;
    constructor() {
        this.mempalacePath = process.env.MEMPALACE_BIN_PATH || '~/.venvs/mempalace/bin/mempalace';
        this.localProvider = new LocalMemoryProvider_1.LocalMemoryProvider();
        this.orchestrator = new MemoryOrchestrator_1.MemoryOrchestrator();
    }
    async search(query, namespace) {
        const queryObj = { query, topK: 5, namespace };
        // v1.11.0 — let MemoryOrchestrator pick providers via selectPrimary so
        // OPENLIFE_MEMORY_PROVIDER drives the cloud path (with local cache).
        const hits = await this.orchestrator.search(queryObj);
        if (hits.length) {
            return hits.map(hit => `- [${hit.provider}] ${hit.record.summary || hit.record.content}`).join('\n');
        }
        if (!MempalaceProvider_1.MempalaceProvider.isAvailable(this.mempalacePath)) {
            return '';
        }
        console.log(`[OMNI-MEMORY] Buscando no MemPalace: "${query}"...`);
        try {
            const safeQuery = query.replace(/"/g, '\\"');
            const command = `bash -c "${this.mempalacePath} search \\\"${safeQuery}\\\""`;
            const timeoutMs = Number(process.env.OPENLIFE_MEMORY_SEARCH_TIMEOUT_MS || 1500);
            const { stdout } = await exec(command, { timeout: timeoutMs });
            if (!stdout.trim() || stdout.includes("No results found")) {
                return "";
            }
            const citation = `\n\n[RAG de Evidências: Buscado em ${new Date().toISOString()}]`;
            return stdout + citation;
        }
        catch (_error) {
            return "";
        }
    }
    async saveFact(fact, metadata, namespace, opts) {
        (0, ToolsetGuard_1.assertToolsetAllowed)('memory', 'OmniMemory.saveFact');
        const content = `\n\n### Fato Salvo\n**Timestamp:** ${new Date(metadata.timestamp).toISOString()}\n**Fonte:** [${metadata.source_uri}](${metadata.source_uri})\n\n${fact}\n`;
        const evidenceFile = path.join(process.cwd(), 'evidence_log.md');
        fs.appendFileSync(evidenceFile, content);
        // v1.11.0 — no explicit providers array → orchestrator picks primary
        // from OPENLIFE_MEMORY_PROVIDER and write-through caches to local.
        await this.orchestrator.save({
            type: 'semantic',
            namespace,
            content: fact,
            summary: fact.slice(0, 180),
            tags: ['fact', 'evidence'],
            confidence: 0.85,
            dedupeKey: `${metadata.source_uri}:${fact.slice(0, 80)}`,
            keep: opts?.keep === true,
        });
        console.log(`[OMNI-MEMORY] Fato salvo com evidências em ${evidenceFile}`);
    }
    async wakeup() {
        console.log(`[OMNI-MEMORY] Executando protocolo de Wake-up (L0 + L1)...`);
        try {
            const command = `bash -c "${this.mempalacePath} wake-up"`;
            const { stdout } = await exec(command);
            return stdout;
        }
        catch (error) {
            console.error(`[OMNI-MEMORY] Erro no Wake-up:`, error);
            return "Falha ao acordar o MemPalace.";
        }
    }
}
exports.OmniMemory = OmniMemory;
