import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_crashlytics/firebase_crashlytics.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'app.dart';
import 'firebase_options.dart';
import 'providers/app_provider.dart';

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();

  // 捕获所有 Dart 异常
  FlutterError.onError = (FlutterErrorDetails details) {
    // 布局溢出（RenderFlex overflow）是 debug 模式下的警告，不属于崩溃，不上报
    final summary = details.exception.toString();
    if (summary.contains('RenderFlex overflowed') || summary.contains('overflowed by')) {
      if (kDebugMode) FlutterError.dumpErrorToConsole(details, forceReport: false);
      return;
    }
    FlutterError.dumpErrorToConsole(details);
    FirebaseCrashlytics.instance.recordFlutterFatalError(details);
  };

  // 捕获异步异常（Platform/isolate）
  PlatformDispatcher.instance.onError = (error, stack) {
    // Flutter SDK / Dart VM 已知 bug：WS 重连时 _SocketProfile.collectStatistic assertion 失败
    final msg = error.toString();
    if (msg.contains('_SocketProfile') || msg.contains('network_profiling')) {
      return true;
    }
    FirebaseCrashlytics.instance.recordError(error, stack, fatal: true);
    return true;
  };

  try {
    // 强制竖屏
    await SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitUp,
      DeviceOrientation.portraitDown,
    ]);

    // 状态栏透明
    SystemChrome.setSystemUIOverlayStyle(
      const SystemUiOverlayStyle(
        statusBarColor: Colors.transparent,
      ),
    );

    // Hive 初始化
    await Hive.initFlutter();

    // SharedPreferences 初始化
    final prefs = await SharedPreferences.getInstance();

    // 重装检测：iOS Keychain 卸载后不会自动清除，需手动处理
    // SharedPreferences 卸载后会被系统清除，利用此差异检测重装
    const kAppInstalled = 'app_installed';
    if (!(prefs.getBool(kAppInstalled) ?? false)) {
      await const FlutterSecureStorage().deleteAll();
      await prefs.setBool(kAppInstalled, true);
    }

    // Firebase 初始化 - 后台异步执行，不阻塞 runApp
    Firebase.initializeApp(
      options: DefaultFirebaseOptions.currentPlatform,
    ).then((_) async {
      // Debug 模式下关闭 Crashlytics 上报，避免污染生产数据
      await FirebaseCrashlytics.instance
          .setCrashlyticsCollectionEnabled(!kDebugMode);
    });

    runApp(
      ProviderScope(
        overrides: [
          sharedPreferencesProvider.overrideWithValue(prefs),
        ],
        child: const CexApp(),
      ),
    );
  } catch (e, stack) {
    debugPrint('🔴 [main] 初始化失败: $e\n$stack');
    rethrow;
  }
}
