// Version: 1.3.0 | Created: 2026-04-01 | Updated: 2026-07-04
// MatrixRTC repository — handles outgoing call invites and detects incoming
// calls. v1.3.0 adds MSC3401 call.member state-event detection: Element X
// (and app2 itself) signals group calls with org.matrix.msc3401.call.member,
// not legacy m.call.invite, so incoming calls from Element X were invisible.
// Both paths now guard against stale events replayed during initial sync.
//
// Incoming calls are surfaced via the incomingCallStream so the
// IncomingCallOverlay can react to them.

import 'dart:async';

import 'package:matrix/matrix.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';

import '../../../core/auth/auth_notifier.dart';
import '../../../core/auth/auth_state.dart';
import '../../../core/network/matrix_client.dart';
import '../../../shared/utils/matrix_id.dart';
import '../../../shared/utils/mxc_url.dart';
import '../domain/incoming_call.dart';

part 'matrixrtc_repository.g.dart';

/// Repository for sending and receiving MatrixRTC call signalling events.
class MatrixRtcRepository {
  MatrixRtcRepository({required Client client, required String? myUserId})
    : _client = client,
      _myUserId = myUserId;

  final Client _client;
  final String? _myUserId;

  final _incomingCallController = StreamController<IncomingCall>.broadcast();

  /// Emits whenever an incoming call invite arrives for the local user.
  Stream<IncomingCall> get incomingCallStream => _incomingCallController.stream;

  StreamSubscription<EventUpdate>? _eventSubscription;

  /// Begin listening for incoming m.call.invite events.
  void startListening() {
    _eventSubscription?.cancel();
    _eventSubscription = _client.onEvent.stream.listen(_onEvent);
  }

  void stopListening() {
    _eventSubscription?.cancel();
    _eventSubscription = null;
  }

  /// Close the stream controller. Called from ref.onDispose only.
  void dispose() {
    stopListening();
    _incomingCallController.close();
  }

  /// Send a call invite to [roomId] to start a voice or video call.
  ///
  /// Uses the standard m.call.invite event type. The room's other participants
  /// will receive this via their sync stream.
  Future<void> sendCallInvite({
    required String roomId,
    required bool isVideo,
  }) async {
    final room = _client.getRoomById(roomId);
    if (room == null) return;

    final callId = 'call_${DateTime.now().millisecondsSinceEpoch}';

    await room.sendEvent({
      'msgtype': EventTypes.CallInvite,
      'call_id': callId,
      'lifetime': 60000, // 60 seconds before invite expires
      'offer': {
        'type': 'offer',
        'sdp': '', // SDP is populated by LiveKit once connected
      },
      'version': '1',
      'invitee': null, // null = invite entire room
      'm.intentional_mentions': {'user_ids': [], 'room': false},
    }, type: EventTypes.CallInvite);
  }

  /// MSC3401 MatrixRTC call membership state event (what Element X sends).
  static const _kCallMemberEventType = 'org.matrix.msc3401.call.member';

  /// Events older than this are sync replays, not live calls.
  static const _maxEventAge = Duration(seconds: 90);

  /// Membership keys we have already alerted on (roomId|sender|membership).
  final Set<String> _seenMembershipKeys = {};

  void _onEvent(EventUpdate update) {
    final eventType = update.content['type'] as String?;
    if (eventType == EventTypes.CallInvite &&
        update.type == EventUpdateType.timeline) {
      _onCallInvite(update);
    } else if (eventType == _kCallMemberEventType &&
        (update.type == EventUpdateType.timeline ||
            update.type == EventUpdateType.state)) {
      _onCallMember(update);
    }
  }

  bool _isStale(EventUpdate update) {
    final ts = update.content['origin_server_ts'] as int?;
    if (ts == null) return true;
    final age = DateTime.now().millisecondsSinceEpoch - ts;
    return age > _maxEventAge.inMilliseconds;
  }

  /// Legacy 1:1 call invites (app2 → app2).
  void _onCallInvite(EventUpdate update) {
    final senderId = update.content['sender'] as String?;
    // Ignore our own invites and stale events replayed on initial sync.
    if (senderId == _myUserId || _isStale(update)) return;

    final roomId = update.roomID;
    final content = update.content['content'] as Map<String, dynamic>?;
    if (content == null) return;

    final callId = content['call_id'] as String?;
    if (callId == null) return;
    if (!_seenMembershipKeys.add('$roomId|$senderId|$callId')) return;

    _emitIncomingCall(
      roomId: roomId,
      senderId: senderId ?? '',
      callId: callId,
      isVideo: content['offer'] != null,
    );
  }

  /// MSC3401 group-call membership: someone (e.g. Element X) joined a call.
  void _onCallMember(EventUpdate update) {
    final senderId = update.content['sender'] as String?;
    if (senderId == null || senderId == _myUserId || _isStale(update)) return;

    final content = update.content['content'] as Map<String, dynamic>?;
    final memberships = content?['memberships'] as List<dynamic>?;
    // Empty/cleared memberships means the caller hung up — nothing to show.
    if (memberships == null || memberships.isEmpty) return;

    final membership = memberships.first as Map<String, dynamic>;
    if (membership['application'] != 'm.call') return;

    final expiresTs = membership['expires_ts'] as int?;
    if (expiresTs != null &&
        expiresTs < DateTime.now().millisecondsSinceEpoch) {
      return;
    }

    final membershipId =
        (membership['membershipID'] ?? membership['call_id'] ?? '').toString();
    final roomId = update.roomID;
    if (!_seenMembershipKeys.add('$roomId|$senderId|$membershipId')) return;

    _emitIncomingCall(
      roomId: roomId,
      senderId: senderId,
      callId: membershipId.isEmpty ? 'matrixrtc' : membershipId,
      isVideo: true,
    );
  }

  void _emitIncomingCall({
    required String roomId,
    required String senderId,
    required String callId,
    required bool isVideo,
  }) {
    final room = _client.getRoomById(roomId);
    final senderProfile = room?.unsafeGetUserFromMemoryOrFallback(senderId);

    _incomingCallController.add(
      IncomingCall(
        callId: callId,
        roomId: roomId,
        callerId: senderId,
        callerDisplayName:
            senderProfile?.displayName ?? senderId.matrixLocalpart,
        callerAvatarUrl: resolveMxcUrl(_client, senderProfile?.avatarUrl),
        isVideo: isVideo,
      ),
    );
  }
}

@Riverpod(keepAlive: true)
MatrixRtcRepository matrixRtcRepository(Ref ref) {
  final client = ref.watch(matrixClientProvider);
  final authState = ref.watch(authProvider);
  final myUserId = authState is AuthAuthenticated ? authState.userId : null;

  final repo = MatrixRtcRepository(client: client, myUserId: myUserId);
  repo.startListening();
  ref.onDispose(repo.dispose);
  return repo;
}
