

library;

import '../../../core/contracts/library.dart';
import '../../../providers/version_priority_provider.dart';
import '../../../shared/widgets/version_filter.dart';
import '../../../shared/widgets/version_source_card.dart';


class MultiSourceVersionEntry {
  final String bucket;
  final VersionSourceCardData data;
  final EmbyRawMediaSource source;
  final bool isLocal;


  final bool isActive;


  final int localIndex;

  final String serverName;
  final String serverId;
  final String itemId;
  final String mediaSourceId;

  const MultiSourceVersionEntry({
    required this.bucket,
    required this.data,
    required this.source,
    required this.isLocal,
    required this.isActive,
    required this.localIndex,
    required this.serverName,
    required this.serverId,
    required this.itemId,
    required this.mediaSourceId,
  });
}

void sortMultiSourceEntries(
  List<MultiSourceVersionEntry> entries,
  List<VersionPriority> priorities,
) {
  entries.sort((a, b) => compareMultiSourceEntries(a, b, priorities));
}


int compareMultiSourceEntries(
  MultiSourceVersionEntry a,
  MultiSourceVersionEntry b,
  List<VersionPriority> priorities,
) {
  final ba = kVersionBucketOrder.indexOf(a.bucket);
  final bb = kVersionBucketOrder.indexOf(b.bucket);
  if (ba != bb) return ba.compareTo(bb);

  if (priorities.isNotEmpty) {
    final cmp = compareMediaSourcesByPriority(a.source, b.source, priorities);
    if (cmp != 0) return cmp;
  }

  if (a.isLocal != b.isLocal) return a.isLocal ? -1 : 1;

  if (a.isLocal && b.isLocal) return a.localIndex.compareTo(b.localIndex);
  final byServerName = a.serverName.compareTo(b.serverName);
  if (byServerName != 0) return byServerName;
  final byServerId = a.serverId.compareTo(b.serverId);
  if (byServerId != 0) return byServerId;
  final byItemId = a.itemId.compareTo(b.itemId);
  if (byItemId != 0) return byItemId;
  return a.mediaSourceId.compareTo(b.mediaSourceId);
}


String? defaultSelectedBucketForEntries(List<MultiSourceVersionEntry> entries) {
  if (entries.isEmpty) return null;
  for (final e in entries) {
    if (e.isActive) return e.bucket;
  }
  final present = entries.map((e) => e.bucket).toSet();
  for (final bucket in kVersionBucketOrder) {
    if (present.contains(bucket)) return bucket;
  }
  return entries.first.bucket;
}
