/**
 * OpenRouter Integration
 *
 * Lightweight wrapper for OpenRouter API, which provides access to
 * hundreds of AI models (GPT-4, Claude, Gemini, Llama, Mistral, etc.)
 * through a single API key and endpoint.
 *
 * Users provide their own OpenRouter API key via BYOK settings.
 */

const OPENROUTER_BASE_URL = 'https://openrouter.ai/api/v1';

// Popular models available on OpenRouter
export const OPENROUTER_MODELS = {
  OPTIONS: [
    { value: 'anthropic/claude-sonnet-4', label: 'Claude Sonnet 4' },
    { value: 'anthropic/claude-opus-4', label: 'Claude Opus 4' },
    { value: 'openai/gpt-4o', label: 'GPT-4o' },
    { value: 'openai/o3', label: 'O3' },
    { value: 'google/gemini-2.5-pro', label: 'Gemini 2.5 Pro' },
    { value: 'meta-llama/llama-4-maverick', label: 'Llama 4 Maverick' },
    { value: 'mistralai/mistral-large', label: 'Mistral Large' },
    { value: 'deepseek/deepseek-r1', label: 'DeepSeek R1' },
  ],
  DEFAULT: 'anthropic/claude-sonnet-4',
};

/**
 * Query OpenRouter API with streaming support
 * @param {string} message - User message
 * @param {Object} options - { model, apiKey, systemPrompt }
 * @param {Object} writer - WebSocketWriter or SSEStreamWriter
 */
export async function queryOpenRouter(message, options = {}, writer) {
  const {
    model = OPENROUTER_MODELS.DEFAULT,
    apiKey,
    systemPrompt,
    sessionId,
  } = options;

  if (!apiKey) {
    writer.send({
      type: 'error',
      error: 'OpenRouter API key required. Add your key in Settings > AI Providers.',
    });
    return;
  }

  // Generate session ID
  const sid = sessionId || `or-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
  writer.send({ type: 'session-created', sessionId: sid });

  const messages = [];
  if (systemPrompt) {
    messages.push({ role: 'system', content: systemPrompt });
  }
  messages.push({ role: 'user', content: message });

  try {
    const response = await fetch(`${OPENROUTER_BASE_URL}/chat/completions`, {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${apiKey}`,
        'Content-Type': 'application/json',
        'HTTP-Referer': 'https://cli.upfyn.com',
        'X-Title': 'Upfyn-Code',
      },
      body: JSON.stringify({
        model,
        messages,
        stream: true,
      }),
    });

    if (!response.ok) {
      const errBody = await response.text();
      let errMsg = `OpenRouter API error (${response.status})`;
      try {
        const parsed = JSON.parse(errBody);
        errMsg = parsed.error?.message || errMsg;
      } catch {}
      writer.send({ type: 'error', error: errMsg, sessionId: sid });
      return;
    }

    // Stream SSE response
    const reader = response.body.getReader();
    const decoder = new TextDecoder();
    let buffer = '';
    let fullContent = '';

    while (true) {
      const { done, value } = await reader.read();
      if (done) break;

      buffer += decoder.decode(value, { stream: true });
      const lines = buffer.split('\n');
      buffer = lines.pop() || '';

      for (const line of lines) {
        if (!line.startsWith('data: ')) continue;
        const data = line.slice(6).trim();
        if (data === '[DONE]') break;

        try {
          const parsed = JSON.parse(data);
          const delta = parsed.choices?.[0]?.delta?.content;
          if (delta) {
            fullContent += delta;
            writer.send({
              type: 'assistant',
              content: delta,
              sessionId: sid,
            });
          }
        } catch {}
      }
    }

    // Send completion
    writer.send({
      type: 'result',
      subtype: 'success',
      sessionId: sid,
      content: fullContent,
      model,
      provider: 'openrouter',
    });
  } catch (error) {
    writer.send({
      type: 'error',
      error: `OpenRouter request failed: ${error.message}`,
      sessionId: sid,
    });
  }
}
