var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
function getHeaderValue(headers, name) {
    var _a;
    const value = (_a = headers[name]) !== null && _a !== void 0 ? _a : headers[name.toLowerCase()];
    if (Array.isArray(value)) {
        return value[0];
    }
    return typeof value === "string" ? value : undefined;
}
function getRequestOrigin(input) {
    var _a, _b, _c, _d;
    const forwardedProto = (_b = (_a = getHeaderValue(input.headers, "x-forwarded-proto")) === null || _a === void 0 ? void 0 : _a.split(",")[0]) === null || _b === void 0 ? void 0 : _b.trim();
    const forwardedHost = (_d = (_c = getHeaderValue(input.headers, "x-forwarded-host")) === null || _c === void 0 ? void 0 : _c.split(",")[0]) === null || _d === void 0 ? void 0 : _d.trim();
    const host = forwardedHost !== null && forwardedHost !== void 0 ? forwardedHost : getHeaderValue(input.headers, "host");
    if (!host) {
        return undefined;
    }
    const proto = forwardedProto !== null && forwardedProto !== void 0 ? forwardedProto : (host.startsWith("localhost") || host.startsWith("127.0.0.1") ? "http" : "https");
    return `${proto}://${host}`;
}
export function setupChatSurfaceEndpoints(ctx, server) {
    var _a;
    for (const adapter of (_a = ctx.options.chatSurfaceAdapters) !== null && _a !== void 0 ? _a : []) {
        server.endpoint({
            method: "POST",
            noAuth: true,
            path: `/agent/surface/${adapter.name}/webhook`,
            handler: (endpointInput) => __awaiter(this, void 0, void 0, function* () {
                var _a;
                const surfaceContext = {
                    body: endpointInput.body,
                    headers: endpointInput.headers,
                    abortSignal: endpointInput.abortSignal,
                    rawRequest: endpointInput._raw_express_req,
                    rawResponse: endpointInput._raw_express_res,
                };
                const incoming = yield adapter.parseIncomingMessage(surfaceContext);
                if (!incoming)
                    return { ok: true };
                incoming.metadata = Object.assign(Object.assign({}, incoming.metadata), { adminPublicOrigin: getRequestOrigin(endpointInput) });
                const sink = yield adapter.createEventSink(surfaceContext, incoming);
                try {
                    yield ctx.handleChatSurfaceMessage(adapter, incoming, sink);
                }
                finally {
                    yield ((_a = sink.close) === null || _a === void 0 ? void 0 : _a.call(sink));
                }
                return { ok: true };
            }),
        });
    }
}
