#pragma once

#include <stdio.h>
#include <windows.h>
#include <string.h>

/* Debug level defines (from DEBUG_LEVEL parameter, set by Makefile):
 *   0 = NONE  - no debug output
 *   1 = ERR   - only _err() messages
 *   2 = WRN   - _err() + _wrn() messages  
 *   3 = INF   - _err() + _wrn() + _inf() messages
 *   4 = ALL   - all messages (_err() + _wrn() + _inf() + _dbg())
 */

/* Debug output defines (from DEBUG_OUTPUT parameter, set by Makefile):
 *   0 = CONSOLE - output to stdout (printf)
 *   1 = FILE    - output to C:\Temp\Ra.log
 */

#if defined(DEBUG_LEVEL) && DEBUG_LEVEL > 0

/* Debug is enabled - determine which levels are active */
#define ENABLE_ERR  1  /* Always enable errors (level >= 1) */
#define ENABLE_WRN  (DEBUG_LEVEL >= 2)
#define ENABLE_INF  (DEBUG_LEVEL >= 3)
#define ENABLE_DBG  (DEBUG_LEVEL >= 4)

#define DBG "DBG"
#define ERR "ERR"
#define WRN "WRN"
#define INF "INF"

#if defined(DEBUG_OUTPUT) && DEBUG_OUTPUT == 1
/* File-based logging */
#define _log(level, format, ...) do { \
    HANDLE debugFile = CreateFileA("C:\\Temp\\Ra.log", FILE_APPEND_DATA, 0, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0); \
    if (debugFile != INVALID_HANDLE_VALUE) { \
        CHAR out[512] = { 0 }; \
        DWORD written = 0; \
        sprintf_s(out, sizeof(out), "[%s] %s:%d - " format "\n", level, __FUNCTION__, __LINE__, ## __VA_ARGS__); \
        WriteFile(debugFile, out, (DWORD)strlen(out), &written, NULL); \
        CloseHandle(debugFile); \
    } \
} while(0)
#else
/* Console-based logging (default) */
#define _log(level, format, ...) do { \
    printf("[%s] %s:%d - " format "\n", level, __FUNCTION__, __LINE__, ## __VA_ARGS__); \
    fflush(stdout); \
} while(0)
#endif

/* Level-specific macros */
#if ENABLE_DBG
#define _dbg(format, ...) _log(DBG, format, ## __VA_ARGS__)
#else
#define _dbg(format, ...) ((void)0)
#endif

#define _err(format, ...) _log(ERR, format, ## __VA_ARGS__)

#if ENABLE_WRN
#define _wrn(format, ...) _log(WRN, format, ## __VA_ARGS__)
#else
#define _wrn(format, ...) ((void)0)
#endif

#if ENABLE_INF
#define _inf(format, ...) _log(INF, format, ## __VA_ARGS__)
#else
#define _inf(format, ...) ((void)0)
#endif

#else

/* Release build: no debug output */
#define _log(level, format, ...) ((void)0)
#define _dbg(format, ...) ((void)0)
#define _err(format, ...) ((void)0)
#define _wrn(format, ...) ((void)0)
#define _inf(format, ...) ((void)0)

#endif
