import dotenv from 'dotenv'
import OpenAI from 'openai'

let openaiClient: OpenAI | null = null

export function getOpenAIClient() {
  if (openaiClient) return openaiClient

  // 只在这里加载 .env.local，避免启动时重复/冲突
  dotenv.config({ path: '.env.local', override: true })

  const apiKey = process.env.MY_OPENAI_API_KEY
  const baseURL = process.env.MY_OPENAI_BASE_URL

  if (!apiKey) {
    console.error('[server] Missing MY_OPENAI_API_KEY in .env.local')
    process.exit(1)
  }

  if (!baseURL) {
    console.error('[server] Missing MY_OPENAI_BASE_URL in .env.local')
    process.exit(1)
  }

  openaiClient = new OpenAI({ apiKey, baseURL })
  return openaiClient
}
