// providers/openai.provider.ts
import {Injectable, Logger} from '@nestjs/common';
import {ConfigService} from '@nestjs/config';
import OpenAI from 'openai';
import {IAIProvider, AIMessage, AICompletionOptions, AICompletionResult} from '../interfaces/ai-provider.interface';
import {OpenRouter} from "@openrouter/sdk";

@Injectable()
export class OpenAIProvider implements IAIProvider {
    readonly name = 'openai';
    private readonly logger = new Logger(OpenAIProvider.name);
    private client: OpenAI;
    private defaultModel: string;

    constructor(private config: ConfigService) {

        // const openRouter = new OpenRouter({
        //     apiKey: '<OPEN_ROUTER_API_KEY>',
        //     // defaultHeaders: {
        //     //     'HTTP-Referer': '<YOUR_SITE_URL>', // Optional. Site URL for rankings on openrouter.ai.
        //     //     'X-OpenRouter-Title': '<YOUR_SITE_NAME>', // Optional. Site title for rankings on openrouter.ai.
        //     // },
        // });
        // const completion = await openRouter.chat.send({
        //     model: 'openai/gpt-4o-mini',
        //     messages: [
        //         {
        //             role: 'user',
        //             content: 'What is the meaning of life?',
        //         },
        //     ],
        //     stream: false,
        // });

        // this.client = new OpenAI({ apiKey: this.config.get('CHATGPT_API_KEY') });
        this.client = new OpenAI({
            baseURL: 'https://openrouter.ai/api/v1',
            apiKey: this.config.get('OPEN_ROUTER_API_KEY')
        });
        this.defaultModel = this.config.get('OPENAI_MODEL', 'openai/gpt-4o-mini'); // rẻ
    }

    async complete(messages: AIMessage[], options: AICompletionOptions = {}): Promise<AICompletionResult> {
        console.log(`OpenAIProvider_complete`);

        const model = options.model ?? this.defaultModel;
        try {
            const res = await this.client.chat.completions.create({
                model,
                messages,
                temperature: options.temperature ?? 0.7,
                max_tokens: options.maxTokens ?? 400, // giới hạn để tiết kiệm
            });
            return {
                content: res.choices[0]?.message?.content?.trim() ?? '',
                tokensUsed: res.usage?.total_tokens ?? 0,
                model,
            };
        } catch (err) {
            console.error(err);
            throw err;
        }
    }
}
