import Combine
import Foundation

@MainActor
class ActiveRecallViewModel: ObservableObject {
    @Published var questions: [ActiveRecallQuestion] = []
    @Published var currentIndex = 0
    @Published var isSubmitting = false
    @Published var errorMessage: String?
    @Published var lastResult: ActiveRecallAnswer?

    var currentQuestion: ActiveRecallQuestion? {
        guard currentIndex < questions.count else { return nil }
        return questions[currentIndex]
    }

    func loadQuestions() async {
        isSubmitting = false
        errorMessage = nil
        do {
            questions = try await ActiveRecallService.shared.questions()
            currentIndex = 0
        } catch {
            errorMessage = "加载问题失败"
        }
    }

    func submitAnswer(text: String) async {
        guard let question = currentQuestion else { return }
        isSubmitting = true
        errorMessage = nil
        do {
            lastResult = try await ActiveRecallService.shared.submit(
                questionId: question.id, answerText: text
            )
            currentIndex += 1
        } catch {
            errorMessage = "提交回答失败"
        }
        isSubmitting = false
    }

    var isComplete: Bool {
        currentIndex >= questions.count
    }

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