"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.aiOrch = exports.ctxWindow = exports.vecSearch = void 0;
exports.loadOutcomeHistory = loadOutcomeHistory;
exports.persistOutcome = persistOutcome;
exports.queryOutcomes = queryOutcomes;
exports.getOutcomeCounts = getOutcomeCounts;
exports.loadFailureMemory = loadFailureMemory;
exports.persistFailure = persistFailure;
exports.getPersistedFailures = getPersistedFailures;
exports.getPersistedFailure = getPersistedFailure;
exports.loadWorkflowMemory = loadWorkflowMemory;
exports.persistWorkflowSession = persistWorkflowSession;
exports.getPersistedWorkflows = getPersistedWorkflows;
exports.getPersistedWorkflow = getPersistedWorkflow;
exports.loadTimeSavedMemory = loadTimeSavedMemory;
exports.persistTimeSaved = persistTimeSaved;
exports.getPersistedTimeSaved = getPersistedTimeSaved;
exports.initializeMemory = initializeMemory;
exports.getMemoryStats = getMemoryStats;
exports.clearAllMemory = clearAllMemory;
exports.indexMemoryForSearch = indexMemoryForSearch;
exports.searchMemory = searchMemory;
exports.addWindowEntry = addWindowEntry;
exports.getWindow = getWindow;
exports.aiQuery = aiQuery;
exports.estimateQueryCost = estimateQueryCost;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const os = __importStar(require("os"));
const memory_store_1 = require("../../../core/memory-store");
const MEMORY_DIR = path.join(os.homedir(), '.fivo', 'cell', 'memory');
function ensureDir() {
    if (!fs.existsSync(MEMORY_DIR)) {
        fs.mkdirSync(MEMORY_DIR, { recursive: true });
    }
}
function filePath(name) {
    return path.join(MEMORY_DIR, `${name}.json`);
}
function readJson(name, fallback) {
    try {
        const fp = filePath(name);
        if (!fs.existsSync(fp))
            return fallback;
        return JSON.parse(fs.readFileSync(fp, 'utf-8'));
    }
    catch {
        return fallback;
    }
}
function writeJson(name, data) {
    ensureDir();
    fs.writeFileSync(filePath(name), JSON.stringify(data, null, 2), 'utf-8');
}
let outcomeHistory = [];
const MAX_OUTCOMES = 5000;
function loadOutcomeHistory() {
    outcomeHistory = readJson('outcomes', []);
    return outcomeHistory;
}
function persistOutcome(record) {
    outcomeHistory.push(record);
    if (outcomeHistory.length > MAX_OUTCOMES) {
        outcomeHistory = outcomeHistory.slice(outcomeHistory.length - MAX_OUTCOMES);
    }
    writeJson('outcomes', outcomeHistory);
}
function queryOutcomes(limit = 100, patternId) {
    let results = outcomeHistory;
    if (patternId)
        results = results.filter((r) => r.patternId === patternId);
    return results.slice(-limit);
}
function getOutcomeCounts() {
    const total = outcomeHistory.length;
    const accepts = outcomeHistory.filter((r) => r.action === 'accept').length;
    const rejects = outcomeHistory.filter((r) => r.action === 'reject').length;
    const retries = outcomeHistory.filter((r) => r.action === 'retry').length;
    return { total, accepts, rejects, retries };
}
let failureRecords = new Map();
function loadFailureMemory() {
    const data = readJson('failures', []);
    failureRecords = new Map(data);
    return failureRecords;
}
function persistFailure(record) {
    failureRecords.set(record.patternId, record);
    writeJson('failures', Array.from(failureRecords.entries()));
}
function getPersistedFailures() {
    return Array.from(failureRecords.values());
}
function getPersistedFailure(patternId) {
    return failureRecords.get(patternId);
}
let workflowSessions = new Map();
function loadWorkflowMemory() {
    const data = readJson('workflows', []);
    workflowSessions = new Map(data);
    return workflowSessions;
}
function persistWorkflowSession(session) {
    workflowSessions.set(session.sessionId, session);
    writeJson('workflows', Array.from(workflowSessions.entries()));
}
function getPersistedWorkflows() {
    return Array.from(workflowSessions.values());
}
function getPersistedWorkflow(sessionId) {
    return workflowSessions.get(sessionId);
}
let timeSavedRecords = [];
const MAX_TIME_SAVED = 10000;
function loadTimeSavedMemory() {
    timeSavedRecords = readJson('time_saved', []);
    return timeSavedRecords;
}
function persistTimeSaved(record) {
    timeSavedRecords.push(record);
    if (timeSavedRecords.length > MAX_TIME_SAVED) {
        timeSavedRecords = timeSavedRecords.slice(timeSavedRecords.length - MAX_TIME_SAVED);
    }
    writeJson('time_saved', timeSavedRecords);
}
function getPersistedTimeSaved() {
    return timeSavedRecords;
}
function initializeMemory() {
    ensureDir();
    loadOutcomeHistory();
    loadFailureMemory();
    loadWorkflowMemory();
    loadTimeSavedMemory();
}
function getMemoryStats() {
    const outcomes = outcomeHistory.length;
    const failures = failureRecords.size;
    const workflows = workflowSessions.size;
    const timeSaved = timeSavedRecords.length;
    const totalTime = timeSavedRecords.reduce((s, r) => s + r.estimatedSeconds, 0);
    return {
        outcomeCount: outcomes,
        failureCount: failures,
        workflowCount: workflows,
        timeSavedCount: timeSaved,
        totalTimeSavedSeconds: totalTime,
        memoryDir: MEMORY_DIR,
    };
}
function clearAllMemory() {
    outcomeHistory = [];
    failureRecords.clear();
    workflowSessions.clear();
    timeSavedRecords = [];
    ensureDir();
    writeJson('outcomes', []);
    writeJson('failures', []);
    writeJson('workflows', []);
    writeJson('time_saved', []);
    exports.vecSearch.clear();
    exports.ctxWindow.clear();
}
// ─── SEMANTIC SEARCH + CONTEXT + AI ORCHESTRATOR ──────
exports.vecSearch = new memory_store_1.VectorSearch();
exports.ctxWindow = new memory_store_1.ContextWindow();
exports.aiOrch = new memory_store_1.MultiAIOrchestrator();
function indexMemoryForSearch() {
    const entries = [];
    for (const o of outcomeHistory) {
        entries.push({ id: `outcome:${o.patternId}:${o.timestamp}`, text: `${o.patternId} ${o.action} ${o.description}` });
    }
    for (const [, f] of failureRecords) {
        entries.push({ id: `fail:${f.patternId}`, text: `${f.patternId} ${f.description} rejected ${f.rejectCount} times ${f.language}` });
    }
    for (const [, w] of workflowSessions) {
        entries.push({ id: `wf:${w.sessionId}`, text: `workflow ${w.sessionId} patterns ${w.patternIds.join(' ')} ${w.success ? 'success' : 'fail'}` });
    }
    for (const t of timeSavedRecords) {
        entries.push({ id: `time:${t.patternId}:${t.timestamp}`, text: `${t.patternId} ${t.description} saved ${t.estimatedSeconds}s ${t.language}` });
    }
    exports.vecSearch.clear();
    exports.vecSearch.indexBatch(entries);
}
function searchMemory(query, limit = 5) {
    return exports.vecSearch.search(query, limit);
}
function addWindowEntry(role, content) {
    return exports.ctxWindow.add(role, content);
}
function getWindow() {
    return exports.ctxWindow.getWindow();
}
async function aiQuery(prompt, preferredModel) {
    const context = exports.ctxWindow.getWindow().map((e) => `[${e.role}]: ${e.content}`).join('\n');
    const result = await exports.aiOrch.generate(prompt, context, preferredModel);
    exports.ctxWindow.add('user', prompt);
    exports.ctxWindow.add('assistant', result);
    return result;
}
function estimateQueryCost(prompt, preferredModel) {
    return exports.aiOrch.estimateCost(prompt, preferredModel);
}
//# sourceMappingURL=ai-memory.js.map