using OpenCvSharp;
using SHH.CameraSdk;

public class ImageEnhanceCluster : BaseFrameProcessor<EnhanceWorker>
{
    public ImageEnhanceCluster(int count, ProcessingConfigManager configManager)
        : base(count, "EnhanceCluster", configManager)
    {
    }

    protected override EnhanceWorker CreateWorker(int id) => new EnhanceWorker(this, _configManager);
}

public class EnhanceWorker : BaseWorker
{
    private readonly ImageEnhanceCluster _parent;
    private readonly ProcessingConfigManager _configManager;

    public EnhanceWorker(ImageEnhanceCluster parent, ProcessingConfigManager configManager)
    {
        _parent = parent;
        _configManager = configManager;
    }

    protected override void PerformAction(long deviceId, SmartFrame frame, FrameDecision decision)
    {
        // 1. 获取配置
        var options = _configManager.GetOptions(deviceId);

        // 2. 检查开关：如果没开启增强，直接跳过
        if (!options.EnableBrightness) return;

        // 3. 确定操作对象
        // 策略：如果上一站生成了 TargetMat (缩放图)，我们处理缩放图；
        // 如果没有 (例如缩放被禁用)，我们是否要处理原图？
        // 通常 UI 预览场景下，如果不缩放，直接处理 4K 原图会非常卡。
        // 建议：仅当 TargetMat 存在时处理，或者强制 clone 一份原图作为 TargetMat

        Mat srcMat;
        if (frame.TargetMat != null)
            srcMat = frame.TargetMat;
        else
            srcMat = frame.InternalMat;

        // 4. 执行增亮
        Mat brightMat = new Mat();
        // Alpha=1.0, Beta=配置值
        srcMat.ConvertTo(brightMat, -1, 1.0, options.Brightness);

        // 5. 挂载结果
        // 这会自动释放上一站生成的旧 TargetMat (如果存在)
        frame.AttachTarget(brightMat, frame.ScaleType);
    }

    protected override void NotifyFinished(long did, SmartFrame frame, FrameDecision dec)
    {
        _parent.PassToNext(did, frame, dec);
    }
}