import Foundation
import SharedModels
import SwiftData

/// SRS rating for non-verb vocab cards. Mirrors `VerbReviewStore` but keyed
/// by `(partOfSpeech, lexemeId, drillMode)` so independent drills against the
/// same lexeme don't fight over one schedule.
struct LexemeReviewStore {
    let context: ModelContext

    @discardableResult
    func fetchOrCreateReviewCard(
        lexemeId: String,
        partOfSpeech: String,
        drillMode: String
    ) -> LexemeReviewCard {
        let id = LexemeReviewCard.makeId(
            lexemeId: lexemeId,
            partOfSpeech: partOfSpeech,
            drillMode: drillMode
        )
        let descriptor = FetchDescriptor<LexemeReviewCard>(
            predicate: #Predicate<LexemeReviewCard> { $0.id == id }
        )
        if let existing = (try? context.fetch(descriptor))?.first {
            return existing
        }
        let card = LexemeReviewCard(
            lexemeId: lexemeId,
            partOfSpeech: partOfSpeech,
            drillMode: drillMode
        )
        context.insert(card)
        return card
    }

    func rate(
        lexemeId: String,
        partOfSpeech: String,
        drillMode: String,
        quality: ReviewQuality
    ) {
        let card = fetchOrCreateReviewCard(
            lexemeId: lexemeId,
            partOfSpeech: partOfSpeech,
            drillMode: drillMode
        )
        let result = SRSEngine.review(
            quality: quality,
            currentEase: card.easeFactor,
            currentInterval: card.interval,
            currentReps: card.repetitions
        )
        card.easeFactor = result.easeFactor
        card.interval = result.interval
        card.repetitions = result.repetitions
        card.dueDate = SRSEngine.nextDueDate(interval: result.interval)
        card.lastReviewDate = Date()
        try? context.save()
    }
}
