package com.ruoyi.generator.service.front;

import java.util.Date;
import java.util.Locale;
import org.springframework.stereotype.Component;
import com.ruoyi.common.utils.StringUtils;

@Component
public class AiTaskRetryPolicy
{
    private static final long[] RETRY_DELAYS_MS = new long[] { 30_000L, 120_000L, 300_000L };

    public boolean canRetry(String errorMessage, int attempts, int maxAttempts)
    {
        if (attempts >= maxAttempts)
        {
            return false;
        }
        if (StringUtils.isEmpty(errorMessage))
        {
            return true;
        }
        String message = errorMessage.toLowerCase(Locale.ROOT);
        if (message.contains("配额") || message.contains("quota") || message.contains("无权限")
                || message.contains("permission") || message.contains("missing field")
                || message.contains("validation"))
        {
            return false;
        }
        return message.contains("timeout") || message.contains("timed out") || message.contains("429")
                || message.contains("too many requests") || message.contains("unavailable")
                || message.contains("502") || message.contains("503") || message.contains("504")
                || message.contains("5xx");
    }

    public Date nextRetryTime(int attempts, Date now)
    {
        long delay = RETRY_DELAYS_MS[Math.min(Math.max(attempts, 1), RETRY_DELAYS_MS.length) - 1];
        return new Date(now.getTime() + delay);
    }
}
