//
//  XHookSettingsManager.m
//  配置管理器 - 实现
//

#import "XHookSettingsManager.h"

@implementation XHookSettingsManager

+ (instancetype)sharedManager {
    static XHookSettingsManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[XHookSettingsManager alloc] init];
    });
    return manager;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        [self resetToDefaults];
    }
    return self;
}

- (void)resetToDefaults {
    _isLoaded = NO;
    
    // 设备信息默认值
    _idfa = nil;
    _idfv = nil;
    _deviceName = nil;
    _osVersion = nil;
    _productStr = @"iPhone14,2";
    _hwModel = nil;
    _trackingStatus = 3; // 默认已授权
    
    // 系统信息默认值
    _physicalMemory = 0;
    _cpuCore = 0;
    _systemUptimeOffset = -1.0;
    _kernBootTimeOffset = 0;
    
    // 电池信息默认值
    _batteryState = UIDeviceBatteryStateUnknown;
    _batteryLevel = -1.0f;
    
    // 屏幕信息默认值
    _screenBrightness = -1.0;
    _screenScale = -1.0;
    _screenBounds = nil;
    _safeAreaInsets = nil;
    
    // 磁盘信息默认值
    _diskSize = 0;
    _diskFreeSize = 0;
    
    // 音频默认值
    _outputVolume = -1.0f;
    
    // 网络信息默认值
    _userAgent = nil;
    _networkInterfacesInfo = nil;
    _simInfo = nil;
    
    // 本地化默认值
    _locale = nil;
    _timeZone = nil;
    
    // 应用列表默认值
    _apps = nil;
}

#pragma mark - 解析辅助方法

- (NSString *)parseString:(id)value defaultValue:(NSString *)defaultValue {
    if ([value isKindOfClass:[NSString class]]) {
        return value;
    }
    return defaultValue;
}

- (NSInteger)parseInteger:(id)value defaultValue:(NSInteger)defaultValue {
    if ([value isKindOfClass:[NSString class]]) {
        return [value integerValue];
    } else if ([value isKindOfClass:[NSNumber class]]) {
        return [value integerValue];
    }
    return defaultValue;
}

- (float)parseFloat:(id)value defaultValue:(float)defaultValue {
    if ([value isKindOfClass:[NSString class]]) {
        return [value floatValue];
    } else if ([value isKindOfClass:[NSNumber class]]) {
        return [value floatValue];
    }
    return defaultValue;
}

- (double)parseDouble:(id)value defaultValue:(double)defaultValue {
    if ([value isKindOfClass:[NSString class]]) {
        return [value doubleValue];
    } else if ([value isKindOfClass:[NSNumber class]]) {
        return [value doubleValue];
    }
    return defaultValue;
}

- (unsigned long long)parseULL:(id)value defaultValue:(unsigned long long)defaultValue {
    if ([value isKindOfClass:[NSString class]]) {
        return [value longLongValue];
    } else if ([value isKindOfClass:[NSNumber class]]) {
        return [value unsignedLongLongValue];
    }
    return defaultValue;
}

- (NSUUID *)parseUUID:(id)value {
    if ([value isKindOfClass:[NSString class]]) {
        return [[NSUUID alloc] initWithUUIDString:value];
    }
    return nil;
}

- (NSDictionary *)parseDictionary:(id)value {
    if ([value isKindOfClass:[NSDictionary class]]) {
        return value;
    }
    return nil;
}

- (NSArray *)parseArray:(id)value {
    if ([value isKindOfClass:[NSArray class]]) {
        return value;
    }
    return nil;
}

#pragma mark - 加载配置

- (BOOL)loadSettingsFromPath:(NSString *)path {
    @try {
        NSFileManager *fileManager = [NSFileManager defaultManager];
        if (![fileManager fileExistsAtPath:path]) {
            return NO;
        }
        
        NSData *jsonData = [NSData dataWithContentsOfFile:path];
        if (!jsonData) {
            return NO;
        }
        
        NSError *error = nil;
        NSDictionary *settings = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];
        if (error || !settings || ![settings isKindOfClass:[NSDictionary class]]) {
            NSLog(@"XHookSettingsManager: Error parsing JSON: %@", error);
            return NO;
        }
        
        // 解析并初始化所有属性
        [self parseSettings:settings];
        
        _isLoaded = YES;
        return YES;
    } @catch (NSException *exception) {
        NSLog(@"XHookSettingsManager: Exception loading settings: %@", exception);
        return NO;
    }
}

- (void)parseSettings:(NSDictionary *)settings {
    // 设备信息
    _idfa = [self parseUUID:settings[@"idfa"]];
    _idfv = [self parseUUID:settings[@"idfv"]];
    _deviceName = [self parseString:settings[@"deviceName"] defaultValue:nil];
    _osVersion = [self parseString:settings[@"osVersion"] defaultValue:nil];
    _productStr = [self parseString:settings[@"productStr"] defaultValue:@"iPhone14,2"];
    _hwModel = [self parseString:settings[@"hwModel"] defaultValue:nil];
    _trackingStatus = [self parseInteger:settings[@"trackingStatus"] defaultValue:3];
    
    // 系统信息
    _physicalMemory = [self parseULL:settings[@"physicalMemory"] defaultValue:0];
    _cpuCore = [self parseInteger:settings[@"cpuCore"] defaultValue:0];
    _systemUptimeOffset = [self parseDouble:settings[@"systemUptime"] defaultValue:-1.0];
    _kernBootTimeOffset = [self parseInteger:settings[@"kernBootTime"] defaultValue:0];
    
    // 电池信息
    NSInteger batteryStateVal = [self parseInteger:settings[@"batteryState"] defaultValue:-1];
    _batteryState = (batteryStateVal >= 0) ? (UIDeviceBatteryState)batteryStateVal : UIDeviceBatteryStateUnknown;
    _batteryLevel = [self parseFloat:settings[@"batteryLevel"] defaultValue:-1.0f];
    
    // 屏幕信息
    _screenBrightness = [self parseDouble:settings[@"screenBrightness"] defaultValue:-1.0];
    _screenScale = [self parseDouble:settings[@"screenScale"] defaultValue:-1.0];
    _screenBounds = [self parseDictionary:settings[@"screenBounds"]];
    _safeAreaInsets = [self parseDictionary:settings[@"safeAreaInsets"]];
    
    // 磁盘信息
    _diskSize = [self parseULL:settings[@"diskSize"] defaultValue:0];
    _diskFreeSize = [self parseULL:settings[@"diskFreeSize"] defaultValue:0];
    
    // 音频
    _outputVolume = [self parseFloat:settings[@"outputVolume"] defaultValue:-1.0f];
    
    // 网络信息
    _userAgent = [self parseString:settings[@"userAgent"] defaultValue:nil];
    _networkInterfacesInfo = [self parseDictionary:settings[@"networkInterfacesInfo"]];
    _simInfo = [self parseDictionary:settings[@"simInfo"]];
    
    // 本地化
    _locale = [self parseString:settings[@"locale"] defaultValue:nil];
    _timeZone = [self parseString:settings[@"timeZone"] defaultValue:nil];
    
    // 应用列表
    _apps = [self parseArray:settings[@"apps"]];
}

- (void)cleanup {
    [self resetToDefaults];
}

#pragma mark - 应用检查

- (BOOL)shouldHookApp:(NSString *)bundleIdentifier {
    if (!bundleIdentifier || !_apps) return NO;
    return [_apps containsObject:bundleIdentifier];
}

@end

