// backend/src/services/ai-provider.js
import Anthropic from '@anthropic-ai/sdk';
import OpenAI from 'openai';
import { GoogleGenerativeAI } from '@google/generative-ai';
import { query } from '../utils/db.js';
import { decrypt } from '../utils/encryption.js';
import { logger } from '../utils/logger.js';

// Get AI provider for a specific user (respects BYOK vs platform keys)
export async function getProviderForUser(userId, userPlan) {
  // BYOK plans: use their own keys
  if (userPlan?.byok) {
    const { rows } = await query(
      'SELECT provider, encrypted_key, model FROM user_api_keys WHERE user_id = $1 AND is_valid = true ORDER BY created_at ASC LIMIT 1',
      [userId]
    );
    if (rows[0]) {
      return createProvider(rows[0].provider, decrypt(rows[0].encrypted_key), rows[0].model);
    }
    throw new Error('No valid API key configured. Please add your API key in Settings.');
  }

  // Starter plan: use platform keys (Claude preferred)
  if (process.env.ANTHROPIC_API_KEY) {
    return createProvider('claude', process.env.ANTHROPIC_API_KEY, 'claude-haiku-4-5-20251001');
  }
  if (process.env.OPENAI_API_KEY) {
    return createProvider('openai', process.env.OPENAI_API_KEY, 'gpt-4o-mini');
  }
  throw new Error('Platform AI keys not configured');
}

export function createProvider(provider, apiKey, model) {
  const defaults = { claude: 'claude-sonnet-4-5', openai: 'gpt-4o', gemini: 'gemini-1.5-flash' };
  const resolvedModel = model || defaults[provider];

  return {
    provider,
    model: resolvedModel,
    async complete(systemPrompt, userPrompt, maxTokens = 4096) {
      switch (provider) {
        case 'claude': {
          const client = new Anthropic({ apiKey });
          const res = await client.messages.create({
            model: resolvedModel, max_tokens: maxTokens,
            system: systemPrompt,
            messages: [{ role: 'user', content: userPrompt }]
          });
          return res.content[0].text;
        }
        case 'openai': {
          const client = new OpenAI({ apiKey });
          const res = await client.chat.completions.create({
            model: resolvedModel, max_tokens: maxTokens,
            messages: [{ role: 'system', content: systemPrompt }, { role: 'user', content: userPrompt }]
          });
          return res.choices[0].message.content;
        }
        case 'gemini': {
          const genai = new GoogleGenerativeAI(apiKey);
          const m = genai.getGenerativeModel({ model: resolvedModel, systemInstruction: systemPrompt });
          const res = await m.generateContent(userPrompt);
          return res.response.text();
        }
        default:
          throw new Error(`Unknown provider: ${provider}`);
      }
    }
  };
}

export async function testApiKey(provider, apiKey, model) {
  try {
    const p = createProvider(provider, apiKey, model);
    await p.complete('You are a test assistant.', 'Reply with exactly: OK', 10);
    return { valid: true };
  } catch (err) {
    logger.warn(`API key test failed for ${provider}`, err.message);
    return { valid: false, error: err.message?.substring(0, 100) };
  }
}
