import Foundation public struct ServicePlanner { public var people: [Person] public var absences: [Absence] public var services: [ServiceOccurrence] public var existingAssignments: [Assignment] public var churches: [Church] public var options: PlannerOptions public init( people: [Person], absences: [Absence], services: [ServiceOccurrence], existingAssignments: [Assignment] = [], churches: [Church] = [], options: PlannerOptions = PlannerOptions() ) { self.people = people self.absences = absences self.services = services self.existingAssignments = existingAssignments self.churches = churches self.options = options } public func plan() -> PlanResult { let activePeople = people.filter(\.active) let peopleByID = Dictionary(uniqueKeysWithValues: activePeople.map { ($0.id, $0) }) let absencesByPerson = Dictionary(grouping: absences, by: \.personID) let churchNames = Dictionary(uniqueKeysWithValues: churches.map { ($0.id, $0.name) }) var working: [Assignment] if options.replaceExisting { working = existingAssignments.filter(\.locked) } else { working = existingAssignments } var totalByPerson: [String: Int] = [:] var monthByPerson: [String: Int] = [:] var dayByPerson: [String: Int] = [:] var churchByPerson: [String: [String: Int]] = [:] var lastDateByPerson: [String: Date] = [:] for assignment in working { guard let service = services.first(where: { $0.id == assignment.serviceID }) else { continue } let month = DayMath.monthKey(service.date) totalByPerson[assignment.personID, default: 0] += 1 monthByPerson["\(assignment.personID)|\(month)", default: 0] += 1 dayByPerson["\(assignment.personID)|\(service.dateKey)", default: 0] += 1 churchByPerson[assignment.personID, default: [:]][service.churchID, default: 0] += 1 let previous = lastDateByPerson[assignment.personID] if previous == nil || service.date > previous! { lastDateByPerson[assignment.personID] = service.date } } let sortedServices = services.sorted { if $0.date != $1.date { return $0.date < $1.date } if $0.timeMinutes != $1.timeMinutes { return $0.timeMinutes < $1.timeMinutes } return $0.id < $1.id } var unfilled: [UnfilledSlot] = [] var newAssignments: [Assignment] = [] for service in sortedServices { for role in Role.allCases { let required = service.requiredCount(for: role) guard required > 0 else { continue } let existingForRole = working.filter { $0.serviceID == service.id && $0.role == role }.count if existingForRole >= required { continue } for _ in existingForRole.. ) -> CandidateResult { var candidates: [(Person, Double)] = [] var blockedReasons: [String: Int] = [:] for person in people where person.canFill(role) { guard !alreadyAssigned.contains(person.id) else { blockedReasons["bereits im Gottesdienst", default: 0] += 1 continue } if let absences = absencesByPerson[person.id], absences.contains(where: { $0.overlaps(service.date) }) { blockedReasons["abwesend", default: 0] += 1 continue } if options.respectPreferredWeekdays, !person.preferredWeekdays.isEmpty, !person.preferredWeekdays.contains(DayMath.weekday(service.date)) { blockedReasons["Einsatztag passt nicht", default: 0] += 1 continue } let month = DayMath.monthKey(service.date) let usedThisMonth = monthByPerson["\(person.id)|\(month)", default: 0] if person.maxPerMonth > 0, usedThisMonth >= person.maxPerMonth { blockedReasons["Monatslimit erreicht", default: 0] += 1 continue } let usedThisDay = dayByPerson["\(person.id)|\(service.dateKey)", default: 0] if usedThisDay >= options.maxAssignmentsPerDay { blockedReasons["bereits an diesem Tag", default: 0] += 1 continue } var score = 10.0 if person.preferredChurchIDs.contains(service.churchID) { score += options.weightChurchPreference } if !person.preferredChurchIDs.isEmpty && !person.preferredChurchIDs.contains(service.churchID) { score -= 1.5 } if !person.preferredServiceTitles.isEmpty { let title = service.title.lowercased() for preference in person.preferredServiceTitles where !preference.isEmpty { if title.contains(preference.lowercased()) { score += options.weightServicePreference } } } if person.preferredWeekdays.contains(DayMath.weekday(service.date)) { score += 3 } let total = totalByPerson[person.id, default: 0] score -= Double(total) * options.weightFairness let churchCount = churchByPerson[person.id]?[service.churchID, default: 0] ?? 0 score -= Double(churchCount) * 0.4 if let last = lastDateByPerson[person.id] { let gap = DayMath.daysBetween(last, service.date) if gap >= 14 { score += 1.8 } else if gap >= 7 { score += 0.8 } } else { score += 2.5 } score += stableTieBreak("\(person.id)|\(service.id)|\(role.rawValue)") candidates.append((person, score)) } guard let best = candidates.max(by: { $0.1 < $1.1 }) else { let reason: String if blockedReasons.isEmpty { reason = "Keine geeignete Person mit Rolle \(role.title)" } else if let top = blockedReasons.max(by: { $0.value < $1.value }) { reason = "\(top.key) (\(top.value) ausgeschlossen)" } else { reason = "Keine geeignete Person" } return .failure(reason) } return .success(best.0) } private func stableTieBreak(_ value: String) -> Double { var hash = 5381 for byte in value.utf8 { hash = ((hash << 5) &+ hash) &+ Int(byte) } return Double(abs(hash % 997)) / 100_000 } }