import Combine
import Foundation

@MainActor
class ReviewViewModel: ObservableObject {
    @Published var dueCards: [ReviewCard] = []
    @Published var currentCardIndex = 0
    @Published var isLoading = false
    @Published var errorMessage: String?

    var currentCard: ReviewCard? {
        guard currentCardIndex < dueCards.count else { return nil }
        return dueCards[currentCardIndex]
    }

    var isComplete: Bool {
        currentCardIndex >= dueCards.count
    }

    var progress: Double {
        guard !dueCards.isEmpty else { return 0 }
        return Double(currentCardIndex) / Double(dueCards.count)
    }

    func loadDueCards() async {
        isLoading = true
        errorMessage = nil
        do {
            dueCards = try await ReviewService.shared.dueCards()
            currentCardIndex = 0
        } catch {
            errorMessage = "加载复习卡片失败"
        }
        isLoading = false
    }

    func submitRating(_ rating: String, responseText: String? = nil) async {
        guard let card = currentCard else { return }
        do {
            _ = try await ReviewService.shared.submit(
                id: card.id, rating: rating, responseText: responseText
            )
            currentCardIndex += 1
        } catch {
            errorMessage = "提交复习结果失败"
        }
    }
}
