//
//  AppUpdateManager.swift
//  punchnet
//
//  Created by 安礼成 on 2026/3/23.
//
import SwiftUI
import Observation

@Observable
class AppUpdateManager {
    static let shared = AppUpdateManager()
    
    var updateInfo: AppUpgradeInfo?
    var isChecking = false
    var showUpdateOverlay = false // 用于启动时的全局遮罩
    
    @MainActor
    func checkUpdate(isManual: Bool = false) async -> Bool {
        isChecking = true
        defer {
            isChecking = false
        }
        
        do {
            let updateInfo = try await AppService.appCheckUpdate()
            // 核心逻辑：比对本地版本
            let currentVersion = SystemConfig.version_name
            let needsUpdate = VersionComparator.isVersion(currentVersion, olderThan: updateInfo.latestVersion)
            if needsUpdate {
                self.updateInfo = updateInfo
                // 如果是启动自动检查，则显示遮罩
                if !isManual {
                    self.showUpdateOverlay = true
                }
                return true
            }
        } catch {
            print("Update check failed: \(error)")
        }
        
        return false
    }
}

private struct VersionComparator {
    
    /// 比较版本号：如果 current < latest 返回 true (需要更新)
    static func isVersion(_ current: String, olderThan latest: String) -> Bool {
        let currentComponents = current.split(separator: ".").map { Int($0) ?? 0 }
        let latestComponents = latest.split(separator: ".").map { Int($0) ?? 0 }
        
        let maxLength = max(currentComponents.count, latestComponents.count)
        for i in 0..<maxLength {
            let currentPart = i < currentComponents.count ? currentComponents[i] : 0
            let latestPart = i < latestComponents.count ? latestComponents[i] : 0
            
            if currentPart < latestPart {
                return true
            }
            
            if currentPart > latestPart {
                return false
            }
        }
        return false
    }
}
