var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
import DatabaseService from "./DatabaseService";
import Model from "../../Models/DatabaseModels/LlmProvider";
import ObjectID from "../../Types/ObjectID";
import QueryHelper from "../Types/Database/QueryHelper";
import LIMIT_MAX from "../../Types/Database/LimitMax";
import CaptureSpan from "../Utils/Telemetry/CaptureSpan";
export class Service extends DatabaseService {
    constructor() {
        super(Model);
    }
    async onBeforeCreate(createBy) {
        // When creating a new LLM provider, set it as default by default
        if (createBy.data.isDefault === undefined) {
            createBy.data.isDefault = true;
        }
        // If this provider is being set as default, unset other defaults in the same project
        if (createBy.data.isDefault && createBy.data.projectId) {
            await this.updateBy({
                query: {
                    projectId: createBy.data.projectId,
                    isDefault: true,
                },
                data: {
                    isDefault: false,
                },
                props: {
                    isRoot: true,
                },
                limit: LIMIT_MAX,
                skip: 0,
            });
        }
        return { createBy, carryForward: null };
    }
    async onBeforeUpdate(updateBy) {
        // If setting isDefault to true, we need to unset other defaults in the same project
        if (updateBy.data.isDefault === true) {
            // Get the items being updated to find their project IDs
            const itemsToUpdate = await this.findBy({
                query: updateBy.query,
                select: {
                    _id: true,
                    projectId: true,
                },
                props: {
                    isRoot: true,
                },
                limit: LIMIT_MAX,
                skip: 0,
            });
            // Collect unique project IDs
            const projectIds = new Set();
            const itemIds = new Set();
            for (const item of itemsToUpdate) {
                if (item.projectId) {
                    projectIds.add(item.projectId.toString());
                }
                if (item._id) {
                    itemIds.add(item._id);
                }
            }
            // For each project, unset the default on other providers
            for (const projectIdStr of projectIds) {
                const projectId = new ObjectID(projectIdStr);
                await this.updateBy({
                    query: {
                        projectId: projectId,
                        isDefault: true,
                        _id: QueryHelper.notInOrNull(Array.from(itemIds)),
                    },
                    data: {
                        isDefault: false,
                    },
                    props: {
                        isRoot: true,
                    },
                    limit: LIMIT_MAX,
                    skip: 0,
                });
            }
        }
        return { updateBy, carryForward: null };
    }
    async getLLMProviderForProject(projectId) {
        // First try to get the default provider for the project
        let provider = await this.findOneBy({
            query: {
                projectId: projectId,
                isDefault: true,
            },
            select: {
                _id: true,
                name: true,
                llmType: true,
                apiKey: true,
                baseUrl: true,
                modelName: true,
                isGlobalLlm: true,
                costPerMillionTokensInUSDCents: true,
            },
            props: {
                isRoot: true,
            },
        });
        if (provider) {
            return provider;
        }
        // If no default provider, get any global provider for the project.
        provider = await this.findOneBy({
            query: {
                projectId: QueryHelper.isNull(),
                isGlobalLlm: true,
            },
            select: {
                _id: true,
                name: true,
                llmType: true,
                apiKey: true,
                baseUrl: true,
                modelName: true,
                isGlobalLlm: true,
                costPerMillionTokensInUSDCents: true,
            },
            props: {
                isRoot: true,
            },
        });
        if (provider) {
            return provider;
        }
        return null;
    }
}
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [ObjectID]),
    __metadata("design:returntype", Promise)
], Service.prototype, "getLLMProviderForProject", null);
export default new Service();
//# sourceMappingURL=LlmProviderService.js.map