import OpenAI from 'openai';
import * as dotenv from 'dotenv';
dotenv.config({ path: ['.env.local', '.env'] });

const AI_PROVIDER = process.env.AI_PROVIDER ?? 'OPENAI';
const isGeneric = AI_PROVIDER === 'GENERIC';

export const openai = isGeneric
  ? new OpenAI({
      apiKey: process.env.BEARER_TOKEN,
      baseURL: process.env.PROVIDER_URL,
    })
  : new OpenAI({
      apiKey: process.env.OPENAI_API_KEY,
    });

export const defaultModel = isGeneric ? (process.env.MODEL_NAME ?? 'default') : 'gpt-5.4';
export const miniModel = isGeneric ? (process.env.MODEL_NAME ?? 'default') : 'gpt-5.4-mini';
export const serviceOptions = isGeneric ? {} : { service_tier: 'flex' as const };
export const supportsWebSearch = !isGeneric;

export async function askAgent(prompt: string) {
  try {
    const response = await openai.chat.completions.create({
      model: 'gpt-5.4',
      service_tier: 'flex',
      messages: [{ role: 'user', content: prompt }],
    });
    return response!.choices![0]!.message!.content;
  } catch (err) {
    console.error('Agent endpoint dummy error:', err instanceof Error ? err.message : err);
    return 'Agent is in dummy mode or encountered an error.';
  }
}
