import 'dart:collection';
import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';

/// Persistent error logger that stores recent API errors locally.
/// Keeps the last [maxEntries] errors for diagnostics.
/// Can be extended to flush to Sentry/Crashlytics/backend.
class ErrorLogger {
  static final ErrorLogger instance = ErrorLogger._();
  ErrorLogger._();

  static const String _storageKey = 'error_log';
  static const int maxEntries = 50;

  final _buffer = Queue<Map<String, dynamic>>();
  bool _initialized = false;

  /// Loads persisted errors from SharedPreferences.
  Future<void> init() async {
    if (_initialized) return;
    try {
      final prefs = await SharedPreferences.getInstance();
      final raw = prefs.getString(_storageKey);
      if (raw != null) {
        final list = jsonDecode(raw) as List;
        for (final item in list) {
          _buffer.add(Map<String, dynamic>.from(item as Map));
        }
      }
    } catch (_) {
      // Silent — don't let logging failures break the app
    }
    _initialized = true;
  }

  /// Logs a structured error entry.
  void log(Map<String, dynamic> entry) {
    _buffer.addLast(entry);
    while (_buffer.length > maxEntries) {
      _buffer.removeFirst();
    }
    _persist();
  }

  /// Returns all logged errors (newest last).
  List<Map<String, dynamic>> get entries => _buffer.toList();

  /// Clears all logged errors.
  Future<void> clear() async {
    _buffer.clear();
    try {
      final prefs = await SharedPreferences.getInstance();
      await prefs.remove(_storageKey);
    } catch (_) {}
  }

  /// Returns a summary: total errors, most frequent endpoint, last error time.
  Map<String, dynamic> get summary {
    if (_buffer.isEmpty) {
      return {'totalErrors': 0};
    }

    // Count errors by URL
    final urlCounts = <String, int>{};
    for (final entry in _buffer) {
      final url = entry['url'] as String? ?? 'unknown';
      // Strip query params for grouping
      final path = Uri.tryParse(url)?.path ?? url;
      urlCounts[path] = (urlCounts[path] ?? 0) + 1;
    }

    final topUrl = urlCounts.entries.reduce(
      (a, b) => a.value >= b.value ? a : b,
    );

    return {
      'totalErrors': _buffer.length,
      'mostFrequentEndpoint': topUrl.key,
      'mostFrequentCount': topUrl.value,
      'lastErrorAt': _buffer.last['timestamp'],
    };
  }

  Future<void> _persist() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      await prefs.setString(_storageKey, jsonEncode(_buffer.toList()));
    } catch (_) {
      // Silent
    }
  }
}
