import 'dart:io';

import 'package:flutter/services.dart';
import 'package:recording_tool/core/platform/device_health_snapshot.dart';

class AppPackageInfo {
  const AppPackageInfo({
    required this.appName,
    required this.packageName,
    required this.version,
    required this.buildNumber,
  });

  factory AppPackageInfo.fromMap(Map<Object?, Object?> map) {
    return AppPackageInfo(
      appName: map['appName'] as String? ?? '',
      packageName: map['packageName'] as String? ?? '',
      version: map['version'] as String? ?? '',
      buildNumber: map['buildNumber'] as String? ?? '',
    );
  }

  final String appName;
  final String packageName;
  final String version;
  final String buildNumber;
}

class AppDeviceInfo {
  const AppDeviceInfo({
    required this.platform,
    required this.isPhysicalDevice,
    required this.values,
    required this.deviceCode,
  });

  factory AppDeviceInfo.fromMap(Map<Object?, Object?> map) {
    final values = <String, String>{};
    for (final entry in map.entries) {
      final key = entry.key;
      final value = entry.value;
      if (key is String && value != null) {
        values[key] = value.toString();
      }
    }

    final isPhysicalDevice = map['isPhysicalDevice'];
    return AppDeviceInfo(
      platform: map['platform'] as String? ?? Platform.operatingSystem,
      isPhysicalDevice: isPhysicalDevice is bool ? isPhysicalDevice : true,
      values: values,
      deviceCode: values['deviceCode'] ?? '',
    );
  }

  final String platform;
  final bool isPhysicalDevice;
  final Map<String, String> values;
  final String deviceCode;
}

class AppPlatformInfo {
  AppPlatformInfo._();

  static const MethodChannel _channel = MethodChannel(
    'app.record_tool/platform_info',
  );

  static Future<AppPackageInfo> packageInfo() async {
    final result = await _channel.invokeMapMethod<Object?, Object?>(
      'packageInfo',
    );
    return AppPackageInfo.fromMap(result ?? const <Object?, Object?>{});
  }

  static Future<AppDeviceInfo> deviceInfo() async {
    final result = await _channel.invokeMapMethod<Object?, Object?>(
      'deviceInfo',
    );
    return AppDeviceInfo.fromMap(result ?? const <Object?, Object?>{});
  }

  static Future<DeviceHealthSnapshot> deviceHealth() async {
    final result = await _channel.invokeMapMethod<Object?, Object?>(
      'deviceHealth',
    );
    return DeviceHealthSnapshot.fromMap(result ?? const <Object?, Object?>{});
  }
}
