#ifndef FLASH_DETECTOR_H
#define FLASH_DETECTOR_H

#include <ros/ros.h>
#include <image_transport/image_transport.h>
#include <sensor_msgs/Image.h>
#include <sensor_msgs/CameraInfo.h>
#include <std_msgs/Bool.h>
#include <std_msgs/Float32MultiArray.h>
#include <dynamic_reconfigure/server.h>
#include <opencv4/opencv2/opencv.hpp>
#include <vector>
#include <cmath>

#include <flash_detector/FlashDetectorConfig.h>

namespace flash_detector
{

struct DetectionResult
{
    bool detected;
    int cx, cy;
    double area;
    double sight_x, sight_y;
    cv::Mat mask;
    cv::Mat result_image;
    std::vector<std::pair<int, int>> centers;
};

class FlashDetector
{
public:
    FlashDetector();
    ~FlashDetector();

    void run();

private:
    // Callbacks
    void imageCallback(const sensor_msgs::Image::ConstPtr& msg);
    void cameraInfoCallback(const sensor_msgs::CameraInfo::ConstPtr& msg);
    void dynamicReconfigureCallback(flash_detector::FlashDetectorConfig &config, uint32_t level);

    // Core detection
    DetectionResult detectFlash(const cv::Mat& image);

    // Helpers
    void updateKernel();
    void publishResults(const cv::Mat& original_image, const DetectionResult& result, const std::string& frame_id);

    // ROS handles
    ros::NodeHandle nh_;
    ros::NodeHandle nh_private_;
    image_transport::ImageTransport it_;
    image_transport::Subscriber image_sub_;
    ros::Subscriber camera_info_sub_;

    ros::Publisher flash_pub_;
    ros::Publisher detection_pub_;
    image_transport::Publisher image_pub_;
    image_transport::Publisher mask_pub_;

    // Dynamic reconfigure
    boost::shared_ptr<dynamic_reconfigure::Server<flash_detector::FlashDetectorConfig>> server_;

    // Parameters
    std::string camera_topic_;
    std::string camera_info_topic_;
    bool debug_mode_;

    // HSV thresholds
    cv::Scalar hsv_lower_;
    cv::Scalar hsv_upper_;

    // Morphological operations
    int kernel_size_;
    int min_area_;
    cv::Mat kernel_;

    // Camera intrinsics
    double fx_, fy_, cx_, cy_;
    bool camera_info_received_;

    // Statistics
    int frame_count_;
    int detection_count_;
};

} // namespace flash_detector

#endif // FLASH_DETECTOR_H
