//
//  CustomJitsiLogger.m
//  AIIM
//
//  Created by qitewei on 2025/6/6.
//

#import "CustomJitsiLogger.h"

@implementation CustomJitsiLogger{
    BOOL _remoteReportingEnabled;
    BOOL _debugLoggingEnabled;
}

+ (instancetype)sharedHandler {
    static CustomJitsiLogger *sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[self alloc] init];
        sharedInstance.criticalErrors = [NSMutableArray array];
    });
    return sharedInstance;
}

#pragma mark - 配置方法

- (void)enableRemoteReporting:(BOOL)enabled {
    _remoteReportingEnabled = enabled;
}

- (void)enableDebugLogging:(BOOL)enabled {
    _debugLoggingEnabled = enabled;
}

#pragma mark - 日志处理方法

- (void)logVerbose:(NSString *)msg {
    if (_debugLoggingEnabled) {
        NSLog(@"[JitsiMeet][VERBOSE] %@", msg);
    }
}

- (void)logDebug:(NSString *)msg {
    if (_debugLoggingEnabled) {
        NSLog(@"[JitsiMeet][DEBUG] %@", msg);
    }
}

- (void)logInfo:(NSString *)msg {
    NSLog(@"[JitsiMeet][INFO] %@", msg);
}

- (void)logWarn:(NSString *)msg {
    NSLog(@"[JitsiMeet][WARN] %@", msg);
    [self checkPotentialIssues:msg];
}

- (void)logError:(NSString *)msg {
    NSLog(@"[JitsiMeet][ERROR] %@", msg);
    self.errorCount++;
    
    // 关键错误处理
    if ([self isCriticalError:msg]) {
        [self.criticalErrors addObject:msg];
        [self handleCriticalError:msg];
    }
    
    // 远程上报
    if (_remoteReportingEnabled) {
        [self reportErrorToAnalytics:msg];
    }
}

#pragma mark - 私有方法

- (BOOL)isCriticalError:(NSString *)error {
    NSArray *criticalKeywords = @[@"disconnect", @"timeout", @"failed", @"exception", @"error"];
    for (NSString *keyword in criticalKeywords) {
        if ([error.lowercaseString containsString:keyword]) {
            return YES;
        }
    }
    return NO;
}

- (void)handleCriticalError:(NSString *)error {
    dispatch_async(dispatch_get_main_queue(), ^{
        if ([error containsString:@"Websocket error"]) {
            !self.WebsocketErrorBlock ?:self.WebsocketErrorBlock();
        }
    });
}

- (void)reportErrorToAnalytics:(NSString *)error {
    // Firebase Crashlytics 上报
    NSError *reportError = [NSError errorWithDomain:@"JitsiMeetErrorDomain"
                                              code:-1
                                          userInfo:@{NSLocalizedDescriptionKey: error}];
    
}

- (void)checkPotentialIssues:(NSString *)warning {
    if ([warning containsString:@"bandwidth"]) {
        NSLog(@"[JitsiMeet] 检测到带宽问题警告");
    }
}

@end
