//
//  YHKingfisherUtils.swift
//  galaxy
//
//  Created by alexzzw on 2025/10/11.
//  Copyright © 2025 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit
import Kingfisher

class YHKingfisherUtils: NSObject {
    
    static func fetchImage(with urlString: String?,
                                  completion: @escaping (UIImage?) -> Void) {
        guard let urlString = urlString, let url = URL(string: urlString) else {
            completion(nil)
            return
        }
        
        let key = url.absoluteString
        
        // 检查缓存
        if ImageCache.default.isCached(forKey: key) {
            ImageCache.default.retrieveImage(forKey: key) { result in
                switch result {
                case .success(let cacheResult):
                    if let image = cacheResult.image {
                        // 缓存命中且图片有效
                        completion(image)
                    } else {
                        // 缓存命中但图片为空，降级到下载
                        downloadAndCacheImage(url: url, key: key, completion: completion)
                    }
                case .failure:
                    // 缓存读取失败，降级到下载
                    downloadAndCacheImage(url: url, key: key, completion: completion)
                }
            }
        } else {
            // 缓存未命中，直接下载
            downloadAndCacheImage(url: url, key: key, completion: completion)
        }
    }

    // 辅助方法：下载并缓存图片
    private static func downloadAndCacheImage(url: URL,
                                             key: String,
                                             completion: @escaping (UIImage?) -> Void) {
        ImageDownloader.default.downloadImage(with: url, options: nil) { result in
            switch result {
            case .success(let imageLoadingResult):
                let image = imageLoadingResult.image
                ImageCache.default.store(image, forKey: key)
                completion(image)
            case .failure:
                completion(nil)
            }
        }
    }
    
    @available(iOS 13.0, *)
    static func fetchImage(with urlString: String?) async -> UIImage? {
        guard let urlString = urlString, let url = URL(string: urlString) else {
            return nil
        }
        
        let key = url.absoluteString
        
        return await withCheckedContinuation { continuation in
            if ImageCache.default.isCached(forKey: key) {
                ImageCache.default.retrieveImage(forKey: key) { result in
                    switch result {
                    case .success(let cacheResult):
                        if let image = cacheResult.image {
                            // 缓存命中且成功获取
                            continuation.resume(returning: image)
                        } else {
                            // 缓存命中但图片为空，降级到下载
                            self.downloadAndCacheImage(url: url, key: key, continuation: continuation)
                        }
                    case .failure:
                        // 缓存读取失败，降级到下载
                        self.downloadAndCacheImage(url: url, key: key, continuation: continuation)
                    }
                }
            } else {
                // 缓存未命中，直接下载
                downloadAndCacheImage(url: url, key: key, continuation: continuation)
            }
        }
    }

    // 辅助方法：下载并缓存图片
    private static func downloadAndCacheImage(
        url: URL,
        key: String,
        continuation: CheckedContinuation<UIImage?, Never>
    ) {
        ImageDownloader.default.downloadImage(with: url, options: nil) { result in
            switch result {
            case .success(let imageLoadingResult):
                let image = imageLoadingResult.image
                ImageCache.default.store(image, forKey: key)
                continuation.resume(returning: image)
            case .failure:
                continuation.resume(returning: nil)
            }
        }
    }

}
