import 'package:flutter_dotenv/flutter_dotenv.dart';

const String _kEnvFromDefine = String.fromEnvironment(
  'ENV',
  defaultValue: 'dev',
);
const String _kBackendUrlFromDefine = String.fromEnvironment(
  'BACKEND_URL',
);
const String _kSupabaseTokenFromDefine = String.fromEnvironment(
  'SUPABASE_TOKEN',
);
const String _kRcAndroidApiKeyFromDefine = String.fromEnvironment(
  'RC_ANDROID_API_KEY',
);
const String _kRcIosApiKeyFromDefine = String.fromEnvironment(
  'RC_IOS_API_KEY',
);
const String _kRcWebApiKeyFromDefine = String.fromEnvironment(
  'RC_WEB_API_KEY',
);
const String _kMixpanelTokenFromDefine = String.fromEnvironment(
  'MIXPANEL_TOKEN',
);
const String _kSentryDsnFromDefine = String.fromEnvironment(
  'SENTRY_DSN',
);
const String _kAppStoreIdFromDefine = String.fromEnvironment(
  'APP_STORE_ID',
);
const String _kLlmChatEndpointFromDefine = String.fromEnvironment(
  'LLM_CHAT_ENDPOINT',
);

// ignore: avoid_classes_with_only_static_members
class AppEnv {
  static bool _isLoaded = false;

  static Future<void> load() async {
    if (_isLoaded) return;
    try {
      await dotenv.load();
    } catch (_) {
      // `.env` is optional: fallback to --dart-define works in all commands.
    }
    _isLoaded = true;
  }

  static String get env => _resolve(
    key: 'ENV',
    dartDefineValue: _kEnvFromDefine,
    defaultValue: 'dev',
  );

  static String get backendUrl =>
      _resolve(key: 'BACKEND_URL', dartDefineValue: _kBackendUrlFromDefine);

  static String get supabaseToken => _resolve(
    key: 'SUPABASE_TOKEN',
    dartDefineValue: _kSupabaseTokenFromDefine,
  );

  static String get rcAndroidApiKey => _resolve(
    key: 'RC_ANDROID_API_KEY',
    dartDefineValue: _kRcAndroidApiKeyFromDefine,
  );

  static String get rcIosApiKey =>
      _resolve(key: 'RC_IOS_API_KEY', dartDefineValue: _kRcIosApiKeyFromDefine);

  static String get rcWebApiKey =>
      _resolve(key: 'RC_WEB_API_KEY', dartDefineValue: _kRcWebApiKeyFromDefine);

  static String get mixpanelToken => _resolve(
    key: 'MIXPANEL_TOKEN',
    dartDefineValue: _kMixpanelTokenFromDefine,
  );

  static String get sentryDsn =>
      _resolve(key: 'SENTRY_DSN', dartDefineValue: _kSentryDsnFromDefine);

  static String get appStoreId =>
      _resolve(key: 'APP_STORE_ID', dartDefineValue: _kAppStoreIdFromDefine);

  static String get llmChatEndpoint => _resolve(
    key: 'LLM_CHAT_ENDPOINT',
    dartDefineValue: _kLlmChatEndpointFromDefine,
  );

  static String _resolve({
    required String key,
    required String dartDefineValue,
    String defaultValue = '',
  }) {
    final String? fromDotEnv = dotenv.isInitialized ? dotenv.env[key] : null;
    if (fromDotEnv != null && fromDotEnv.isNotEmpty) return fromDotEnv;
    if (dartDefineValue.isNotEmpty) return dartDefineValue;
    return defaultValue;
  }
}
