import 'package:flutter/widgets.dart';
import 'package:uuid/uuid.dart';
import '../telemetry_service.dart';
import '../models/telemetry_event.dart';
import 'session_events.dart';

/// 会话管理器
class SessionManager with WidgetsBindingObserver {
  static SessionManager? _instance;

  SessionManager._();

  factory SessionManager() {
    _instance ??= SessionManager._();
    return _instance!;
  }

  String? _currentSessionId;
  String? get currentSessionId => _currentSessionId;

  SessionState _state = SessionState.unknown;
  SessionState get state => _state;

  DateTime? _sessionStartTime;

  VoidCallback? onSessionStart;
  VoidCallback? onSessionEnd;

  TelemetryService? _telemetryService;

  bool _isInitialized = false;

  void initialize(TelemetryService telemetryService) {
    if (_isInitialized) return;

    _telemetryService = telemetryService;
    WidgetsBinding.instance.addObserver(this);

    _handleForeground();

    _isInitialized = true;
    debugPrint('[Session] Manager initialized');
  }

  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    _isInitialized = false;
    _instance = null;
    debugPrint('[Session] Manager disposed');
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    switch (state) {
      case AppLifecycleState.resumed:
        _handleForeground();
        break;
      case AppLifecycleState.paused:
        _handleBackground();
        break;
      case AppLifecycleState.inactive:
      case AppLifecycleState.detached:
      case AppLifecycleState.hidden:
        break;
    }
  }

  void _handleForeground() {
    if (_state == SessionState.foreground) return;

    _state = SessionState.foreground;
    _startNewSession();
    // 上传上次被强杀遗留的事件 + 本次 session_start（含设备信息）
    _telemetryService?.flushOnBackground();
  }

  void _handleBackground() {
    if (_state == SessionState.background) return;

    _state = SessionState.background;
    _endCurrentSession();
    // session_end 写入队列后立即上传，不等待阈值
    _telemetryService?.flushOnBackground();
  }

  void _startNewSession() {
    _currentSessionId = const Uuid().v4();
    _sessionStartTime = DateTime.now();

    _telemetryService?.logEvent(
      SessionEvents.sessionStart,
      type: EventType.session,
      level: EventLevel.info,
      properties: {
        'session_id': _currentSessionId,
      },
    );

    onSessionStart?.call();

    debugPrint('[Session] Started: $_currentSessionId');
  }

  void _endCurrentSession() {
    if (_currentSessionId == null) return;

    final duration = _sessionStartTime != null
        ? DateTime.now().difference(_sessionStartTime!).inSeconds
        : 0;

    _telemetryService?.logEvent(
      SessionEvents.sessionEnd,
      type: EventType.session,
      level: EventLevel.info,
      properties: {
        'session_id': _currentSessionId,
        'duration_seconds': duration,
      },
    );

    onSessionEnd?.call();

    debugPrint('[Session] Ended: $_currentSessionId (${duration}s)');

    _currentSessionId = null;
    _sessionStartTime = null;
  }

  int get sessionDurationSeconds {
    if (_sessionStartTime == null) return 0;
    return DateTime.now().difference(_sessionStartTime!).inSeconds;
  }
}
