package com.sino.mci.policy.engine;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Slf4j
@Data
@NoArgsConstructor
@AllArgsConstructor
public class PolicyGroupConfig {

    private List<Policy> policies = new ArrayList<>();

    public static PolicyGroupConfig parseJson(String json) {
        if (!StringUtils.hasText(json)) {
            return new PolicyGroupConfig();
        }
        ObjectMapper mapper = new ObjectMapper();
        try {
            List<Policy> list = mapper.readValue(json, new TypeReference<List<Policy>>() {
            });
            return new PolicyGroupConfig(list != null ? list : new ArrayList<>());
        } catch (JsonProcessingException e) {
            log.warn("解析策略组配置失败: {}", json, e);
            return new PolicyGroupConfig();
        }
    }

    public Optional<RetryConfig> getRetryConfig() {
        return policies.stream()
                .filter(p -> p.getType() == PolicyType.RETRY)
                .findFirst()
                .map(p -> new RetryConfig(
                        p.getMaxRetry() == null ? 0 : p.getMaxRetry(),
                        p.getIntervals()));
    }
}
