import 'dart:io';
import 'package:flutter/services.dart';
import 'package:flutter/foundation.dart';
import 'package:permission_handler/permission_handler.dart';

/// APK 安装器
/// 负责调用原生代码安装 APK 文件
class ApkInstaller {
  static const MethodChannel _channel =
      MethodChannel('com.iagent.it0_app/apk_installer');

  /// 安装 APK
  static Future<bool> installApk(File apkFile) async {
    try {
      if (!await apkFile.exists()) {
        debugPrint('APK file not found');
        return false;
      }

      // Android 8.0+ 需要请求安装权限
      if (Platform.isAndroid) {
        final hasPermission = await _requestInstallPermission();
        if (!hasPermission) {
          debugPrint('Install permission denied');
          return false;
        }
      }

      debugPrint('Installing APK: ${apkFile.path}');
      final result = await _channel.invokeMethod('installApk', {
        'apkPath': apkFile.path,
      });

      debugPrint('Installation triggered: $result');
      return result == true;
    } on PlatformException catch (e) {
      debugPrint('Install failed (PlatformException): ${e.message}');
      return false;
    } catch (e) {
      debugPrint('Install failed: $e');
      return false;
    }
  }

  /// 请求安装权限（Android 8.0+）
  static Future<bool> _requestInstallPermission() async {
    if (await Permission.requestInstallPackages.isGranted) {
      return true;
    }

    final status = await Permission.requestInstallPackages.request();
    return status.isGranted;
  }

  /// 检查是否有安装权限
  static Future<bool> hasInstallPermission() async {
    return await Permission.requestInstallPackages.isGranted;
  }
}
