import '../../../core/contracts/library.dart';
import '../../../shared/utils/tmdb_episode_helpers.dart';


String? resolveInitialSeasonId({
  required List<EmbyRawSeason> seasons,
  String? autoSelectSeasonId,
  String? initialSeasonId,
  String? currentEpisodeSeasonId,
  int? currentEpisodeSeasonNumber,
}) {
  if (seasons.isEmpty) return null;
  bool has(String? id) => id != null && seasons.any((s) => s.Id == id);
  if (has(autoSelectSeasonId)) return autoSelectSeasonId;
  if (has(initialSeasonId)) return initialSeasonId;
  if (has(currentEpisodeSeasonId)) return currentEpisodeSeasonId;
  if (currentEpisodeSeasonNumber != null) {
    for (final s in seasons) {
      if (seasonNumberFrom(s) == currentEpisodeSeasonNumber) return s.Id;
    }
  }
  return seasons.first.Id;
}


String? resolveActiveEpisodeId({
  required List<EmbyRawItem> episodes,
  String? currentEpisodeId,
  String? displayedSeasonId,
  int? displayedSeasonNumber,
  String? currentEpisodeSeasonId,
  int? currentEpisodeSeasonNumber,
  int? currentEpisodeIndexNumber,
}) {
  final id = currentEpisodeId;
  if (id == null || id.isEmpty) return null;
  if (episodes.any((e) => e.Id == id)) return id;
  final seasonMatches =
      (currentEpisodeSeasonId != null &&
          currentEpisodeSeasonId == displayedSeasonId) ||
      (currentEpisodeSeasonNumber != null &&
          displayedSeasonNumber != null &&
          currentEpisodeSeasonNumber == displayedSeasonNumber);
  if (seasonMatches && currentEpisodeIndexNumber != null) {
    for (final e in episodes) {
      if (e.IndexNumber == currentEpisodeIndexNumber) return e.Id;
    }
  }
  return id;
}
