using Ayay.SerilogLogs;
using Serilog;

namespace SHH.CameraSdk;

/// <summary>
/// [配置中心] 预处理参数管理器
/// 职责：提供线程安全的配置读写接口，连接 Web API 与 底层 Worker
/// </summary>
public class ProcessingConfigManager
{
    private ILogger _sysLog = Log.ForContext("SourceContext", LogModules.Core);

    // 内存字典：Key=设备ID, Value=配置对象
    private readonly ConcurrentDictionary<long, ProcessingOptions> _configs = new();

    /// <summary>
    /// 获取指定设备的配置（如果不存在则返回默认值）
    /// </summary>
    /// <param name="deviceId">设备ID</param>
    /// <returns>配置对象（非空）</returns>
    public ProcessingOptions GetOptions(long deviceId)
    {
        // GetOrAdd 保证了永远能拿回一个有效的配置，防止 Worker 报空指针
        return _configs.GetOrAdd(deviceId, _ => ProcessingOptions.Default);
    }

    /// <summary>
    /// 更新指定设备的配置（实时生效）
    /// </summary>
    public void UpdateOptions(long deviceId, ProcessingOptions newOptions)
    {
        if (newOptions == null) return;

        // 直接覆盖旧配置，由于是引用替换，原子性较高
        _configs.AddOrUpdate(deviceId, newOptions, (key, old) => newOptions);

        _sysLog.Information($"[ConfigManager] 设备 {deviceId} 预处理参数已更新: " +
                          $"Expand={newOptions.EnableExpand} Shrink:{newOptions.EnableShrink} 分辨率:({newOptions.TargetWidth}x{newOptions.TargetHeight}), " +
                          $"EnableBrightness}}={newOptions.EnableBrightness}");
    }
}