"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.LocalMemoryProvider = void 0;
const fs = __importStar(require("fs"));
const os = __importStar(require("os"));
const path = __importStar(require("path"));
const AtomicWriter_1 = require("../orchestrator/util/AtomicWriter");
const DistributedLock_1 = require("../orchestrator/util/DistributedLock");
/**
 * LocalMemoryProvider — file-backed memory store.
 *
 * v1.11.0 hardening:
 *   - Default path moved from `<cwd>/.artifacts/memory-records.json` to
 *     `<OPENLIFE_MEMORY_DIR or ~/.openlife/memory>/memory-records.json` so the
 *     core CLI and the autonomous daemon share one file regardless of cwd.
 *   - Writes go through AtomicWriter (temp+fsync+rename) so a crash mid-save
 *     never produces a half-written JSON file.
 *   - Concurrent writers serialize through a DistributedLock with 5s TTL +
 *     auto-takeover. Lock holder dies → next writer takes over in <5s instead
 *     of waiting on a stuck `flock`.
 *   - One-time migration: on first boot of v1.11+, if old
 *     `<cwd>/.artifacts/memory-records.json` exists and the new location is
 *     empty, copy forward. The old file is NEVER deleted (user-data safety).
 */
const LOCK_KEY = 'memory.local';
const LOCK_TTL_MS = 5_000;
function resolveStoreDir() {
    const explicit = process.env.OPENLIFE_MEMORY_DIR;
    if (explicit && explicit.trim())
        return explicit;
    return path.join(os.homedir(), '.openlife', 'memory');
}
function legacyStorePath(root) {
    return path.join(root, '.artifacts', 'memory-records.json');
}
class LocalMemoryProvider {
    filePath;
    lock;
    migrationChecked = false;
    legacyRoot;
    constructor(root = process.cwd()) {
        const dir = resolveStoreDir();
        this.filePath = path.join(dir, 'memory-records.json');
        this.legacyRoot = root;
        fs.mkdirSync(dir, { recursive: true });
        // Lock files live alongside the manifest under the same state dir so
        // crash-takeover works across processes that share the memory store.
        this.lock = new DistributedLock_1.DistributedLock({ baseDir: path.join(dir, 'locks') });
    }
    name() {
        return 'local';
    }
    async search(input) {
        this.maybeMigrate();
        const records = this.getAll();
        const terms = input.query.toLowerCase().split(/\s+/).filter(Boolean);
        const filtered = records
            .map(record => {
            const hay = `${record.content} ${record.summary || ''} ${(record.tags || []).join(' ')}`.toLowerCase();
            const namespaceOk = !input.namespace || this.matchNamespace(record.namespace, input.namespace);
            const typeOk = !input.types?.length || input.types.includes(record.type);
            const score = terms.reduce((acc, term) => acc + (hay.includes(term) ? 1 : 0), 0);
            return { record, namespaceOk, typeOk, score };
        })
            .filter(item => item.namespaceOk && item.typeOk && item.score > 0)
            .sort((a, b) => b.score - a.score)
            .map(item => item.record);
        return filtered.slice(0, input.topK || 5);
    }
    async save(record) {
        this.maybeMigrate();
        // Serialize writes through a distributed file lock. Acquire+retry loop
        // bounded so a stale lock from a crashed peer auto-takes-over after TTL.
        const startMs = Date.now();
        const maxWaitMs = LOCK_TTL_MS * 3; // worst case: wait one full TTL for takeover
        let acquired = this.lock.acquire(LOCK_KEY, LOCK_TTL_MS);
        while (!acquired.ok && Date.now() - startMs < maxWaitMs) {
            await new Promise(resolve => setTimeout(resolve, 100));
            acquired = this.lock.acquire(LOCK_KEY, LOCK_TTL_MS);
        }
        if (!acquired.ok) {
            // Last-resort: write anyway. Better to risk a last-writer-wins clobber
            // than to drop user facts entirely. AtomicWriter still guarantees we
            // never produce a half-written file — worst case a peer's record is
            // overwritten, not corrupted.
            console.warn('[LOCAL-MEMORY] lock acquisition timed out, writing anyway (last-writer-wins)');
            this.commitRecord(record);
            return;
        }
        try {
            this.commitRecord(record);
        }
        finally {
            this.lock.release(acquired.lockId);
        }
    }
    commitRecord(record) {
        const all = this.getAll();
        const deduped = record.dedupeKey
            ? all.filter(item => item.dedupeKey !== record.dedupeKey)
            : all;
        deduped.push(record);
        (0, AtomicWriter_1.writeJsonAtomic)(this.filePath, deduped);
    }
    getAll() {
        if (!fs.existsSync(this.filePath))
            return [];
        try {
            return JSON.parse(fs.readFileSync(this.filePath, 'utf-8'));
        }
        catch {
            return [];
        }
    }
    maybeMigrate() {
        if (this.migrationChecked)
            return;
        this.migrationChecked = true;
        // Skip if new store already has data — migration only runs against empty.
        if (fs.existsSync(this.filePath)) {
            try {
                const existing = JSON.parse(fs.readFileSync(this.filePath, 'utf-8'));
                if (Array.isArray(existing) && existing.length > 0)
                    return;
            }
            catch { /* corrupt — fall through to migration */ }
        }
        const legacy = legacyStorePath(this.legacyRoot);
        if (!fs.existsSync(legacy))
            return;
        try {
            const legacyRaw = fs.readFileSync(legacy, 'utf-8');
            const parsed = JSON.parse(legacyRaw);
            if (!Array.isArray(parsed) || parsed.length === 0)
                return;
            (0, AtomicWriter_1.writeJsonAtomic)(this.filePath, parsed);
            console.log(`[LOCAL-MEMORY] migrated ${parsed.length} record(s) from ${legacy} → ${this.filePath} (legacy file kept intact)`);
        }
        catch (err) {
            console.error('[LOCAL-MEMORY] migration failed (continuing with empty store):', err);
        }
    }
    matchNamespace(a, b) {
        return Object.entries(b).every(([k, v]) => !v || a?.[k] === v);
    }
    /** Exposed for tests so they can target the actual on-disk file. */
    _filePath() {
        return this.filePath;
    }
}
exports.LocalMemoryProvider = LocalMemoryProvider;
