"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.MempalaceProvider = void 0;
const child_process = __importStar(require("child_process"));
const fs = __importStar(require("fs"));
const os = __importStar(require("os"));
const path = __importStar(require("path"));
const util_1 = require("util");
const execFile = (0, util_1.promisify)(child_process.execFile);
const DEFAULT_BIN = '~/.venvs/mempalace/bin/mempalace';
function expandHome(p) {
    if (!p)
        return p;
    if (p === '~')
        return os.homedir();
    if (p.startsWith('~/'))
        return path.join(os.homedir(), p.slice(2));
    return p;
}
/**
 * MemPalace é uma integração OPCIONAL. Em produção (Railway) o binário Python
 * normalmente não existe; tentar shell-out adiciona latência e ruído de log a
 * cada turno de conversa. `isAvailable()` resolve o path uma única vez e
 * retorna false silenciosamente quando o binário não está instalado, para que
 * o MemoryProviderRegistry possa pular o registro sem custo.
 */
class MempalaceProvider {
    mempalacePath;
    static cachedAvailability = null;
    static cachedPath = null;
    constructor(mempalacePath = process.env.MEMPALACE_BIN_PATH || DEFAULT_BIN) {
        this.mempalacePath = mempalacePath;
    }
    name() {
        return 'mempalace';
    }
    static isAvailable(rawPath) {
        const configured = (rawPath ?? process.env.MEMPALACE_BIN_PATH ?? DEFAULT_BIN).trim();
        if (configured === '' || configured.toLowerCase() === 'off' || configured.toLowerCase() === 'disabled') {
            MempalaceProvider.cachedAvailability = false;
            MempalaceProvider.cachedPath = null;
            return false;
        }
        if (MempalaceProvider.cachedAvailability !== null && MempalaceProvider.cachedPath === configured) {
            return MempalaceProvider.cachedAvailability;
        }
        const resolved = expandHome(configured);
        let ok = false;
        try {
            ok = fs.existsSync(resolved) && fs.statSync(resolved).isFile();
        }
        catch {
            ok = false;
        }
        MempalaceProvider.cachedAvailability = ok;
        MempalaceProvider.cachedPath = configured;
        return ok;
    }
    static resetAvailabilityCache() {
        MempalaceProvider.cachedAvailability = null;
        MempalaceProvider.cachedPath = null;
    }
    async search(input) {
        if (!MempalaceProvider.isAvailable(this.mempalacePath))
            return [];
        try {
            const { stdout } = await execFile(expandHome(this.mempalacePath), ['search', input.query], { timeout: 5000 });
            if (!stdout.trim())
                return [];
            return [{
                    id: `mempalace-${Date.now()}`,
                    type: 'episodic',
                    namespace: input.namespace || {},
                    content: stdout,
                    summary: stdout.slice(0, 200),
                    createdAt: new Date().toISOString()
                }];
        }
        catch {
            return [];
        }
    }
    async save(record) {
        void record;
    }
}
exports.MempalaceProvider = MempalaceProvider;
