import Combine
import Foundation

@MainActor
class StudyViewModel: ObservableObject {
    @Published var sessions: [LearningSession] = []
    @Published var currentSession: LearningSession?
    @Published var isLoading = false
    @Published var errorMessage: String?

    func loadSessions() async {
        isLoading = true
        errorMessage = nil
        do {
            sessions = try await LearningSessionService.shared.list()
        } catch {
            errorMessage = "加载学习会话失败"
        }
        isLoading = false
    }

    func startSession(knowledgeBaseId: String? = nil, mode: String? = nil) async {
        do {
            currentSession = try await LearningSessionService.shared.start(
                knowledgeBaseId: knowledgeBaseId, mode: mode
            )
            sessions.insert(currentSession!, at: 0)
        } catch {
            errorMessage = "开始学习会话失败"
        }
    }

    func endCurrentSession() async {
        guard let session = currentSession else { return }
        do {
            _ = try await LearningSessionService.shared.end(id: session.id)
            currentSession = nil
        } catch {
            errorMessage = "结束学习会话失败"
        }
    }
}
