//
//  BCALicenseManager.m
//  ChatAgentApp
//
//  Created by caoshiqian on 2025/8/5.
//

#import "BCALicenseManager.h"

@interface BCALicenseManager ()

@property (nonatomic, copy) NSString *licenseFilePath;
@property (nonatomic, strong) NSMutableDictionary<NSString *, NSString *> *licenseDict;

@end

@implementation BCALicenseManager

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

- (instancetype)init {
    if (self = [super init]) {
        _licenseFilePath = [[NSBundle mainBundle] pathForResource:@"license" ofType:@"txt"];
        [self loadLicenses];
    }
    return self;
}

+ (void)setLicenseKey:(NSString *)key forAppID:(NSString *)appId {
    [[[self class] sharedManager] setLicenseKey:key forAppID:appId];
}

+ (NSString *)licenseKeyForAppID:(NSString *)appId {
    return [[[self class] sharedManager] licenseKeyForAppID:appId];
}

#pragma mark - privates

- (void)setLicenseKey:(NSString *)key forAppID:(NSString *)appId {
    if (key.length > 0 && appId.length > 0) {
        [self.licenseDict setObject:key forKey:appId];
    }
}

- (NSString *)licenseKeyForAppID:(NSString *)appId {
    if (appId.length == 0) {
        return @"";
    }
    NSString *key = [self.licenseDict objectForKey:appId];
    return key;
}

- (void)loadLicenses {
    self.licenseDict = [self parseLicenseFileAtPath:self.licenseFilePath];
}

- (NSMutableDictionary<NSString *, NSString *> *)parseLicenseFileAtPath:(NSString *)filePath {
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    
    NSError *error;
    NSString *fileContents = [NSString stringWithContentsOfFile:filePath
                                                      encoding:NSUTF8StringEncoding
                                                         error:&error];
    
    if (error) {
        NSLog(@"Error reading file: %@", error.localizedDescription);
        return nil;
    }
    
    NSArray *lines = [fileContents componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
    
    for (NSString *line in lines) {
        NSString *trimmedLine = [line stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
        
        // 跳过空行和注释行
        if (trimmedLine.length == 0 ||
            [trimmedLine hasPrefix:@"#"] ||
            [trimmedLine hasPrefix:@"//"] ||
            [trimmedLine hasPrefix:@"/*"] ||
            [trimmedLine hasPrefix:@"*"] ||
            [trimmedLine hasPrefix:@"--"]) {
            continue;
        }
        
        // 按空格分割每行
        NSArray *components = [trimmedLine componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
        components = [components filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"SELF != ''"]];
        
        if (components.count >= 2) {
            NSString *appId = components[0];
            NSString *licenseKey = components[1];
            
            [dict setObject:licenseKey forKey:appId];
        } else {
            NSLog(@"empty license for appid: %@", line);
        }
    }
    
    return [dict mutableCopy];
}

@end
