import 'dart:io';
import 'package:device_info_plus/device_info_plus.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart';
import '../models/device_context.dart';

/// 设备信息收集器
/// 负责收集完整的设备上下文信息
class DeviceInfoCollector {
  static DeviceInfoCollector? _instance;
  DeviceInfoCollector._();

  factory DeviceInfoCollector() {
    _instance ??= DeviceInfoCollector._();
    return _instance!;
  }

  DeviceContext? _cachedContext;

  /// 收集完整设备上下文(首次会缓存)
  Future<DeviceContext> collect(BuildContext context) async {
    if (_cachedContext != null) return _cachedContext!;

    final deviceInfo = DeviceInfoPlugin();
    final packageInfo = await PackageInfo.fromPlatform();
    final mediaQuery = MediaQuery.of(context);

    DeviceContext result;

    if (Platform.isAndroid) {
      final androidInfo = await deviceInfo.androidInfo;

      result = DeviceContext(
        platform: 'android',
        brand: androidInfo.brand,
        model: androidInfo.model,
        manufacturer: androidInfo.manufacturer,
        isPhysicalDevice: androidInfo.isPhysicalDevice,
        osVersion: androidInfo.version.release,
        sdkInt: androidInfo.version.sdkInt,
        androidId: androidInfo.id, // 匿名ID,不是IMEI
        screen: _collectScreenInfo(mediaQuery),
        appName: packageInfo.appName,
        packageName: packageInfo.packageName,
        appVersion: packageInfo.version,
        buildNumber: packageInfo.buildNumber,
        buildMode: _getBuildMode(),
        locale: Platform.localeName,
        timezone: DateTime.now().timeZoneName,
        isDarkMode: mediaQuery.platformBrightness == Brightness.dark,
        networkType: 'unknown', // 需要额外的connectivity包
        collectedAt: DateTime.now(),
      );
    } else if (Platform.isIOS) {
      final iosInfo = await deviceInfo.iosInfo;

      result = DeviceContext(
        platform: 'ios',
        brand: 'Apple',
        model: iosInfo.model,
        manufacturer: 'Apple',
        isPhysicalDevice: iosInfo.isPhysicalDevice,
        osVersion: iosInfo.systemVersion,
        sdkInt: 0, // iOS没有SDK版本号
        androidId: iosInfo.identifierForVendor ?? '',
        screen: _collectScreenInfo(mediaQuery),
        appName: packageInfo.appName,
        packageName: packageInfo.packageName,
        appVersion: packageInfo.version,
        buildNumber: packageInfo.buildNumber,
        buildMode: _getBuildMode(),
        locale: Platform.localeName,
        timezone: DateTime.now().timeZoneName,
        isDarkMode: mediaQuery.platformBrightness == Brightness.dark,
        networkType: 'unknown',
        collectedAt: DateTime.now(),
      );
    } else {
      throw UnsupportedError('Unsupported platform');
    }

    _cachedContext = result;
    return result;
  }

  /// 收集屏幕信息
  ScreenInfo _collectScreenInfo(MediaQueryData mediaQuery) {
    final size = mediaQuery.size;
    final density = mediaQuery.devicePixelRatio;

    return ScreenInfo(
      widthPx: size.width * density,
      heightPx: size.height * density,
      density: density,
      widthDp: size.width,
      heightDp: size.height,
      hasNotch: mediaQuery.padding.top > 24, // 简单判断刘海屏
    );
  }

  /// 获取构建模式
  String _getBuildMode() {
    if (kReleaseMode) return 'release';
    if (kProfileMode) return 'profile';
    return 'debug';
  }

  /// 清除缓存(版本更新时调用)
  void clearCache() {
    _cachedContext = null;
  }

  /// 获取缓存的上下文
  DeviceContext? get cachedContext => _cachedContext;
}
