#import "TQPrewarmDedup.h"

@implementation TQPrewarmDedup {
    NSMutableDictionary<NSString *, NSNumber *> *_reached;
    BOOL _minimalDone;
    NSObject *_lock;
}

- (instancetype)init {
    if (self = [super init]) {
        _reached = [NSMutableDictionary dictionary];
        _minimalDone = NO;
        _lock = [[NSObject alloc] init];
    }
    return self;
}

- (BOOL)shouldRun:(TQPrewarmLevel)level bizType:(NSString *)bizType {
    @synchronized (_lock) {
        if (level == TQPrewarmLevelMinimal) {
            return !_minimalDone;
        }
        NSNumber *cur = _reached[bizType];
        if (cur == nil) {
            return YES;
        }
        return level > cur.integerValue;
    }
}

- (void)markDone:(TQPrewarmLevel)level bizType:(NSString *)bizType {
    @synchronized (_lock) {
        // 档位增量补做：任意档位 execute 都会先跑全局 DNS，故一律置 minimalDone
        _minimalDone = YES;
        if (level == TQPrewarmLevelMinimal) {
            return;
        }
        NSNumber *cur = _reached[bizType];
        if (cur == nil || level > cur.integerValue) {
            _reached[bizType] = @(level);
        }
    }
}

- (void)reset {
    @synchronized (_lock) {
        [_reached removeAllObjects];
        _minimalDone = NO;
    }
}

@end
