import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.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/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}');

    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,
      );
    }
  }
}
