"use strict";
// Webhook notification channel for the Ollama Agent Harness.
//
// Sends POST requests to configured webhook URLs when automation jobs
// complete, autonomy runs finish, or other notable events occur.
//
// Configure via Settings → API Keys:
//   HARNESS_WEBHOOK_URL — primary webhook endpoint
//   HARNESS_WEBHOOK_SECRET — optional shared secret for HMAC signing
//
// Or via the webhooks API:
//   POST /api/webhooks { url, secret?, events? }
//   GET  /api/webhooks
//   DELETE /api/webhooks/:id
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.addWebhook = addWebhook;
exports.removeWebhook = removeWebhook;
exports.listWebhooks = listWebhooks;
exports.loadWebhooksFromEnv = loadWebhooksFromEnv;
exports.sendWebhookNotification = sendWebhookNotification;
const crypto = __importStar(require("crypto"));
const logger_1 = require("../core/logger");
const webhooks = [];
function addWebhook(config) {
    const id = `wh-${Date.now().toString(36)}-${crypto.randomBytes(3).toString('hex')}`;
    const webhook = { id, ...config };
    webhooks.push(webhook);
    return webhook;
}
function removeWebhook(id) {
    const idx = webhooks.findIndex((w) => w.id === id);
    if (idx === -1)
        return false;
    webhooks.splice(idx, 1);
    return true;
}
function listWebhooks() {
    return webhooks.map((w) => ({ ...w, secret: w.secret ? '***' : undefined }));
}
function loadWebhooksFromEnv() {
    const url = process.env.HARNESS_WEBHOOK_URL?.trim();
    if (url) {
        const existing = webhooks.find((w) => w.url === url);
        if (!existing) {
            addWebhook({
                url,
                secret: process.env.HARNESS_WEBHOOK_SECRET?.trim(),
                events: ['automation.completed', 'autonomy.completed', 'autonomy.failed'],
                enabled: true,
            });
            logger_1.logger.info('Webhook', 'Loaded webhook from env', { url });
        }
    }
}
async function sendWebhookNotification(event, data) {
    const payload = {
        event,
        timestamp: new Date().toISOString(),
        data,
    };
    const body = JSON.stringify(payload);
    let sent = 0;
    for (const webhook of webhooks) {
        if (!webhook.enabled)
            continue;
        if (webhook.events.length > 0 && !webhook.events.includes(event))
            continue;
        try {
            const headers = { 'Content-Type': 'application/json' };
            if (webhook.secret) {
                const signature = crypto.createHmac('sha256', webhook.secret).update(body).digest('hex');
                headers['X-Webhook-Signature'] = `sha256=${signature}`;
            }
            headers['X-Webhook-Event'] = event;
            const res = await fetch(webhook.url, { method: 'POST', headers, body, signal: AbortSignal.timeout(10000) });
            if (res.ok) {
                sent++;
                logger_1.logger.info('Webhook', 'Delivered', { event, url: webhook.url, status: res.status });
            }
            else {
                logger_1.logger.warn('Webhook', 'Delivery failed', { event, url: webhook.url, status: res.status });
            }
        }
        catch (err) {
            logger_1.logger.warn('Webhook', 'Delivery error', { event, url: webhook.url, error: err instanceof Error ? err.message : String(err) });
        }
    }
    return sent;
}
//# sourceMappingURL=webhooks.js.map