import 'dart:async';
import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import '../storage/telemetry_storage.dart';

/// 遥测上传器
/// 负责批量上传事件到服务器
class TelemetryUploader {
  final String apiBaseUrl;
  final TelemetryStorage storage;
  final Dio _dio;

  Timer? _uploadTimer;
  bool _isUploading = false;

  /// 获取认证头的回调
  Map<String, String> Function()? getAuthHeaders;

  TelemetryUploader({
    required this.apiBaseUrl,
    required this.storage,
    this.getAuthHeaders,
  }) : _dio = Dio(BaseOptions(
          baseUrl: apiBaseUrl,
          connectTimeout: const Duration(seconds: 10),
          receiveTimeout: const Duration(seconds: 10),
        ));

  /// 启动定时上传(每30秒或累积20条)
  void startPeriodicUpload({
    Duration interval = const Duration(seconds: 30),
    int batchSize = 20,
  }) {
    _uploadTimer?.cancel();
    _uploadTimer = Timer.periodic(interval, (_) {
      uploadIfNeeded(batchSize: batchSize);
    });
    debugPrint('📊 Telemetry uploader started (interval: ${interval.inSeconds}s)');
  }

  /// 停止定时上传
  void stopPeriodicUpload() {
    _uploadTimer?.cancel();
    _uploadTimer = null;
    debugPrint('📊 Telemetry uploader stopped');
  }

  /// 条件上传(队列大于阈值才上传)
  Future<void> uploadIfNeeded({int batchSize = 20}) async {
    if (_isUploading) return;

    final queueSize = storage.getQueueSize();
    if (queueSize < 10) return; // 少于10条不上传,等待积累

    await uploadBatch(batchSize: batchSize);
  }

  /// 立即上传一批
  Future<bool> uploadBatch({int batchSize = 20}) async {
    if (_isUploading) return false;

    _isUploading = true;
    try {
      final events = storage.dequeueEvents(batchSize);
      if (events.isEmpty) return true;

      // 调用后端API (使用 toServerJson 格式化为服务端期望的格式)
      final response = await _dio.post(
        '/api/v1/analytics/events',
        data: {
          'events': events.map((e) => e.toServerJson()).toList(),
        },
        options: Options(
          headers: getAuthHeaders?.call(),
        ),
      );

      if (response.statusCode == 200) {
        // 上传成功,删除本地记录
        await storage.removeEvents(events.length);
        debugPrint('✅ Uploaded ${events.length} telemetry events');
        return true;
      } else {
        debugPrint('❌ Upload failed: ${response.statusCode}');
        return false;
      }
    } on DioException catch (e) {
      debugPrint('❌ Upload error (DioException): ${e.message}');
      return false;
    } catch (e) {
      debugPrint('❌ Upload error: $e');
      return false;
    } finally {
      _isUploading = false;
    }
  }

  /// 强制上传全部(app退出前调用)
  Future<void> forceUploadAll() async {
    stopPeriodicUpload();

    int retries = 0;
    while (storage.getQueueSize() > 0 && retries < 3) {
      final success = await uploadBatch(batchSize: 50);
      if (!success) {
        retries++;
        await Future.delayed(const Duration(seconds: 1));
      }
    }

    if (storage.getQueueSize() > 0) {
      debugPrint('⚠️ ${storage.getQueueSize()} events remaining in queue');
    }
  }
}
