import Foundation
import SwiftData

public enum VerbStore {
    /// Deterministically pick a `Verb` for the given date, filtered by the user's
    /// selected level (which expands to the set of underlying data levels).
    /// Returns nil if there are no matching verbs.
    public static func fetchVerbOfDay(
        for date: Date,
        dayOffset: Int,
        selectedLevel: String,
        context: ModelContext
    ) -> Verb? {
        let allowedLevels = Array(VerbLevelGroup.dataLevels(for: selectedLevel))
        var descriptor = FetchDescriptor<Verb>(
            predicate: #Predicate<Verb> { verb in
                allowedLevels.contains(verb.level)
            },
            sortBy: [SortDescriptor(\Verb.rank), SortDescriptor(\Verb.infinitive)]
        )

        let count = (try? context.fetchCount(descriptor)) ?? 0
        guard count > 0 else { return nil }

        let dayOfYear = Calendar.current.ordinality(of: .day, in: .year, for: date) ?? 1
        let index = (dayOfYear + dayOffset) % count

        descriptor.fetchOffset = index
        descriptor.fetchLimit = 1
        return (try? context.fetch(descriptor))?.first
    }
}
