"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.OpenAIService = void 0;
const tslib_1 = require("tslib");
const client_1 = require("openai/client");
const ResponseStream_1 = require("./ResponseStream");
const checkOpenaiPackage_1 = require("./checkOpenaiPackage");
const consts_1 = require("./consts");
(0, checkOpenaiPackage_1.checkOpenaiPackage)();
class OpenAIService extends client_1.OpenAI {
    constructor(options) {
        super(options);
        this.model = options.model;
        this.agent = options.agent;
    }
    setModel(model) {
        this.model = model;
    }
    async createResponseStream(payload) {
        const metadata = this.getMetadataForResponse(payload.metadata);
        const stream = await this.responses.create(Object.assign(Object.assign({ model: this.model }, payload), { stream: true, metadata }));
        return new ResponseStream_1.ResponseStream(stream);
    }
    async getAllConvItems(convId, fetchBy = 100, order = 'asc') {
        var _a, e_1, _b, _c;
        const allConvItems = [];
        try {
            for (var _d = true, _e = tslib_1.__asyncValues(this.iterateByConvItems(convId, fetchBy, order)), _f; _f = await _e.next(), _a = _f.done, !_a; _d = true) {
                _c = _f.value;
                _d = false;
                const items = _c;
                allConvItems.push(...items);
            }
        }
        catch (e_1_1) { e_1 = { error: e_1_1 }; }
        finally {
            try {
                if (!_d && !_a && (_b = _e.return)) await _b.call(_e);
            }
            finally { if (e_1) throw e_1.error; }
        }
        return allConvItems;
    }
    async summarizeConvTitle(summarizePayload) {
        var _a;
        const { conversation, joinItems, promptForSummarization } = summarizePayload;
        let order = 'asc';
        let itemsForSummarize = 5;
        if ('byLastItems' in summarizePayload && typeof summarizePayload.byLastItems === 'number') {
            order = 'desc';
            itemsForSummarize = summarizePayload === null || summarizePayload === void 0 ? void 0 : summarizePayload.byLastItems;
        }
        if ('byFirstItems' in summarizePayload &&
            typeof summarizePayload.byFirstItems === 'number') {
            order = 'asc';
            itemsForSummarize = summarizePayload.byFirstItems;
        }
        const convItems = await this.conversations.items.list(conversation, {
            limit: itemsForSummarize,
            order: order,
        });
        const conversationContext = joinItems
            ? joinItems(convItems)
            : this.joinConvItemsForSummarizingTitle(convItems);
        const systemPrompt = promptForSummarization !== null && promptForSummarization !== void 0 ? promptForSummarization : consts_1.BASE_PROMPT_FOR_SUMMARIZATION;
        const userPrompt = `Create a short title for this conversation:\n\n${conversationContext}`;
        const metadata = this.getMetadataForResponse(summarizePayload.metadata);
        const response = await this.responses.create({
            model: this.model,
            input: [
                {
                    content: [
                        {
                            text: systemPrompt,
                            type: 'input_text',
                        },
                    ],
                    role: 'user',
                    status: 'completed',
                    type: 'message',
                },
                {
                    content: [
                        {
                            text: userPrompt,
                            type: 'input_text',
                        },
                    ],
                    role: 'user',
                    status: 'completed',
                    type: 'message',
                },
            ],
            metadata,
        });
        const firstResponseOutput = (_a = response.output) === null || _a === void 0 ? void 0 : _a[0];
        const firstContent = (firstResponseOutput === null || firstResponseOutput === void 0 ? void 0 : firstResponseOutput.type) === 'message' ? firstResponseOutput.content[0] : null;
        const firstOutputText = (firstContent === null || firstContent === void 0 ? void 0 : firstContent.type) === 'output_text' ? firstContent.text : null;
        if (firstOutputText === null) {
            throw new Error('Failed to generate title. Empty response');
        }
        return firstOutputText;
    }
    joinConvItemsForSummarizingTitle(itemsPage) {
        return itemsPage.data
            .map((item) => {
            if (item.type === 'message' && typeof item.content === 'string') {
                return item.content;
            }
            return '';
        })
            .join('\n');
    }
    getMetadataForResponse(payloadMetadata) {
        if (payloadMetadata)
            return payloadMetadata;
        if (this.agent)
            return { agent: this.agent };
        return undefined;
    }
    iterateByConvItems(convId, fetchBy, order) {
        return tslib_1.__asyncGenerator(this, arguments, function* iterateByConvItems_1() {
            var _a;
            let after;
            while (true) {
                const page = yield tslib_1.__await(this.conversations.items.list(convId, {
                    limit: fetchBy,
                    after,
                    order,
                }));
                yield yield tslib_1.__await(page.data);
                if (!page.has_more)
                    return yield tslib_1.__await(void 0);
                after = (_a = page.data[page.data.length - 1]) === null || _a === void 0 ? void 0 : _a.id;
            }
        });
    }
}
exports.OpenAIService = OpenAIService;
