namespace Jiaowu.Api.Infrastructure.Teaching;

public static class PublicCourseTaskAssignmentPlanner
{
    public static IReadOnlyList<Guid> AssignTeachers(
        IReadOnlyCollection<Guid> eligibleTeacherIds,
        IReadOnlyDictionary<Guid, int> existingLoads,
        int groupCount,
        Random? random = null)
    {
        if (eligibleTeacherIds.Count == 0)
            throw new ArgumentException("至少需要一名可分配教师。", nameof(eligibleTeacherIds));
        if (groupCount < 1)
            throw new ArgumentOutOfRangeException(nameof(groupCount));
        random ??= Random.Shared;
        var teachers = eligibleTeacherIds.Distinct().ToArray();
        var loads = teachers.ToDictionary(
            teacherId => teacherId,
            teacherId => existingLoads.GetValueOrDefault(teacherId));
        var assignments = new List<Guid>(groupCount);
        for (var index = 0; index < groupCount; index++)
        {
            var minimumLoad = loads.Values.Min();
            var candidates = teachers
                .Where(teacherId => loads[teacherId] == minimumLoad)
                .ToArray();
            var selected = candidates[random.Next(candidates.Length)];
            assignments.Add(selected);
            loads[selected]++;
        }
        return assignments;
    }
}
