#include "backgroundextractor_aggressive.h"
#include "../io/logger.h"

// Include the template implementation
#include "backgroundextractor_aggressive.tpp"

cv::Mat BackgroundExtractorAggressive::makeMoreAggressive(const cv::Mat &image)
{
    // Convert to float for processing
    cv::Mat floatImage;
    image.convertTo(floatImage, CV_32F);

    // Calculate original mean and standard deviation
    cv::Scalar originalMean, originalStdDev;
    cv::meanStdDev(floatImage, originalMean, originalStdDev);

    // Apply more aggressive background darkening
    // Reduce the mean by a factor to darken the background
    float darkeningFactor = 0.5f; // More aggressive darkening (was 0.7f)
    cv::Mat result = floatImage * darkeningFactor;

    // Ensure no negative values
    cv::threshold(result, result, 0, 0, cv::THRESH_TOZERO);

    // Apply a gamma correction to enhance contrast
    double min, max;
    float contrastFactor = 0.6f; // More aggressive contrast enhancement (was 0.8f)
    cv::minMaxLoc(result, &min, &max);
    if (max > 0)
    {
        // Apply a power function to enhance contrast
        cv::pow(result / max, contrastFactor, result);
        result *= max;
    }

    // Convert back to original type
    cv::Mat output;
    if (image.type() == CV_8U || image.type() == CV_8UC3)
    {
        result.convertTo(output, image.type());
    }
    else if (image.type() == CV_16U || image.type() == CV_16UC3)
    {
        result.convertTo(output, image.type());
    }
    else
    {
        output = result;
    }

    LOG_INFO("Applied aggressive background processing with darkeningFactor=" +
             std::to_string(darkeningFactor) + ", contrastFactor=" +
             std::to_string(contrastFactor));
    return output;
}
