'use strict';

/**
 * Anthropic Claude Provider
 * 
 * Pricing (April 2026):
 *   Opus 4.6:   $5.00 / 1M input,  $25.00 / 1M output
 *   Sonnet 4.6: $3.00 / 1M input,  $15.00 / 1M output
 *   Haiku 4.5:  $1.00 / 1M input,   $5.00 / 1M output
 */

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

const DEFAULT_MODELS = {
  classification: 'claude-haiku-4.5-20260301',
  codeGeneration: 'claude-sonnet-4.6-20260301',
  analysis: 'claude-sonnet-4.6-20260301',
};

class AnthropicProvider {
  constructor(config) {
    this.apiKey = config.apiKey;
    this.baseUrl = config.baseUrl || 'https://api.anthropic.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 ?? 60000;
  }

  async chat(messages, options = {}) {
    const model = options.model || this.models.codeGeneration;

    // Anthropic uses a different format — extract system message
    let system = '';
    const chatMessages = [];
    for (const msg of messages) {
      if (msg.role === 'system') {
        system += (system ? '\n\n' : '') + msg.content;
      } else {
        chatMessages.push({ role: msg.role, content: msg.content });
      }
    }

    const body = {
      model,
      max_tokens: options.maxTokens ?? this.maxTokens,
      messages: chatMessages,
    };
    if (system) body.system = system;
    if ((options.temperature ?? this.temperature) > 0) {
      body.temperature = options.temperature ?? this.temperature;
    }

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

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

    return response.content[0].text;
  }

  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',
          'x-api-key': this.apiKey,
          'anthropic-version': '2024-01-01',
          '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(`Anthropic API ${res.statusCode}: ${data.slice(0, 500)}`));
            return;
          }
          try {
            resolve(JSON.parse(data));
          } catch (e) {
            reject(new Error(`Failed to parse Anthropic response: ${e.message}`));
          }
        });
      });

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

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

module.exports = AnthropicProvider;
