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

/// 会话管理器
///
/// 职责：
/// 1. 监听 App 生命周期，触发 app_session_start/app_session_end 事件
/// 2. 管理 sessionId（每次前台生成新的）
/// 3. 与 HeartbeatService 联动（前台启动心跳，后台停止）
class SessionManager with WidgetsBindingObserver {
  static SessionManager? _instance;

  SessionManager._();

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

  /// 当前会话 ID
  String? _currentSessionId;
  String? get currentSessionId => _currentSessionId;

  /// 当前会话状态
  SessionState _state = SessionState.unknown;
  SessionState get state => _state;

  /// 会话开始时间
  DateTime? _sessionStartTime;

  /// 回调：会话开始（HeartbeatService 监听此回调）
  VoidCallback? onSessionStart;

  /// 回调：会话结束（HeartbeatService 监听此回调）
  VoidCallback? onSessionEnd;

  /// TelemetryService 引用
  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（含设备信息）
    // Amplitude/Mixpanel 标准做法：回到前台即是下一次上传机会
    _telemetryService?.flushOnBackground();
  }

  /// 处理进入后台
  void _handleBackground() {
    if (_state == SessionState.background) return;

    _state = SessionState.background;
    _endCurrentSession();

    // session_end 写入队列后立即上传，不等待10条阈值
    _telemetryService?.flushOnBackground();
  }

  /// 开始新会话
  void _startNewSession() {
    // 生成新的 sessionId
    _currentSessionId = const Uuid().v4();
    _sessionStartTime = DateTime.now();

    // 记录 app_session_start 事件（用于 DAU）
    _telemetryService?.logEvent(
      SessionEvents.sessionStart,
      type: EventType.session,
      level: EventLevel.info,
      properties: {
        'session_id': _currentSessionId,
      },
    );

    // 通知外部（HeartbeatService 会监听这个回调）
    onSessionStart?.call();

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

  /// 结束当前会话
  void _endCurrentSession() {
    if (_currentSessionId == null) return;

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

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

    // 通知外部（HeartbeatService 会监听这个回调）
    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;
  }
}
