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

dotenv.config();

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

export const config = {
  env: process.env.NODE_ENV || 'development',
  version: process.env.npm_package_version || '1.0.0',
  port: parseInt(process.env.PORT || '3000', 10),
  // 服务监听地址：127.0.0.1 仅本地访问，0.0.0.0 允许局域网访问
  host: process.env.HOST || '127.0.0.1',

  // 数据库配置
  database: {
    host: process.env.DB_HOST || 'localhost',
    port: parseInt(process.env.DB_PORT || '3306', 10),
    username: process.env.DB_USERNAME || 'root',
    password: process.env.DB_PASSWORD || '',
    database: process.env.DB_DATABASE || 'media_manager',
  },

  // Redis 配置
  redis: {
    host: process.env.REDIS_HOST || 'localhost',
    port: parseInt(process.env.REDIS_PORT || '6379', 10),
    password: process.env.REDIS_PASSWORD || undefined,
    db: parseInt(process.env.REDIS_DB || '0', 10),
  },

  // JWT 配置
  jwt: {
    secret: process.env.JWT_SECRET || 'your-super-secret-key-change-in-production',
    accessExpiresIn: process.env.JWT_ACCESS_EXPIRES_IN || '15m',
    refreshExpiresIn: process.env.JWT_REFRESH_EXPIRES_IN || '7d',
  },

  // CORS 配置
  cors: {
    origin: process.env.CORS_ORIGIN?.split(',') || ['http://localhost:5173'],
  },

  // 上传配置
  upload: {
    path: process.env.UPLOAD_PATH || path.join(__dirname, '../../uploads'),
    maxVideoSize: parseInt(process.env.MAX_VIDEO_SIZE || '4096', 10) * 1024 * 1024, // MB to bytes
    maxImageSize: parseInt(process.env.MAX_IMAGE_SIZE || '10', 10) * 1024 * 1024,
    allowedVideoTypes: ['video/mp4', 'video/quicktime', 'video/x-flv'],
    allowedImageTypes: ['image/jpeg', 'image/png', 'image/gif', 'image/webp'],
  },

  // 加密配置
  encryption: {
    key: process.env.ENCRYPTION_KEY || 'your-encryption-key-32-chars-long!',
  },

  // 内部 API 密钥（供 Python 服务调用）
  internalApiKey: process.env.INTERNAL_API_KEY || 'internal-api-key-default',

  // AI 配置 - 阿里云百炼千问大模型
  ai: {
    apiKey: process.env.DASHSCOPE_API_KEY || process.env.OPENAI_API_KEY || '',
    baseUrl: process.env.DASHSCOPE_BASE_URL || process.env.OPENAI_BASE_URL || 'https://dashscope.aliyuncs.com/compatible-mode/v1',
    // 默认模型配置
    defaultModel: process.env.AI_DEFAULT_MODEL || 'qwen-plus',
    // 可用模型列表
    models: {
      // 商业版模型
      chat: process.env.AI_CHAT_MODEL || 'qwen-plus', // 对话模型
      fast: process.env.AI_FAST_MODEL || 'qwen-turbo', // 快速模型
      reasoning: process.env.AI_REASONING_MODEL || 'qwq-plus', // 推理模型
      vision: process.env.AI_VISION_MODEL || 'qwen-vl-plus', // 视觉理解模型
      coder: process.env.AI_CODER_MODEL || 'qwen-coder-plus', // 代码模型
      embedding: process.env.AI_EMBEDDING_MODEL || 'text-embedding-v3', // 嵌入模型
    },
    // 请求配置
    timeout: parseInt(process.env.AI_TIMEOUT || '60000', 10),
    maxRetries: parseInt(process.env.AI_MAX_RETRIES || '3', 10),
  },
};
