#define STB_IMAGE_IMPLEMENTATION
#define STB_IMAGE_WRITE_IMPLEMENTATION

#include <iostream>
#include <string>
#include "stb_image.h"
#include "stb_image_write.h"

int main()
{
    const char* input_filename = "input.jpg";
    const char* output_filename = "output.jpg";
    
    // Load the image
    int width, height, channels;
    unsigned char* data = stbi_load(input_filename, &width, &height, &channels, 0);
    
    if (!data) {
        std::cerr << "Error: Could not load image '" << input_filename << "'" << std::endl;
        std::cerr << "stb_image error: " << stbi_failure_reason() << std::endl;
        return 1;
    }
    
    std::cout << "Image loaded successfully!" << std::endl;
    std::cout << "Width: " << width << ", Height: " << height << ", Channels: " << channels << std::endl;
    
    // Check if the target pixel coordinates are within bounds
    int target_x = 40;
    int target_y = 100;
    
    if (target_x >= width || target_y >= height) {
        std::cerr << "Error: Target pixel (" << target_x << ", " << target_y << ") is out of bounds!" << std::endl;
        std::cerr << "Image dimensions: " << width << "x" << height << std::endl;
        stbi_image_free(data);
        return 1;
    }
    
    // Calculate the pixel index in the data array
    int pixel_index = (target_y * width + target_x) * channels;
    
    // Set the pixel to red (RGB format)
    if (channels >= 3) {
        data[pixel_index] = 255;     // Red
        data[pixel_index + 1] = 0;   // Green
        data[pixel_index + 2] = 0;   // Blue
        if (channels == 4) {
            data[pixel_index + 3] = 255; // Alpha (if present)
        }
        std::cout << "Set pixel (" << target_x << ", " << target_y << ") to red" << std::endl;
    } else {
        std::cerr << "Error: Image has " << channels << " channels, need at least 3 for RGB" << std::endl;
        stbi_image_free(data);
        return 1;
    }
    
    // Save the modified image
    int success = stbi_write_jpg(output_filename, width, height, channels, data, 90);
    
    if (success) {
        std::cout << "Modified image saved as '" << output_filename << "'" << std::endl;
    } else {
        std::cerr << "Error: Failed to save image '" << output_filename << "'" << std::endl;
    }
    
    // Free the image data
    stbi_image_free(data);
    
    return 0;
}
