import dotenv from 'dotenv';
import path from 'path';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// 加载.env文件
dotenv.config({ path: path.join(__dirname, '../../.env') });

export const config = {
  // 服务器配置
  port: parseInt(process.env.PORT || '3001', 10),
  host: process.env.HOST || '0.0.0.0',
  nodeEnv: process.env.NODE_ENV || 'development',
  logLevel: process.env.LOG_LEVEL || 'info',

  // 数据库配置
  databaseUrl: process.env.DATABASE_URL || 'postgresql://postgres:postgres@localhost:5432/ai_clinical',

  // Redis配置
  redisUrl: process.env.REDIS_URL || 'redis://localhost:6379',

  // JWT配置
  jwtSecret: process.env.JWT_SECRET || 'your-secret-key-change-in-production',
  jwtExpiresIn: process.env.JWT_EXPIRES_IN || '7d',

  // LLM API配置
  deepseekApiKey: process.env.DEEPSEEK_API_KEY || '',
  deepseekBaseUrl: process.env.DEEPSEEK_BASE_URL || 'https://api.deepseek.com',
  
  dashscopeApiKey: process.env.DASHSCOPE_API_KEY || '',  // 用于Qwen模型
  geminiApiKey: process.env.GEMINI_API_KEY || '',
  
  // CloseAI配置（代理OpenAI和Claude）
  closeaiApiKey: process.env.CLOSEAI_API_KEY || '',
  closeaiOpenaiBaseUrl: process.env.CLOSEAI_OPENAI_BASE_URL || 'https://api.openai-proxy.org/v1',
  closeaiClaudeBaseUrl: process.env.CLOSEAI_CLAUDE_BASE_URL || 'https://api.openai-proxy.org/anthropic',

  // Dify配置
  difyApiKey: process.env.DIFY_API_KEY || '',
  difyApiUrl: process.env.DIFY_API_URL || 'http://localhost/v1',

  // 文件上传配置
  uploadMaxSize: parseInt(process.env.UPLOAD_MAX_SIZE || '10485760', 10), // 10MB
  uploadDir: process.env.UPLOAD_DIR || './uploads',

  // CORS配置
  corsOrigin: process.env.CORS_ORIGIN || 'http://localhost:5173',
};

// 验证必需的环境变量
export function validateEnv(): void {
  const requiredVars = ['DATABASE_URL'];
  const missing = requiredVars.filter(v => !process.env[v]);
  
  if (missing.length > 0) {
    console.warn(`Warning: Missing environment variables: ${missing.join(', ')}`);
  }

  // 检查LLM API Keys
  if (!config.deepseekApiKey && !config.dashscopeApiKey) {
    console.warn('Warning: No LLM API keys configured. At least one of DEEPSEEK_API_KEY or DASHSCOPE_API_KEY should be set.');
  }
}
