#ifndef TEST_COMMON_H
#define TEST_COMMON_H

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <math.h>
#include <time.h>

#define TEST_PASSED 0
#define TEST_FAILED 1

typedef struct {
    const char *name;
    int (*fn)(void);
} TestCase;

typedef struct {
    const char *name;
    double (*fn)(void);
} BenchCase;

extern int test_failures;
extern int test_total;

#define TEST_ASSERT(cond, msg) do { \
    if (!(cond)) { \
        fprintf(stderr, "  [FAIL] %s\n", msg); \
        test_failures++; \
        return TEST_FAILED; \
    } \
} while (0)

#define TEST_ASSERT_EQ(actual, expected, msg) do { \
    if ((actual) != (expected)) { \
        fprintf(stderr, "  [FAIL] %s: expected %ld, got %ld\n", msg, (long)(expected), (long)(actual)); \
        test_failures++; \
        return TEST_FAILED; \
    } \
} while (0)

#define TEST_ASSERT_FTZ(actual, expected, tol, msg) do { \
    double _actual = (double)(actual); \
    double _expected = (double)(expected); \
    double _tol = (double)(tol); \
    double _diff = fabs(_actual - _expected); \
    if (_diff > _tol) { \
        fprintf(stderr, "  [FAIL] %s: expected %.6f, got %.6f (diff %.6f)\n", msg, _expected, _actual, _diff); \
        test_failures++; \
        return TEST_FAILED; \
    } \
} while (0)

#define TEST_ASSERT_PTR_NOT_NULL(ptr, msg) do { \
    if ((ptr) == NULL) { \
        fprintf(stderr, "  [FAIL] %s: pointer is NULL\n", msg); \
        test_failures++; \
        return TEST_FAILED; \
    } \
} while (0)

#define RUN_TEST(tests, name) do { \
    int _result = (name)(); \
    test_total++; \
    if (_result == TEST_PASSED) { \
        printf("  [PASS] %s\n", #name); \
    } \
} while (0)

#define RUN_BENCH(benchmarks, name, iter) do { \
    double _time = run_benchmark((name), (iter)); \
    printf("  [BENCH] %-40s %.3f ms\n", #name, _time); \
} while (0)

extern int test_failures;
extern int test_total;

uint8_t *load_image(const char *path, int *width, int *height, int *channels);
int save_image(const char *path, uint8_t *data, int width, int height, int channels);
uint8_t *downsample_image(uint8_t *src, int sw, int sh, int sc, int *dw, int *dh, float scale);
double get_time_ms(void);
double run_benchmark(double (*fn)(void), int iterations);
int compare_images(uint8_t *a, uint8_t *b, int w, int h, int ch, float threshold);
float compute_psnr(uint8_t *a, uint8_t *b, int w, int h, int ch);
uint8_t *create_gradient_image(int w, int h);
uint8_t *create_noise_image(int w, int h, unsigned int seed);
uint8_t *create_uniform_image(int w, int h, uint8_t r, uint8_t g, uint8_t b);
uint8_t *create_checkerboard(int w, int h, int check_size);

#endif
