"use strict";
// =============================================================================
// Pure Agent - Gateway Message Delivery
// Ported from Hermes gateway/delivery.py
// =============================================================================
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.DeliveryRouter = void 0;
exports.parseDeliveryTarget = parseDeliveryTarget;
const path = __importStar(require("path"));
const fs = __importStar(require("fs"));
const config_1 = require("./config");
const constants_1 = require("../constants");
// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------
const MAX_PLATFORM_OUTPUT = 4000;
function parseDeliveryTarget(target, origin) {
    if (target === 'local') {
        return { platform: config_1.Platform.LOCAL, isOrigin: false, isExplicit: true };
    }
    if (target === 'origin' && origin) {
        return {
            platform: origin.platform,
            chatId: origin.chatId,
            threadId: origin.threadId,
            isOrigin: true,
            isExplicit: false,
        };
    }
    // Parse: "telegram", "telegram:123", "telegram:123:456"
    const parts = target.split(':');
    const platform = parts[0];
    const chatId = parts[1];
    const threadId = parts[2];
    return {
        platform,
        chatId,
        threadId,
        isOrigin: false,
        isExplicit: true,
    };
}
// ---------------------------------------------------------------------------
// DeliveryRouter
// ---------------------------------------------------------------------------
class DeliveryRouter {
    _config;
    _adapters;
    constructor(_config, adapters) {
        this._config = _config;
        this._adapters = adapters || new Map();
    }
    setAdapters(adapters) {
        this._adapters = adapters;
    }
    async deliver(content, targets, metadata) {
        const results = {};
        for (const target of targets) {
            const key = `${target.platform}:${target.chatId || 'default'}`;
            try {
                if (target.platform === config_1.Platform.LOCAL) {
                    results[key] = this._deliverLocal(content, metadata);
                }
                else {
                    results[key] = await this._deliverToPlatform(content, target);
                }
            }
            catch (err) {
                results[key] = { success: false, error: err.message };
            }
        }
        return results;
    }
    _deliverLocal(content, metadata) {
        const outputDir = path.join((0, constants_1.getPureAgentHome)(), 'cron', 'output');
        const dir = metadata?.jobId ? path.join(outputDir, metadata.jobId) : outputDir;
        if (!fs.existsSync(dir))
            fs.mkdirSync(dir, { recursive: true });
        const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
        const filePath = path.join(dir, `${timestamp}.md`);
        fs.writeFileSync(filePath, content, 'utf-8');
        return { success: true };
    }
    async _deliverToPlatform(content, target) {
        const adapter = this._adapters.get(target.platform);
        if (!adapter) {
            return { success: false, error: `No adapter for platform ${target.platform}` };
        }
        if (!target.chatId) {
            return { success: false, error: 'No chat_id for delivery' };
        }
        // Truncate if needed
        const truncated = content.length > MAX_PLATFORM_OUTPUT
            ? content.slice(0, MAX_PLATFORM_OUTPUT - 50) + '\n\n... [truncated]'
            : content;
        const result = await adapter.send(target.chatId, truncated);
        return { success: result.success, error: result.error };
    }
}
exports.DeliveryRouter = DeliveryRouter;
//# sourceMappingURL=delivery.js.map