import 'package:flutter/foundation.dart';

/// 应用环境
enum AppEnvironment {
  development,
  staging,
  production,
}

/// 应用配置
///
/// 根据环境变量或编译配置决定 API 地址等配置
class AppConfig {
  static AppConfig? _instance;

  final AppEnvironment environment;
  final String apiBaseUrl;
  final bool enableLogging;

  AppConfig._({
    required this.environment,
    required this.apiBaseUrl,
    required this.enableLogging,
  });

  /// 初始化配置
  ///
  /// 可通过以下方式指定环境:
  /// 1. flutter run --dart-define=ENV=dev
  /// 2. 编译时: flutter build apk --dart-define=ENV=prod
  static void initialize() {
    const envString = String.fromEnvironment('ENV', defaultValue: 'prod');

    final environment = _parseEnvironment(envString);

    _instance = AppConfig._(
      environment: environment,
      apiBaseUrl: _getApiBaseUrl(environment),
      enableLogging: environment != AppEnvironment.production,
    );

    if (kDebugMode) {
      debugPrint('🔧 [AppConfig] Environment: ${_instance!.environment}');
      debugPrint('🔧 [AppConfig] API Base URL: ${_instance!.apiBaseUrl}');
    }
  }

  /// 获取配置实例
  static AppConfig get instance {
    if (_instance == null) {
      initialize();
    }
    return _instance!;
  }

  /// 解析环境字符串
  static AppEnvironment _parseEnvironment(String env) {
    switch (env.toLowerCase()) {
      case 'dev':
      case 'development':
        return AppEnvironment.development;
      case 'staging':
      case 'stage':
        return AppEnvironment.staging;
      case 'prod':
      case 'production':
      default:
        return AppEnvironment.production;
    }
  }

  /// 获取 API 基础地址
  static String _getApiBaseUrl(AppEnvironment env) {
    switch (env) {
      case AppEnvironment.development:
        // Android 模拟器访问本机: 10.0.2.2
        // iOS 模拟器访问本机: localhost
        // 真机测试: 使用局域网 IP
        return const String.fromEnvironment(
          'API_URL',
          defaultValue: 'http://10.0.2.2:3000/api/v1',
        );
      case AppEnvironment.staging:
        return 'https://rwaapi-dev.szaiai.com/api/v1';
      case AppEnvironment.production:
        return 'https://rwaapi.szaiai.com/api/v1';
    }
  }

  /// 是否为开发环境
  bool get isDevelopment => environment == AppEnvironment.development;

  /// 是否为生产环境
  bool get isProduction => environment == AppEnvironment.production;
}
