/*
 * DWN - Desktop Window Manager
 * retoor <retoor@molodetz.nl>
 * Specialized Worker Threads - High-Level API
 * 
 * Pre-built worker types for common async operations:
 * - I/O Worker: File operations, networking
 * - Compute Worker: CPU-intensive tasks
 * - System Worker: /proc monitoring, system stats
 * - Deferred Worker: Delayed/scheduled execution
 */

#ifndef DWN_THREAD_WORKERS_H
#define DWN_THREAD_WORKERS_H

#include "threading.h"

/* ============================================================================
 * I/O Worker - Async File and Network Operations
 * ============================================================================ */

typedef void (*IoCallback)(void *result, size_t size, int error, void *user_data);
typedef void (*IoProgressCallback)(size_t processed, size_t total, void *user_data);

/**
 * Initialize I/O worker subsystem
 */
bool io_worker_init(void);

/**
 * Shutdown I/O worker subsystem
 */
void io_worker_shutdown(void);

/**
 * Read file asynchronously
 * @param path File path
 * @param callback Called with file contents
 * @param user_data Passed to callback
 * @return Task handle or NULL
 */
TaskHandle io_read_file_async(const char *path, IoCallback callback, void *user_data);

/**
 * Write file asynchronously
 */
TaskHandle io_write_file_async(const char *path, const void *data, size_t size,
                               IoCallback callback, void *user_data);

/**
 * Read directory contents asynchronously
 * Result is a null-separated list of filenames
 */
TaskHandle io_read_dir_async(const char *path, IoCallback callback, void *user_data);

/**
 * HTTP GET request asynchronously
 * @param url URL to fetch
 * @param callback Called with response body
 * @param user_data Passed to callback
 * @return Task handle or NULL
 */
TaskHandle io_http_get_async(const char *url, IoCallback callback, void *user_data);

/**
 * HTTP POST request asynchronously
 */
TaskHandle io_http_post_async(const char *url, const void *data, size_t size,
                              IoCallback callback, void *user_data);

/**
 * Download file with progress callback
 */
TaskHandle io_download_async(const char *url, const char *dest_path,
                             IoProgressCallback progress,
                             IoCallback callback, void *user_data);

/* ============================================================================
 * Compute Worker - CPU-Intensive Tasks
 * ============================================================================ */

typedef void (*ComputeCallback)(void *result, void *user_data);

/**
 * Initialize compute worker subsystem
 */
bool compute_worker_init(void);

/**
 * Shutdown compute worker subsystem
 */
void compute_worker_shutdown(void);

/**
 * Parallel for - distribute work across threads
 * @param start Start index
 * @param end End index (exclusive)
 * @param func Function called for each index
 * @param user_data Passed to each invocation
 */
void compute_parallel_for(int start, int end, 
                          void (*func)(int index, void *user_data),
                          void *user_data);

/**
 * Map operation - apply function to each element
 */
void* compute_map(void *array, size_t count, size_t elem_size,
                  void (*func)(void *in, void *out, void *user_data),
                  void *user_data);

/**
 * Reduce operation - aggregate values
 */
void* compute_reduce(void *array, size_t count, size_t elem_size,
                     void (*func)(void *accum, void *elem, void *user_data),
                     void *initial, void *user_data);

/**
 * Submit compute task
 */
TaskHandle compute_submit(void (*func)(void *user_data), void *user_data,
                          ComputeCallback callback, void *callback_data);

/* ============================================================================
 * System Worker - System Monitoring
 * ============================================================================ */

typedef struct {
    float cpu_percent;
    uint64_t memory_used;
    uint64_t memory_total;
    float memory_percent;
    float load_avg[3];
    uint64_t uptime_seconds;
} SystemStats;

typedef struct {
    uint32_t pid;
    char name[64];
    float cpu_percent;
    uint64_t memory_bytes;
} ProcessInfo;

typedef void (*SystemStatsCallback)(const SystemStats *stats, void *user_data);
typedef void (*ProcessListCallback)(ProcessInfo *processes, uint32_t count, void *user_data);

/**
 * Initialize system worker
 */
bool system_worker_init(void);

/**
 * Shutdown system worker
 */
void system_worker_shutdown(void);

/**
 * Get cached system stats (non-blocking, updated periodically)
 */
bool system_worker_get_cached_stats(SystemStats *stats);

/**
 * Get fresh system stats (blocking)
 */
Future* system_worker_get_stats_async(void);

/**
 * Get process list asynchronously
 */
TaskHandle system_worker_get_processes_async(ProcessListCallback callback, void *user_data);

/**
 * Subscribe to periodic stats updates
 * @param interval_ms Update interval (0 to disable)
 * @param callback Called with new stats
 * @param user_data Passed to callback
 * @return Subscription ID
 */
uint32_t system_worker_subscribe_stats(uint32_t interval_ms, 
                                        SystemStatsCallback callback,
                                        void *user_data);

/**
 * Unsubscribe from stats updates
 */
bool system_worker_unsubscribe_stats(uint32_t subscription_id);

/* ============================================================================
 * Deferred Worker - Delayed Execution
 * ============================================================================ */

typedef uint64_t DeferredId;
typedef void (*DeferredCallback)(DeferredId id, void *user_data);

/**
 * Initialize deferred worker
 */
bool deferred_worker_init(void);

/**
 * Shutdown deferred worker
 */
void deferred_worker_shutdown(void);

/**
 * Execute after delay
 * @param delay_ms Milliseconds to wait
 * @param callback Function to call
 * @param user_data Passed to callback
 * @return Deferred ID
 */
DeferredId deferred_after(uint64_t delay_ms, DeferredCallback callback, void *user_data);

/**
 * Execute at regular interval
 */
DeferredId deferred_every(uint64_t interval_ms, DeferredCallback callback, void *user_data);

/**
 * Cancel deferred execution
 */
bool deferred_cancel(DeferredId id);

/**
 * Process deferred tasks (call from main loop)
 * @return Number of tasks executed
 */
uint32_t deferred_process(void);

/**
 * Get poll fd for select()
 */
int deferred_get_poll_fd(void);

/* ============================================================================
 * High-Level Integration API
 * ============================================================================ */

/**
 * Initialize all worker subsystems
 */
bool thread_workers_init(void);

/**
 * Shutdown all worker subsystems
 */
void thread_workers_shutdown(void);

/**
 * Process all pending async work (call from main loop)
 * @return true if work was processed
 */
bool thread_workers_process_all(void);

/**
 * Get combined poll fds for select()
 * @param fds Array to fill (size at least 4)
 * @return Number of fds filled
 */
int thread_workers_get_poll_fds(int *fds);

#endif /* DWN_THREAD_WORKERS_H */
