import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter/foundation.dart';
import '../models/telemetry_event.dart';

class TelemetryStorage {
  static const String _keyEventQueue = 'telemetry_event_queue';
  static const String _keyDeviceContext = 'telemetry_device_context';
  static const String _keyInstallId = 'telemetry_install_id';
  static const int _maxQueueSize = 500;

  late SharedPreferences _prefs;
  bool _isInitialized = false;

  Future<void> init() async {
    if (_isInitialized) return;
    _prefs = await SharedPreferences.getInstance();
    _isInitialized = true;
  }

  Future<void> saveDeviceContext(Map<String, dynamic> context) async {
    await _prefs.setString(_keyDeviceContext, jsonEncode(context));
  }

  Map<String, dynamic>? getDeviceContext() {
    final str = _prefs.getString(_keyDeviceContext);
    if (str == null) return null;
    return jsonDecode(str) as Map<String, dynamic>;
  }

  Future<void> saveInstallId(String installId) async {
    await _prefs.setString(_keyInstallId, installId);
  }

  String? getInstallId() => _prefs.getString(_keyInstallId);

  Future<void> enqueueEvent(TelemetryEvent event) async {
    final queue = _getEventQueue();
    if (queue.length >= _maxQueueSize) {
      queue.removeAt(0);
      debugPrint('[TelemetryStorage] Queue full, dropped oldest event');
    }
    queue.add(event.toJson());
    await _saveEventQueue(queue);
  }

  List<TelemetryEvent> dequeueEvents(int limit) {
    final queue = _getEventQueue();
    final count = queue.length > limit ? limit : queue.length;
    return queue.take(count).map((json) => TelemetryEvent.fromJson(json)).toList();
  }

  Future<void> removeEvents(int count) async {
    final queue = _getEventQueue();
    if (count >= queue.length) {
      await clearEventQueue();
    } else {
      queue.removeRange(0, count);
      await _saveEventQueue(queue);
    }
  }

  int getQueueSize() => _getEventQueue().length;

  Future<void> clearEventQueue() async {
    await _prefs.remove(_keyEventQueue);
  }

  Future<void> clearUserData() async {
    if (!_isInitialized) await init();
    await _prefs.remove(_keyEventQueue);
  }

  List<Map<String, dynamic>> _getEventQueue() {
    final str = _prefs.getString(_keyEventQueue);
    if (str == null) return [];
    try {
      return (jsonDecode(str) as List).cast<Map<String, dynamic>>();
    } catch (e) {
      debugPrint('[TelemetryStorage] Failed to parse queue: $e');
      return [];
    }
  }

  Future<void> _saveEventQueue(List<Map<String, dynamic>> queue) async {
    await _prefs.setString(_keyEventQueue, jsonEncode(queue));
  }
}
