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

        async let s = try? ActivityService.shared.summary()
        async let f = try? FocusItemService.shared.list()
        async let h = try? ActivityService.shared.heatmap()
        async let st = try? ActivityService.shared.streak()
        async let t = try? ActivityService.shared.trend()
        async let r = try? ActivityService.shared.recommendations()

        let (summaryResult, focusResult, heatmapResult, streakResult, trendResult, recResult) = await (s, f, h, st, t, r)

        summary = summaryResult
        focusItems = focusResult ?? []
        heatmap = heatmapResult ?? [:]
        streak = streakResult
        trends = trendResult ?? []
        recommendations = recResult ?? []

        if summary == nil {
            errorMessage = "加载分析数据失败，请下拉刷新重试"
        }

        isLoading = false
    }

    func refresh() async {
        errorMessage = nil

        async let s = try? ActivityService.shared.summary()
        async let f = try? FocusItemService.shared.list()
        async let h = try? ActivityService.shared.heatmap()
        async let st = try? ActivityService.shared.streak()
        async let t = try? ActivityService.shared.trend()
        async let r = try? ActivityService.shared.recommendations()

        let (summaryResult, focusResult, heatmapResult, streakResult, trendResult, recResult) = await (s, f, h, st, t, r)

        summary = summaryResult
        focusItems = focusResult ?? []
        heatmap = heatmapResult ?? [:]
        streak = streakResult
        trends = trendResult ?? []
        recommendations = recResult ?? []
    }
}
