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,
    timeout: 600000, // 10 minutes
    maxRetries: 3,
  })
  : new OpenAI({
    apiKey: process.env.OPENAI_API_KEY,
    timeout: 600000, // 10 minutes
    maxRetries: 3,
  });

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;

function isJsonParseError(err: unknown): boolean {
  if (err instanceof SyntaxError) return true;
  if (!(err instanceof Error)) return false;

  // Some providers wrap JSON parsing failures in plain Error objects.
  return /not valid json|unexpected token|json/i.test(err.message);
}

export async function parseWithRetry<T>(fn: () => Promise<T>, retries = 3): Promise<T> {
  let lastErr: unknown;
  for (let attempt = 0; attempt <= retries; attempt++) {
    try {
      return await fn();
    } catch (err) {
      if (isJsonParseError(err) && attempt < retries) {
        lastErr = err;
        continue;
      }
      throw err;
    }
  }
  throw lastErr;
}
