package gc.mda.kcg.collector;

import lombok.Getter;
import org.springframework.stereotype.Component;

import java.time.Instant;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class CollectorStatusTracker {

    @Getter
    public static class CollectorStatus {
        private final String name;
        private volatile String region;
        private volatile Instant lastSuccess;
        private volatile Instant lastFailure;
        private volatile int lastCount;
        private volatile String lastError;
        private volatile long totalSuccess;
        private volatile long totalFailure;
        private volatile long totalItems;

        public CollectorStatus(String name) {
            this.name = name;
        }

        void recordSuccess(String region, int count) {
            this.region = region;
            this.lastSuccess = Instant.now();
            this.lastCount = count;
            this.lastError = null;
            this.totalSuccess++;
            this.totalItems += count;
        }

        void recordFailure(String region, String error) {
            this.region = region;
            this.lastFailure = Instant.now();
            this.lastError = error;
            this.totalFailure++;
        }
    }

    private final ConcurrentHashMap<String, CollectorStatus> statuses = new ConcurrentHashMap<>();

    public void recordSuccess(String name, String region, int count) {
        statuses.computeIfAbsent(name, CollectorStatus::new).recordSuccess(region, count);
    }

    public void recordFailure(String name, String region, String error) {
        statuses.computeIfAbsent(name, CollectorStatus::new).recordFailure(region, error);
    }

    public List<CollectorStatus> getAll() {
        return statuses.values().stream()
                .sorted(Comparator.comparing(CollectorStatus::getName))
                .toList();
    }
}
