'use strict';

/**
 * OpenAI Provider
 * 
 * Pricing (April 2026):
 *   GPT-4.1:      $2.00 / 1M input,  $8.00 / 1M output
 *   GPT-4.1 Mini: $0.40 / 1M input,  $1.60 / 1M output
 *   GPT-5.4:      $2.50 / 1M input,  $15.00 / 1M output
 */

const https = require('https');
const { URL } = require('url');

const DEFAULT_MODELS = {
  classification: 'gpt-4.1-mini',
  codeGeneration: 'gpt-4.1',
  analysis: 'gpt-4.1',
};

class OpenAIProvider {
  constructor(config) {
    this.apiKey = config.apiKey;
    this.baseUrl = config.baseUrl || 'https://api.openai.com/v1';
    this.models = Object.assign({}, DEFAULT_MODELS, config.model);
    this.temperature = config.temperature ?? 0.1;
    this.maxTokens = config.maxTokens ?? 4096;
    this.timeout = config.timeout ?? 30000;
  }

  async chat(messages, options = {}) {
    const model = options.model || this.models.codeGeneration;
    const body = {
      model,
      messages,
      temperature: options.temperature ?? this.temperature,
      max_tokens: options.maxTokens ?? this.maxTokens,
    };

    const response = await this._request('/chat/completions', body);

    if (!response.choices || !response.choices[0]) {
      throw new Error('OpenAI API returned empty response');
    }

    return response.choices[0].message.content;
  }

  async _request(path, body) {
    const url = new URL(path, this.baseUrl);

    return new Promise((resolve, reject) => {
      const postData = JSON.stringify(body);

      const req = https.request(url, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${this.apiKey}`,
          'Content-Length': Buffer.byteLength(postData),
        },
        timeout: this.timeout,
      }, (res) => {
        let data = '';
        res.on('data', chunk => data += chunk);
        res.on('end', () => {
          if (res.statusCode >= 400) {
            reject(new Error(`OpenAI API ${res.statusCode}: ${data.slice(0, 500)}`));
            return;
          }
          try {
            resolve(JSON.parse(data));
          } catch (e) {
            reject(new Error(`Failed to parse OpenAI response: ${e.message}`));
          }
        });
      });

      req.on('timeout', () => {
        req.destroy();
        reject(new Error('OpenAI API request timed out'));
      });

      req.on('error', reject);
      req.write(postData);
      req.end();
    });
  }
}

module.exports = OpenAIProvider;
