"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;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.handleVoiceRequest = handleVoiceRequest;
/**
 * Copyright (C) 2025 by Fonoster Inc (https://fonoster.com)
 * http://github.com/fonoster/fonoster
 *
 * This file is part of Fonoster
 *
 * Licensed under the MIT License (the "License");
 * you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *    https://opensource.org/licenses/MIT
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
const fs_1 = __importDefault(require("fs"));
const common_1 = require("@fonoster/common");
const logger_1 = require("@fonoster/logger");
const envs_1 = require("./envs");
const loadAssistantConfigFromFile_1 = require("./loadAssistantConfigFromFile");
const loadAssistantFromAPI_1 = require("./loadAssistantFromAPI");
const createLanguageModel_1 = require("./models/createLanguageModel");
const sendConversationEndedEvent_1 = require("./sendConversationEndedEvent");
const _1 = __importStar(require("."));
const logger = (0, logger_1.getLogger)({ service: "autopilot", filePath: __filename });
async function handleVoiceRequest(req, res) {
    const { accessKeyId, callerNumber, ingressNumber, sessionRef, appRef, callDirection } = req;
    logger.verbose("voice request", {
        accessKeyId,
        ingressNumber,
        sessionRef,
        appRef,
        metadata: req.metadata
    });
    const assistantConfig = envs_1.CONVERSATION_PROVIDER === _1.ConversationProvider.FILE
        ? (0, loadAssistantConfigFromFile_1.loadAssistantConfigFromFile)(envs_1.CONVERSATION_PROVIDER_FILE)
        : await (0, loadAssistantFromAPI_1.loadAssistantFromAPI)(req, JSON.parse(fs_1.default.readFileSync(envs_1.INTEGRATIONS_FILE, "utf8")));
    let knowledgeBase;
    if (envs_1.KNOWLEDGE_BASE_ENABLED) {
        knowledgeBase = new _1.S3KnowledgeBase({
            bucket: req.accessKeyId.toLowerCase(),
            documents: assistantConfig.languageModel?.knowledgeBase?.map((doc) => doc.document),
            s3Config: {
                endpoint: envs_1.AWS_S3_ENDPOINT,
                region: envs_1.AWS_S3_REGION,
                credentials: {
                    accessKeyId: envs_1.AWS_S3_ACCESS_KEY_ID,
                    secretAccessKey: envs_1.AWS_S3_SECRET_ACCESS_KEY
                },
                forcePathStyle: true
            },
            unstructuredAPIURL: envs_1.UNSTRUCTURED_API_URL,
            unstructuredAPIKey: envs_1.UNSTRUCTURED_API_KEY
        });
    }
    knowledgeBase?.load().then(() => {
        logger.verbose("knowledge base loaded");
    });
    const voice = new _1.VoiceImpl(sessionRef, res);
    const languageModel = (0, createLanguageModel_1.createLanguageModel)({
        voice,
        assistantConfig,
        knowledgeBase,
        telephonyContext: {
            callDirection,
            ingressNumber,
            callerNumber
        }
    });
    const { conversationSettings } = assistantConfig;
    const autopilot = new _1.default({
        conversationSettings: conversationSettings,
        voice: voice,
        languageModel: languageModel
    });
    autopilot.start();
    res.on(common_1.StreamEvent.END, async () => {
        autopilot.stop();
        const rawChatHistory = await languageModel.getChatHistoryMessages();
        const chatHistory = rawChatHistory
            .map((msg) => {
            if (msg.constructor.name === "HumanMessage") {
                return { human: msg.content };
            }
            else if (msg.constructor.name === "AIMessage") {
                return { ai: msg.content };
            }
            return null;
        })
            .filter(Boolean);
        if (assistantConfig.eventsHook?.url) {
            await (0, sendConversationEndedEvent_1.sendConversationEndedEvent)(assistantConfig.eventsHook, chatHistory);
        }
    });
}
