/*
 * DWN - Desktop Window Manager
 * retoor <retoor@molodetz.nl>
 * Utility functions
 */

#ifndef DWN_UTIL_H
#define DWN_UTIL_H

#include <stdbool.h>
#include <stddef.h>
#include <stdarg.h>
#include <assert.h>
#include <string.h>

#define DWN_ASSERT(cond) assert(cond)
#define DWN_ASSERT_MSG(cond, msg) assert((cond) && (msg))

typedef enum {
    LOG_DEBUG,
    LOG_INFO,
    LOG_WARN,
    LOG_ERROR
} LogLevel;

void log_init(const char *log_file);
void log_close(void);
void log_set_level(LogLevel level);
void log_flush(void);
void log_msg(LogLevel level, const char *fmt, ...);

#define LOG_DEBUG(...) log_msg(LOG_DEBUG, __VA_ARGS__)
#define LOG_INFO(...)  log_msg(LOG_INFO, __VA_ARGS__)
#define LOG_WARN(...)  log_msg(LOG_WARN, __VA_ARGS__)
#define LOG_ERROR(...) log_msg(LOG_ERROR, __VA_ARGS__)

void *dwn_malloc(size_t size);
void *dwn_calloc(size_t nmemb, size_t size);
void *dwn_realloc(void *ptr, size_t size);
char *dwn_strdup(const char *s);
void dwn_free(void *ptr);
void secure_wipe(void *ptr, size_t size);

char *str_trim(char *str);
bool str_starts_with(const char *str, const char *prefix);
bool str_ends_with(const char *str, const char *suffix);
int str_split(char *str, char delim, char **parts, int max_parts);
char *shell_escape(const char *str);

/* Safe string copy that always null-terminates */
static inline void safe_strncpy(char *dest, const char *src, size_t n)
{
    if (n == 0) return;
    size_t src_len = strlen(src);
    size_t copy_len = (src_len < n - 1) ? src_len : n - 1;
    memcpy(dest, src, copy_len);
    dest[copy_len] = '\0';
}

/* Check if value is within valid range */
static inline bool in_range_int(int val, int min, int max)
{
    return val >= min && val <= max;
}

static inline bool in_range_size_t(size_t val, size_t min, size_t max)
{
    return val >= min && val <= max;
}

bool file_exists(const char *path);
char *file_read_all(const char *path);
bool file_write_all(const char *path, const char *content);
char *expand_path(const char *path);

unsigned long parse_color(const char *color_str);
void color_to_rgb(unsigned long color, int *r, int *g, int *b);
unsigned long rgb_to_pixel(int r, int g, int b);
unsigned long generate_unique_color(void);
unsigned long adjust_color_for_background(unsigned long color, unsigned long bg);
unsigned long interpolate_color(unsigned long from, unsigned long to, float progress);
unsigned long dim_color(unsigned long color, float factor);
unsigned long glow_color(unsigned long base, float phase);
unsigned long ambient_glow_bg(unsigned long base, float phase);
unsigned long ambient_glow_accent(unsigned long base, float phase);

long get_time_ms(void);
void sleep_ms(int ms);

int spawn(const char *cmd);
int spawn_async(const char *cmd);
char *spawn_capture(const char *cmd);

#endif
