import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_ume/flutter_ume.dart';
import 'package:flutter_ume_kit_device/components/device_info/device_info_panel.dart';
import 'package:flutter_ume_kit_dio/flutter_ume_kit_dio.dart';
import 'package:recording_tool/app/app.dart';
import 'package:recording_tool/app/config/app_config.dart';
import 'package:recording_tool/core/cache/app_storage.dart';
import 'package:recording_tool/core/logging/app_logger.dart';
import 'package:recording_tool/core/network/app_dio.dart';
import 'package:recording_tool/core/platform/app_platform_info.dart';

class AppBootstrapper {
  AppBootstrapper._();

  static Future<void> bootstrap({
    AppEnvironment environment = AppEnvironment.dev,
  }) async {
    WidgetsFlutterBinding.ensureInitialized();

    await SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);

    await AppStorage.init();

    AppConfig.configure(environment: environment);

    AppLogger.debug('App started in ${AppConfig.current.environment.name}');

    // 注册 UME 调试插件（DioInspector 需与业务共用同一 Dio 实例）
    PluginManager.instance
      ..register(DioInspector(dio: AppDio.instance))
      ..register(DeviceInfoPanel());

    runApp(
      UMEWidget(
        enable: true,
        child: Stack(
          alignment: Alignment.center,
          children: [const ProviderScope(child: FlutterTemplateApp())],
        ),
      ),
    );
    // runApp(const ProviderScope(child: FlutterTemplateApp()));

    // Load native package metadata after the first frame can render.
    // Awaiting MethodChannel calls before runApp() can stall the Android
    // splash screen on some devices.
    unawaited(_loadPackageInfo(environment));
  }

  static Future<void> _loadPackageInfo(AppEnvironment environment) async {
    try {
      final packageInfo = await AppPlatformInfo.packageInfo().timeout(
        const Duration(seconds: 8),
      );
      AppConfig.configure(environment: environment, packageInfo: packageInfo);
    } catch (error, stackTrace) {
      AppLogger.debug(
        'Native packageInfo unavailable',
        error: error,
        stackTrace: stackTrace,
      );
    }
  }
}
