#include <pthread.h>
#include <atomic>
#include <algorithm>
#include <chrono>
#include "row.hpp"
#include "sort_algorithms.hpp"

// Χρήση του MatrixSortContext για πρόσβαση στα δεδομένα του πίνακα
struct MatrixSortContext {
    uint8_t* A;
    int F, H, W;
};

struct GuidedArgs {
    MatrixSortContext* ctx;
    std::atomic<int>* next_row;
    int total_rows;
    int K; // Αριθμός threads
};

void* guided_worker(void* arg) {
    GuidedArgs* ga = (GuidedArgs*)arg;
    
    while (true) {
        int remaining = ga->total_rows - ga->next_row->load();
        if (remaining <= 0) break;

        // Υπολογισμός μεγέθους chunk: εναπομείναντα / threads
        int chunk_size = std::max(1, remaining / ga->K);
        int start = ga->next_row->fetch_add(chunk_size);
        if (start >= ga->total_rows) break;

        int end = std::min(start + chunk_size, ga->total_rows);
        for (int i = start; i < end; ++i) {
            uint8_t* row_ptr = ga->ctx->A + (static_cast<size_t>(i) * ga->ctx->W);
            // Ταξινόμηση απευθείας στη Shared Memory
            row<uint8_t> r(row_ptr, static_cast<uint32_t>(ga->ctx->W), false);
            quick_sort(r);
        }
    }
    return nullptr;
}

long long run_guided_scheduler(MatrixSortContext* ctx, int K) {
    int total_rows = ctx->F * ctx->H;
    std::atomic<int> next_row(0);
    pthread_t threads[K];
    GuidedArgs args[K];

    auto t1 = std::chrono::high_resolution_clock::now();
    for (int i = 0; i < K; ++i) {
        args[i] = {ctx, &next_row, total_rows, K};
        pthread_create(&threads[i], nullptr, guided_worker, &args[i]);
    }
    for (int i = 0; i < K; ++i) pthread_join(threads[i], nullptr);
    auto t2 = std::chrono::high_resolution_clock::now();

    return std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1).count();
}