import Foundation
import Combine

@MainActor
class ProfileViewModel: ObservableObject {
    @Published var userProfile: UserProfileResponse?
    @Published var preferences: UserPreferences?
    @Published var profileData: UserProfileData?
    @Published var summary: ActivitySummary?
    @Published var kbCount = 0
    @Published var itemCount = 0
    @Published var cardCount = 0
    @Published var usedBytes = 0
    @Published var totalBytes = 1073741824
    @Published var isLoading = false
    @Published var errorMessage: String?

    var formattedStorage: String {
        if usedBytes < 1024 * 1024 { return "\(usedBytes / 1024) KB / \(totalBytes / 1024 / 1024 / 1024) GB" }
        return String(format: "%.0f MB / %d GB", Double(usedBytes) / 1024 / 1024, totalBytes / 1024 / 1024 / 1024)
    }

    func loadAll() async {
        isLoading = true; errorMessage = nil
        await loadProfile()
        isLoading = false
        Task { await loadActivitySummary() }
        Task { await loadStats() }
    }

    func loadProfile() async {
        do { let p = try await UserService.shared.myProfile(); userProfile = p; preferences = p.preferences; profileData = p.profile } catch { if userProfile == nil { errorMessage = "加载用户信息失败" } }
    }
    func updatePreferences(_ dto: UpdatePreferencesRequest) async { do { preferences = try await UserService.shared.updatePreferences(dto) } catch { errorMessage = "保存设置失败" } }
    func updateProfileDetail(_ dto: UpdateProfileDataRequest) async { do { profileData = try await UserService.shared.updateProfileDetail(dto) } catch { errorMessage = "保存学习档案失败" } }
    private func loadActivitySummary() async { do { summary = try await ActivityService.shared.summary() } catch {} }

    private func loadStats() async {
        async let a: AssetsResponse? = try? UserService.shared.fetchAssets()
        async let s: StorageResponse? = try? UserService.shared.fetchStorage()
        if let assets = await a { kbCount = assets.knowledgeBaseCount; itemCount = assets.knowledgeItemCount; cardCount = assets.reviewCardCount }
        if let storage = await s { usedBytes = storage.usedBytes; totalBytes = storage.totalBytes }
    }
}

// MARK: - Raw API models

struct AssetsResponse: Codable {
    let knowledgeBaseCount: Int
    let knowledgeItemCount: Int
    let reviewCardCount: Int
}

struct StorageResponse: Codable {
    let usedBytes: Int
    let totalBytes: Int
    let fileCount: Int
}
