package com.hotwj.platform.system.maintenance.config;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.io.File;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

/**
 * 媒体资源元数据修复配置
 */
@Data
@Component
@ConfigurationProperties(prefix = "maintenance.media-resource-repair")
public class MediaResourceMetadataRepairProperties {

    /**
     * 任务缓存key前缀
     */
    private String taskKeyPrefix = "maintenance:media-resource-repair:";

    /**
     * 临时目录根路径
     */
    private String workDir = System.getProperty("java.io.tmpdir") + File.separator + "media-resource-repair";

    /**
     * ffprobe 命令
     */
    private String ffprobeCommand = "ffprobe";

    /**
     * ffmpeg 命令
     */
    private String ffmpegCommand = "ffmpeg";

    /**
     * 任务状态保留小时数
     */
    private Integer taskExpireHours = 24;

    /**
     * 默认单次处理上限
     */
    private Integer defaultLimit = 200;

    /**
     * 最大单次处理上限
     */
    private Integer maxLimit = 500;

    /**
     * 默认批处理条数
     */
    private Integer defaultBatchSize = 20;

    /**
     * 最大批处理条数
     */
    private Integer maxBatchSize = 50;

    /**
     * 连接超时秒数
     */
    private Integer connectTimeoutSeconds = 10;

    /**
     * 读取超时秒数
     */
    private Integer readTimeoutSeconds = 60;

    /**
     * 单文件最大大小
     */
    private Long maxFileSizeBytes = 524288000L;

    /**
     * HLS 最大分片数
     */
    private Integer maxHlsSegments = 500;

    /**
     * HLS 最大总下载大小
     */
    private Long maxHlsTotalSizeBytes = 1073741824L;

    /**
     * 采样错误条数上限
     */
    private Integer maxErrorSamples = 20;

    /**
     * 播放列表最大大小
     */
    private Long maxPlaylistSizeBytes = 2097152L;

    /**
     * 允许的域名白名单，留空则不限制
     */
    private List<String> allowedHosts = new ArrayList<>();

    public Duration taskExpireDuration() {
        return Duration.ofHours(taskExpireHours == null ? 24L : taskExpireHours.longValue());
    }

    public boolean isHostAllowed(String host) {
        if (host == null || host.isBlank()) {
            return false;
        }
        if (allowedHosts == null || allowedHosts.isEmpty()) {
            return true;
        }
        String normalizedHost = host.toLowerCase(Locale.ROOT);
        for (String allowedHost : allowedHosts) {
            if (allowedHost == null || allowedHost.isBlank()) {
                continue;
            }
            String normalizedAllowed = allowedHost.toLowerCase(Locale.ROOT).trim();
            if (normalizedHost.equals(normalizedAllowed) || normalizedHost.endsWith("." + normalizedAllowed)) {
                return true;
            }
        }
        return false;
    }
}
