"use strict";
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
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());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
    return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.OpenAIClient = void 0;
var promises_1 = require("timers/promises");
var common_1 = require("../util/common");
var OpenAIClient = /** @class */ (function () {
    function OpenAIClient(config) {
        this.config = config;
        if (!this.config.apiKey) {
            throw new Error('AI API key is required for AI client');
        }
    }
    OpenAIClient.prototype.chat = function (messages, options) {
        return __awaiter(this, void 0, void 0, function () {
            var baseUrl, primaryModel, fallbackModel, maxRetries, retryDelayMs, payload, responseFormat, normalized, runRequest, runWithRetry, result, error_1, result;
            var _this = this;
            var _a, _b;
            return __generator(this, function (_c) {
                switch (_c.label) {
                    case 0:
                        baseUrl = (this.config.baseUrl || 'https://api.openai.com/v1').replace(/\/+$/, '');
                        primaryModel = this.config.model || 'gpt-5.1';
                        fallbackModel = (this.config.fallbackModel || '').trim();
                        maxRetries = this.normalizeRetryCount(this.config.maxRetries);
                        retryDelayMs = this.normalizeRetryDelay(this.config.retryDelayMs);
                        payload = {
                            model: primaryModel,
                            messages: messages,
                            temperature: (_a = this.config.temperature) !== null && _a !== void 0 ? _a : 0.2
                        };
                        responseFormat = (_b = options === null || options === void 0 ? void 0 : options.responseFormat) !== null && _b !== void 0 ? _b : this.config.responseFormat;
                        if (responseFormat) {
                            normalized = typeof responseFormat === 'string' ? responseFormat.toLowerCase() : '';
                            if (normalized === 'json' || normalized === 'json_object') {
                                payload.response_format = { type: 'json_object' };
                            }
                            else if (typeof responseFormat === 'object') {
                                payload.response_format = responseFormat;
                            }
                            else if (normalized && normalized !== 'text') {
                                payload.response_format = { type: normalized };
                            }
                        }
                        if (Number.isFinite(this.config.maxTokens)) {
                            payload.max_completion_tokens = this.normalizeTokenCount(this.config.maxTokens);
                        }
                        runRequest = function (model) { return __awaiter(_this, void 0, void 0, function () {
                            var timeoutMs, controller, timeoutId, response, requestId, error_2, responseText, requestError, data, message, content, refusal, usage;
                            var _a, _b, _c;
                            return __generator(this, function (_d) {
                                switch (_d.label) {
                                    case 0:
                                        timeoutMs = options === null || options === void 0 ? void 0 : options.timeoutMs;
                                        controller = timeoutMs ? new AbortController() : null;
                                        timeoutId = controller ? setTimeout(function () { return controller.abort(); }, timeoutMs) : null;
                                        requestId = '';
                                        _d.label = 1;
                                    case 1:
                                        _d.trys.push([1, 3, 4, 5]);
                                        return [4 /*yield*/, fetch("".concat(baseUrl, "/chat/completions"), {
                                                method: 'POST',
                                                headers: {
                                                    'Content-Type': 'application/json',
                                                    Authorization: "Bearer ".concat(this.config.apiKey)
                                                },
                                                body: JSON.stringify(__assign(__assign({}, payload), { model: model })),
                                                signal: controller === null || controller === void 0 ? void 0 : controller.signal
                                            })];
                                    case 2:
                                        response = _d.sent();
                                        requestId = response.headers.get('x-request-id') || '';
                                        return [3 /*break*/, 5];
                                    case 3:
                                        error_2 = _d.sent();
                                        if ((_a = controller === null || controller === void 0 ? void 0 : controller.signal) === null || _a === void 0 ? void 0 : _a.aborted) {
                                            throw new Error('AI request timed out.');
                                        }
                                        throw error_2;
                                    case 4:
                                        if (timeoutId) {
                                            clearTimeout(timeoutId);
                                        }
                                        return [7 /*endfinally*/];
                                    case 5: return [4 /*yield*/, response.text()];
                                    case 6:
                                        responseText = _d.sent();
                                        if (!response.ok) {
                                            requestError = new Error("AI request failed (".concat(response.status, ")."));
                                            requestError.status = response.status;
                                            requestError.raw = responseText;
                                            throw requestError;
                                        }
                                        data = responseText ? JSON.parse(responseText) : {};
                                        message = ((_c = (_b = data === null || data === void 0 ? void 0 : data.choices) === null || _b === void 0 ? void 0 : _b[0]) === null || _c === void 0 ? void 0 : _c.message) || {};
                                        content = this.extractContent(message);
                                        if (!content) {
                                            refusal = (message === null || message === void 0 ? void 0 : message.refusal) ? " Refusal: ".concat(message.refusal) : '';
                                            throw new Error("AI returned no completion content.".concat(refusal));
                                        }
                                        usage = this.extractUsage(data === null || data === void 0 ? void 0 : data.usage);
                                        return [2 /*return*/, {
                                                content: content,
                                                usage: usage,
                                                model: (data === null || data === void 0 ? void 0 : data.model) || model,
                                                requestId: (data === null || data === void 0 ? void 0 : data.id) || requestId,
                                                responseText: responseText
                                            }];
                                }
                            });
                        }); };
                        runWithRetry = function (model) { return __awaiter(_this, void 0, void 0, function () {
                            var attempt, lastError, error_3, delay;
                            return __generator(this, function (_a) {
                                switch (_a.label) {
                                    case 0:
                                        attempt = 0;
                                        lastError = null;
                                        _a.label = 1;
                                    case 1:
                                        if (!(attempt <= maxRetries)) return [3 /*break*/, 7];
                                        _a.label = 2;
                                    case 2:
                                        _a.trys.push([2, 4, , 6]);
                                        return [4 /*yield*/, runRequest(model)];
                                    case 3: return [2 /*return*/, _a.sent()];
                                    case 4:
                                        error_3 = _a.sent();
                                        lastError = error_3;
                                        if (attempt >= maxRetries || !this.isRetryableError(error_3)) {
                                            return [3 /*break*/, 7];
                                        }
                                        delay = retryDelayMs * Math.pow(2, attempt);
                                        return [4 /*yield*/, this.sleep(delay)];
                                    case 5:
                                        _a.sent();
                                        attempt += 1;
                                        return [3 /*break*/, 6];
                                    case 6: return [3 /*break*/, 1];
                                    case 7: throw lastError;
                                }
                            });
                        }); };
                        _c.label = 1;
                    case 1:
                        _c.trys.push([1, 3, , 5]);
                        return [4 /*yield*/, runWithRetry(primaryModel)];
                    case 2:
                        result = _c.sent();
                        return [2 /*return*/, {
                                content: result.content,
                                usage: result.usage,
                                model: result.model,
                                requestId: result.requestId
                            }];
                    case 3:
                        error_1 = _c.sent();
                        if (!fallbackModel || fallbackModel === primaryModel) {
                            throw error_1;
                        }
                        return [4 /*yield*/, runWithRetry(fallbackModel)];
                    case 4:
                        result = _c.sent();
                        return [2 /*return*/, {
                                content: result.content,
                                usage: result.usage,
                                model: result.model,
                                requestId: result.requestId
                            }];
                    case 5: return [2 /*return*/];
                }
            });
        });
    };
    OpenAIClient.prototype.extractContent = function (message) {
        if (!message) {
            return '';
        }
        var content = message.content;
        if (typeof content === 'string') {
            return content.trim();
        }
        if (Array.isArray(content)) {
            return content
                .map(function (part) {
                if (!part) {
                    return '';
                }
                if (typeof part === 'string') {
                    return part;
                }
                if (typeof (part === null || part === void 0 ? void 0 : part.text) === 'string') {
                    return part.text;
                }
                if (typeof (part === null || part === void 0 ? void 0 : part.content) === 'string') {
                    return part.content;
                }
                return '';
            })
                .join('')
                .trim();
        }
        return '';
    };
    OpenAIClient.prototype.extractUsage = function (usage) {
        var _a, _b, _c;
        if (!usage) {
            return undefined;
        }
        var inputTokens = this.normalizeTokenValue((_a = usage.prompt_tokens) !== null && _a !== void 0 ? _a : usage.input_tokens);
        var outputTokens = this.normalizeTokenValue((_b = usage.completion_tokens) !== null && _b !== void 0 ? _b : usage.output_tokens);
        var totalTokens = this.normalizeTokenValue((_c = usage.total_tokens) !== null && _c !== void 0 ? _c : (inputTokens + outputTokens));
        if (!totalTokens && !inputTokens && !outputTokens) {
            return undefined;
        }
        return {
            inputTokens: inputTokens,
            outputTokens: outputTokens,
            totalTokens: totalTokens
        };
    };
    OpenAIClient.prototype.normalizeTokenValue = function (value) {
        var parsed = Number(value);
        if (!Number.isFinite(parsed) || parsed < 0) {
            return 0;
        }
        return (0, common_1.round)(parsed);
    };
    OpenAIClient.prototype.normalizeTokenCount = function (value) {
        if (!Number.isFinite(value)) {
            return 0;
        }
        var rounded = (0, common_1.round)(value || 0);
        return rounded < 0 ? 0 : rounded;
    };
    OpenAIClient.prototype.normalizeRetryCount = function (value) {
        if (!Number.isFinite(value)) {
            return 0;
        }
        return Math.max(0, (0, common_1.round)(value || 0));
    };
    OpenAIClient.prototype.normalizeRetryDelay = function (value) {
        if (!Number.isFinite(value)) {
            return 750;
        }
        return Math.max(250, (0, common_1.round)(value || 0));
    };
    OpenAIClient.prototype.isRetryableError = function (error) {
        var message = error instanceof Error ? error.message.toLowerCase() : String(error || '').toLowerCase();
        return message.includes('timeout') || message.includes('429') || message.includes('rate limit');
    };
    OpenAIClient.prototype.sleep = function (ms) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (!ms) {
                            return [2 /*return*/];
                        }
                        return [4 /*yield*/, (0, promises_1.setTimeout)(ms)];
                    case 1:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        });
    };
    return OpenAIClient;
}());
exports.OpenAIClient = OpenAIClient;

//# sourceMappingURL=openai-client.js.map
