"use strict";
/**
 * test_memory_provider_selection — v1.11.0 regression suite.
 *
 * Asserts:
 *   1. OPENLIFE_MEMORY_PROVIDER unset → selectPrimary() returns 'local'
 *   2. Valid provider name → returned as primary
 *   3. Unknown provider → falls back to 'local'
 *   4. keep:true bypasses retention policy (semantic test)
 *   5. MemoryOrchestrator with primary != local writes through to local
 */
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 });
const fs = __importStar(require("fs"));
const os = __importStar(require("os"));
const path = __importStar(require("path"));
const MemoryProviderRegistry_1 = require("./memory/MemoryProviderRegistry");
const MemoryOrchestrator_1 = require("./memory/MemoryOrchestrator");
const MemoryRetentionPolicy_1 = require("./memory/MemoryRetentionPolicy");
function assert(cond, msg) {
    if (!cond)
        throw new Error(`assertion failed: ${msg}`);
}
function mkTmp() {
    return fs.mkdtempSync(path.join(os.tmpdir(), 'mem-select-test-'));
}
function rmTmp(dir) {
    try {
        fs.rmSync(dir, { recursive: true, force: true });
    }
    catch { /* ignore */ }
}
function setEnv(key, value) {
    const prev = process.env[key];
    if (value === undefined)
        delete process.env[key];
    else
        process.env[key] = value;
    return () => {
        if (prev === undefined)
            delete process.env[key];
        else
            process.env[key] = prev;
    };
}
function scenarioDefaultLocal() {
    const restore = setEnv('OPENLIFE_MEMORY_PROVIDER', undefined);
    try {
        const reg = new MemoryProviderRegistry_1.MemoryProviderRegistry();
        assert(reg.selectPrimary() === 'local', 'default must be local');
    }
    finally {
        restore();
    }
    console.log('✅ scenario 1: unset env → local');
}
function scenarioKnownProviders() {
    for (const name of ['mem0', 'honcho', 'supermemory', 'redis-ams', 'zep-graphiti']) {
        const restore = setEnv('OPENLIFE_MEMORY_PROVIDER', name);
        try {
            const reg = new MemoryProviderRegistry_1.MemoryProviderRegistry();
            assert(reg.selectPrimary() === name, `expected ${name}, got ${reg.selectPrimary()}`);
        }
        finally {
            restore();
        }
    }
    console.log('✅ scenario 2: known providers returned as primary');
}
function scenarioUnknownFallsBack() {
    const restore = setEnv('OPENLIFE_MEMORY_PROVIDER', 'mongodb-fake');
    try {
        const reg = new MemoryProviderRegistry_1.MemoryProviderRegistry();
        assert(reg.selectPrimary() === 'local', 'unknown → local fallback');
    }
    finally {
        restore();
    }
    console.log('✅ scenario 3: unknown provider → local fallback');
}
function scenarioKeepFlagSemantic() {
    const policy = new MemoryRetentionPolicy_1.MemoryRetentionPolicy();
    // Working memory: would normally expire after 7 days
    const oldWorking = {
        id: 't1', type: 'working', namespace: {}, content: 'old',
        createdAt: new Date(Date.now() - 30 * 86400_000).toISOString(),
    };
    const decisionNoKeep = policy.decide(oldWorking);
    assert(decisionNoKeep.keep === false, 'old working without keep → expires');
    const decisionWithKeep = policy.decide({ ...oldWorking, keep: true });
    assert(decisionWithKeep.keep === true, 'keep:true bypasses expiry');
    console.log('✅ scenario 4: keep:true bypasses retention expiry');
}
async function scenarioWriteThroughLocal() {
    // Strategy: configure local-only (primary=local) AND verify orchestrator
    // resolves to local. Mocking cloud providers via env requires API keys we
    // don't have in CI — instead we test the resolver logic by setting primary
    // to a registered but unconfigured cloud provider (honcho without keys
    // would normally still register since the constructor doesn't fail).
    const tmp = mkTmp();
    const restores = [
        setEnv('OPENLIFE_MEMORY_DIR', tmp),
        setEnv('OPENLIFE_MEMORY_PROVIDER', 'honcho'),
        // Force HONCHO_API_KEY absent so honcho.save() is a no-op
        setEnv('HONCHO_API_KEY', undefined),
        setEnv('HONCHO_APP_ID', undefined),
    ];
    try {
        const orch = new MemoryOrchestrator_1.MemoryOrchestrator();
        await orch.save({
            type: 'semantic',
            content: 'write-through fact',
            tags: ['test'],
            keep: true,
        });
        // Local file MUST contain the record even though primary was honcho
        const localFile = path.join(tmp, 'memory-records.json');
        assert(fs.existsSync(localFile), 'local cache file must exist after write-through');
        const records = JSON.parse(fs.readFileSync(localFile, 'utf-8'));
        assert(Array.isArray(records) && records.length === 1, `expected 1 local record, got ${records?.length}`);
        assert(records[0].content === 'write-through fact', 'content preserved');
        assert(records[0].keep === true, 'keep flag preserved');
    }
    finally {
        for (const r of restores)
            r();
        rmTmp(tmp);
    }
    console.log('✅ scenario 5: primary != local writes through to local cache');
}
(async () => {
    try {
        scenarioDefaultLocal();
        scenarioKnownProviders();
        scenarioUnknownFallsBack();
        scenarioKeepFlagSemantic();
        await scenarioWriteThroughLocal();
        console.log('TEST_MEMORY_PROVIDER_SELECTION_OK');
    }
    catch (err) {
        console.error('TEST_MEMORY_PROVIDER_SELECTION_FAIL', err);
        process.exit(1);
    }
})();
