import 'package:system_clock/system_clock.dart';

import 'boost_logger.dart';
import 'log/logger.dart';
import 'ntp_time_service.dart';

class BoostReportManager {
  final BoostLogger _logger = BoostLogger();
  static const String TAG = 'BoostReportManager';
  static final BoostReportManager _instance = BoostReportManager._internal();
  factory BoostReportManager() => _instance;
  BoostReportManager._internal();

  /// 初始化报告管理器
  Future<void> init() async {
    try {
      await _logger.init();

      // 初始化基本结构
      await _logger.setSection('sessionInfo', {});
      await _logger.setSection('targetInfo', {});
      await _logger.setSectionObj('generatedTime', _getCurrentTimestamp());
    } catch (e) {
      log(TAG, 'BoostReportManager init error: $e');
    }
  }

  int _getCurrentTimestamp() {
    return NtpTimeService().getCurrentTimestamp();
  }

  /// 读取历史日志
  Future<void> readHistoryLog() async {
    try {
      await _logger.readHistoryLog();
    } catch (e) {
      log(TAG, 'BoostReportManager readHistoryLog error: $e');
    }
  }

  /// 初始化会话信息
  Future<void> initSessionInfo({
    required String appSessionId,
    required String boostSessionId,
    required Map<String, String> deviceInfo,
  }) async {
    try {
      await _logger.setSection('sessionInfo', {
        'appSessionId': appSessionId,
        'boostSessionId': boostSessionId,
        'success': false,
        'errorCode': -1,
        'boostStartTime': _getCurrentTimestamp(),
        'boostStopTime': 0,
        'boostDuration': 0,
        'elapsedRealtime': SystemClock.elapsedRealtime().inMilliseconds,
        'userDeviceInfo': {
          'deviceModel': deviceInfo['deviceModel'] ?? '',
          'osVersion': deviceInfo['osVersion'] ?? '',
          'appVersion': deviceInfo['appVersion'] ?? '',
          'networkType': deviceInfo['networkType'] ?? '',
          'deviceBrand': deviceInfo['deviceBrand'] ?? '',
        },
      });
    } catch (e) {
      log(TAG, 'BoostReportManager initSessionInfo error: $e');
    }
  }

  /// 添加 targetInfo
  Future<void> addTargetInfo({
    required String locationSelectionType,
    required dynamic location,
  }) async {
    try {
      await _logger.updateField(
        'targetInfo',
        'locationSelectionType',
        locationSelectionType,
      );
      await _logger.updateField('targetInfo', 'location', location);
    } catch (e) {
      log(TAG, 'BoostReportManager addTargetInfo error: $e');
    }
  }

  /// 添加 latencyList
  Future<void> addLatencyList({required Map<String, int> latencyList}) async {
    try {
      await _logger.setSectionObj('latencys', latencyList);
    } catch (e) {
      log(TAG, 'BoostReportManager addLatencyList error: $e');
    }
  }

  // 获取 boostStartTime
  int getBoostStartTime() {
    try {
      final session = _logger.getCurrentSession();
      final sessionInfo = session['sessionInfo'] as Map<String, dynamic>;
      return sessionInfo['boostStartTime'] as int;
    } catch (e) {
      log(TAG, 'BoostReportManager getBoostStartTime error: $e');
      return 0;
    }
  }

  /// 获取当前报告
  Map<String, dynamic> getCurrentReport() {
    return _logger.getCurrentSession();
  }

  /// 获取核心日志文件路径
  Future<String?> getCoreLogFilePath() {
    return _logger.getCoreLogFilePath();
  }

  /// 获取报告文件路径
  Future<String?> getAppLogFilePath() {
    return _logger.getAppLogFilePath();
  }

  /// 释放资源
  Future<void> release() async {
    await _logger.release();
  }
}
