package tech.easyflow.agent.config;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.util.unit.DataSize;

import java.time.Duration;

/**
 * Agent 受控 Shell 的统一平台限制。
 */
@ConfigurationProperties(prefix = "easyflow.agent.shell")
public class AgentShellProperties implements InitializingBean {

    private Duration defaultTimeout = Duration.ofSeconds(60);
    private Duration maxTimeout = Duration.ofSeconds(300);
    private int maxCommandLength = 4_096;
    private DataSize maxOutputSize = DataSize.ofMegabytes(1);
    private int maxConcurrentPerInstance = 2;

    /** @return 默认超时 */
    public Duration getDefaultTimeout() { return defaultTimeout; }
    /** @param defaultTimeout 默认超时 */
    public void setDefaultTimeout(Duration defaultTimeout) { this.defaultTimeout = defaultTimeout; }
    /** @return 最大超时 */
    public Duration getMaxTimeout() { return maxTimeout; }
    /** @param maxTimeout 最大超时 */
    public void setMaxTimeout(Duration maxTimeout) { this.maxTimeout = maxTimeout; }
    /** @return 命令最大字符数 */
    public int getMaxCommandLength() { return maxCommandLength; }
    /** @param maxCommandLength 命令最大字符数 */
    public void setMaxCommandLength(int maxCommandLength) { this.maxCommandLength = maxCommandLength; }
    /** @return 输出最大字节数 */
    public DataSize getMaxOutputSize() { return maxOutputSize; }
    /** @param maxOutputSize 输出最大字节数 */
    public void setMaxOutputSize(DataSize maxOutputSize) { this.maxOutputSize = maxOutputSize; }
    /** @return 单实例最大并发数 */
    public int getMaxConcurrentPerInstance() { return maxConcurrentPerInstance; }
    /** @param maxConcurrentPerInstance 单实例最大并发数 */
    public void setMaxConcurrentPerInstance(int maxConcurrentPerInstance) {
        this.maxConcurrentPerInstance = maxConcurrentPerInstance;
    }

    /**
     * 启动期校验 Shell 限制。
     */
    @Override
    public void afterPropertiesSet() {
        if (!positive(defaultTimeout) || !positive(maxTimeout)
                || maxTimeout.compareTo(defaultTimeout) < 0) {
            throw new IllegalStateException("Shell 最大超时必须大于等于正值默认超时");
        }
        if (maxCommandLength <= 0 || maxOutputSize == null || maxOutputSize.toBytes() <= 0
                || maxConcurrentPerInstance <= 0) {
            throw new IllegalStateException("Shell 命令长度、输出大小和并发数必须为正值");
        }
    }

    private boolean positive(Duration value) {
        return value != null && !value.isZero() && !value.isNegative();
    }
}
