//  ImageCacheHelper.mm
#import <CommonCrypto/CommonDigest.h>
#import "ImageCacheHelper.h"
#import "NetworkManager.h"
#import "APIClient.h"

@implementation ImageCacheHelper

#pragma mark - Public Methods

+ (void)loadImageWithURL:(NSURL *)url
             completion:(void (^)(UIImage *image))completion {
    
    if (!url) {
        if (completion) completion([self placeholderImage]);
        return;
    }
    
    NSString *filePath = [self cachedFilePathForURL:url];
    NSFileManager *fm = [NSFileManager defaultManager];
    
    // 1️⃣ Check cache
    if ([fm fileExistsAtPath:filePath]) {
        UIImage *cachedImage = [UIImage imageWithContentsOfFile:filePath];
        if (cachedImage) {
            if (completion) completion(cachedImage);
            return;
        }
    }
    
    // 2️⃣ Not cached → check network
    if (![self canDownloadImages]) {
        // No internet → return placeholder
        if (completion) completion([self placeholderImage]);
        return;
    }
    
    // 3️⃣ Download
    [APIClient downloadAndCacheImage:url completion:^(BOOL success, NSString *filePath) {
        UIImage *img = nil;
        if (success && filePath) {
            img = [UIImage imageWithContentsOfFile:filePath];
        }
        if (!img) img = [self placeholderImage];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            if (completion) completion(img);
        });
    }];
}

+ (UIImage *)placeholderImage {
    static UIImage *image = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSBundle *bundle = [NSBundle bundleForClass:self];
        image = [UIImage imageNamed:@"img_placeholder"
                           inBundle:bundle
      compatibleWithTraitCollection:nil];
    });
    return image;
}

#pragma mark - Cache File Helper

+ (NSString *)cachedFilePathForURL:(NSURL *)url {
    if (!url) return nil;
    
    NSString *cacheDir = [self offlineImageCacheDirectory]; // You already have this
    NSFileManager *fm = [NSFileManager defaultManager];
    if (![fm fileExistsAtPath:cacheDir]) {
        NSError *dirError = nil;
        [fm createDirectoryAtPath:cacheDir
      withIntermediateDirectories:YES
                       attributes:nil
                            error:&dirError];
        if (dirError) {
            NSLog(@"❌ Failed to create cache directory: %@", dirError);
        }
    }
    
    NSString *cleanName = url.lastPathComponent.stringByDeletingPathExtension;
    NSString *ext = url.pathExtension;
    NSString *fileName = [NSString stringWithFormat:@"%@_%@.%@",
                          cleanName,
                          [self md5Hash:url.absoluteString],
                          ext];
    
    return [cacheDir stringByAppendingPathComponent:fileName];
}

#pragma mark - MD5 Hash Helper

+ (NSString *)md5Hash:(NSString *)input {
    if (!input) return @"";
    const char *cStr = [input UTF8String];
    unsigned char digest[CC_MD5_DIGEST_LENGTH];
    CC_MD5(cStr, (CC_LONG)strlen(cStr), digest);
    NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
        [output appendFormat:@"%02x", digest[i]];
    return output;
}

#pragma mark - Offline Cache Directory

+ (NSString *)offlineImageCacheDirectory {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *cacheDir = [[paths firstObject] stringByAppendingPathComponent:@"OfflineImages"];
    return cacheDir;
}

+ (BOOL)canDownloadImages {
    return [NetworkManager.sharedManager isConnected];
}

@end
