import Combine
import Foundation

@MainActor
class ActivityViewModel: ObservableObject {
    @Published var summary: ActivitySummary?
    @Published var focusItems: [FocusItem] = []
    @Published var heatmap: [String: Int] = [:]
    @Published var streak: ActivityStreak?
    @Published var trends: [ActivityTrend] = []
    @Published var recommendations: [ActivityRecommendation] = []
    @Published var isLoading = false
    @Published var errorMessage: String?

    func loadAll() async {
        isLoading = true
        errorMessage = nil
        do {
            async let s = ActivityService.shared.summary()
            async let f = FocusItemService.shared.list()
            async let h = ActivityService.shared.heatmap()
            async let st = ActivityService.shared.streak()
            async let t = ActivityService.shared.trend()
            async let r = ActivityService.shared.recommendations()
            let (summaryResult, focusResult, heatmapResult, streakResult, trendResult, recResult) = try await (s, f, h, st, t, r)
            summary = summaryResult; focusItems = focusResult; heatmap = heatmapResult
            streak = streakResult; trends = trendResult; recommendations = recResult
        } catch {
            if summary == nil { errorMessage = "加载分析数据失败" }
        }
        isLoading = false
    }

    func refresh() async {
        do {
            async let s = ActivityService.shared.summary()
            async let f = FocusItemService.shared.list()
            async let h = ActivityService.shared.heatmap()
            async let st = ActivityService.shared.streak()
            async let t = ActivityService.shared.trend()
            async let r = ActivityService.shared.recommendations()
            let (summaryResult, focusResult, heatmapResult, streakResult, trendResult, recResult) = try await (s, f, h, st, t, r)
            summary = summaryResult; focusItems = focusResult; heatmap = heatmapResult
            streak = streakResult; trends = trendResult; recommendations = recResult
        } catch {}
    }
}
