import 'dart:async';
import 'dart:ui';

import 'package:aesthetica_wallpaper/providers/editor_provider.dart';
import 'package:aesthetica_wallpaper/providers/recipe_provider.dart';
import 'package:aesthetica_wallpaper/providers/weather_provider.dart';
import 'package:aesthetica_wallpaper/providers/puzzle_provider.dart';
import 'package:aesthetica_wallpaper/providers/drag_puzzle_provider.dart';
import 'package:aesthetica_wallpaper/core/app.dart';
import 'package:firebase_analytics/firebase_analytics.dart';
import 'package:firebase_analytics/observer.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_crashlytics/firebase_crashlytics.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

import 'core/firebase_optinons.dart';

bool isFirebaseInitialized = false;

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

    try {
      await Firebase.initializeApp(
        options: DefaultFirebaseOptions.currentPlatform,
      ).timeout(const Duration(seconds: 10)); // 设置15秒超时
      print("✅ Firebase 初始化成功。");
      isFirebaseInitialized = true; // 成功后设置标志
    } on TimeoutException {
      print("⚠️ Firebase 初始化超时 (超过15秒)，应用将继续运行但相关功能将不可用。");
    } catch (error, stack) {
      print("!!!!!!!!!! Firebase 初始化失败 !!!!!!!!!!: $error");
      FirebaseCrashlytics.instance.recordError(error, stack, fatal: false);
    }

    // Firebase 成功初始化后，配置依赖它的服务
    if (isFirebaseInitialized) {
      //设置全局错误处理器
      FlutterError.onError = FirebaseCrashlytics.instance.recordFlutterError;
      PlatformDispatcher.instance.onError = (error, stack) {
        FirebaseCrashlytics.instance.recordError(error, stack, fatal: true);
        return true;
      };
      // 使用安全服务来记录 App Open
      AnalyticsService.instance.logAppOpen();
    }

    final analyObserver = SafeFirebaseAnalyticsObserver();
    runApp(
      MultiProvider(
        providers: [
          ChangeNotifierProvider(create: (_) => EditorProvider()),
          ChangeNotifierProvider(
            create: (_) => RecipeProvider()..loadRecipes(),
          ),
          ChangeNotifierProvider(create: (_) => WeatherProvider()),
          ChangeNotifierProvider(create: (_) => PuzzleProvider()),
          ChangeNotifierProvider(create: (_) => DragPuzzleProvider()),
        ],
        child: AestheticaApp(analyObserver: analyObserver),
      ),
    );
  }, (e, s) {});
}

class AnalyticsService {
  // 单例模式
  AnalyticsService._();
  static final instance = AnalyticsService._();
  final _analytics = FirebaseAnalytics.instance;
  /// 安全地记录一个 App Open 事件。
  void logAppOpen() {
    if (isFirebaseInitialized) {
      _analytics.logAppOpen();
    } else {
      print("[AnalyticsService] Skipped logAppOpen: Firebase not initialized.");
    }
  }
}

class SafeFirebaseAnalyticsObserver extends NavigatorObserver {
  late final FirebaseAnalyticsObserver _observer;

  SafeFirebaseAnalyticsObserver() {
    if (isFirebaseInitialized) {
      _observer = FirebaseAnalyticsObserver(
        analytics: AnalyticsService.instance._analytics,
      );
    }
  }

  @override
  void didPush(Route<dynamic> route, Route<dynamic>? previousRoute) {
    if (isFirebaseInitialized) {
      _observer.didPush(route, previousRoute);
    }
  }

  @override
  void didPop(Route<dynamic> route, Route<dynamic>? previousRoute) {
    if (isFirebaseInitialized) {
      _observer.didPop(route, previousRoute);
    }
  }

  @override
  void didReplace({Route<dynamic>? newRoute, Route<dynamic>? oldRoute}) {
    if (isFirebaseInitialized) {
      _observer.didReplace(newRoute: newRoute, oldRoute: oldRoute);
    }
  }
}
