import dotenv from 'dotenv';
import fs from 'fs';
import path from 'path';
import { logger } from '../utils/logger';

dotenv.config();

// 配置文件类型定义
interface ConfigFile {
  server?: {
    port?: number;
  };
  security?: {
    jwtSecret?: string;
    rateLimit?: {
      windowMs?: number;
      max?: number;
    };
    cors?: {
      origin?: string;
      methods?: string[];
      allowedHeaders?: string[];
    };
  };
  database?: {
    postgreSQL?: {
      host?: string;
      port?: string;
      username?: string;
      password?: string;
      database?: string;
    };
  };
  dataSource?: any;
}

// 从文件读取配置
let fileConfig: ConfigFile = {};
try {
  const configPath = path.join(__dirname, '../../../config.json');
  if (fs.existsSync(configPath)) {
    const configData = fs.readFileSync(configPath, 'utf8');
    fileConfig = JSON.parse(configData);
    logger.log('已读取配置文件:', configPath);
    logger.log('配置文件内容:', fileConfig);
  }
} catch (error) {
  logger.error('读取配置文件失败:', error);
}

export const config = {
  port: process.env.PORT || (fileConfig.server?.port || 3007),
  jwtSecret: process.env.JWT_SECRET || (fileConfig.security?.jwtSecret || 'your-secret-key'),
  database: {
    mongo: {
      url: process.env.MONGO_URL || 'mongodb://localhost:27017/alpha-futures'
    },
    postgres: {
      host: process.env.PG_HOST || (fileConfig.database?.postgreSQL?.host || 'localhost'),
      port: parseInt(process.env.PG_PORT || (fileConfig.database?.postgreSQL?.port || '5432')),
      user: process.env.PG_USER || (fileConfig.database?.postgreSQL?.username || 'postgres'),
      password: process.env.PG_PASSWORD || (fileConfig.database?.postgreSQL?.password || 'password'),
      database: process.env.PG_DATABASE || (fileConfig.database?.postgreSQL?.database || 'alpha-futures')
    },
    mysql: {
      host: process.env.MYSQL_HOST || 'localhost',
      port: parseInt(process.env.MYSQL_PORT || '3306'),
      user: process.env.MYSQL_USER || 'root',
      password: process.env.MYSQL_PASSWORD || 'password',
      database: process.env.MYSQL_DATABASE || 'alpha-futures'
    }
  },
  redis: {
    url: process.env.REDIS_URL || 'redis://localhost:6379'
  },
  rateLimit: {
    windowMs: fileConfig.security?.rateLimit?.windowMs || 60 * 1000, // 1分钟
    max: fileConfig.security?.rateLimit?.max || 120 // 每分钟120次请求
  },
  cors: {
    origin: fileConfig.security?.cors?.origin || '*', // 在生产环境中应该设置具体的域名
    methods: fileConfig.security?.cors?.methods || ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
    allowedHeaders: fileConfig.security?.cors?.allowedHeaders || ['Content-Type', 'Authorization']
  },
  dataSource: (() => {
    const dataSourceConfig = fileConfig.dataSource || {
      test: {
        enabled: true,
        timeout: 10000,
        retries: 3,
        refreshInterval: 60000
      },
      tqsdk: {
        enabled: true,
        apiKey: '',
        apiSecret: '',
        username: '',
        password: '',
        timeout: 30000,
        retries: 3,
        maxConnections: 5
      },
      wind: {
        enabled: false,
        apiKey: '',
        apiSecret: '',
        url: 'https://api.wind.com.cn',
        timeout: 30000,
        retries: 3
      },
      sina: {
        enabled: false,
        url: 'https://finance.sina.com.cn',
        timeout: 10000,
        retries: 3,
        refreshInterval: 60000
      },
      defaultDataSource: 'tqsdk'
    };
    logger.log('数据源配置初始化完成:', {
          hasFileConfig: !!fileConfig.dataSource,
          enabledDataSources: Object.keys(dataSourceConfig).filter(key => 
            key !== 'defaultDataSource' && dataSourceConfig[key].enabled
          ),
          defaultDataSource: dataSourceConfig.defaultDataSource
        });
    return dataSourceConfig;
  })()
};