/**
 * @file    test_log.cpp
 * @brief   异步日志系统单元测试
 */
#include "myLog.h"
#include <cstdio>
#include <cstring>
#include <thread>
#include <chrono>
#include <unistd.h>

static int g_pass = 0, g_fail = 0;
#define TEST(n) do { printf("  TEST: %s ... ", n); } while (0)
#define OK()    do { printf("OK\n"); g_pass++; } while (0)
#define FAIL(m) do { printf("FAIL: %s\n", m); g_fail++; } while (0)

int main(void)
{
    printf("\n=== liblog 单元测试 ===\n\n");

    TEST("LOG_I basic (no crash)");
    {
        LOG_I("hello world %d", 42);
    }
    OK();

    TEST("LOG_E basic (no crash)");
    {
        LOG_E("error: %s", "test error");
    }
    OK();

    TEST("LOGI/LOGE empty message");
    {
        LOG_I("");
        LOG_E("");
    }
    OK();

    TEST("log flush (no hang)");
    {
        log_flush();
    }
    OK();

    TEST("log console/file on/off");
    {
        log_console_off();
        LOG_I("should not appear on console");
        log_console_on();
        LOG_I("console back on");

        log_file_off();
        LOG_I("should not write to file");
        log_file_on();
        LOG_I("file back on");
    }
    OK();

    TEST("burst write 100 messages + flush");
    {
        for (int i = 0; i < 100; i++)
        {
            LOG_I("burst msg #%d", i);
        }
        log_flush();
    }
    OK();

    TEST("multi-thread concurrent log");
    {
        std::thread t1([]() {
            for (int i = 0; i < 50; i++) { LOG_I("t1 msg %d", i); }
        });
        std::thread t2([]() {
            for (int i = 0; i < 50; i++) { LOG_I("t2 msg %d", i); }
        });
        t1.join();
        t2.join();
        log_flush();
    }
    OK();

    TEST("log_cleanup (graceful shutdown)");
    {
        LOG_I("before cleanup");
        log_flush();
        log_cleanup();
        /* after cleanup, first LOG call re-initializes */
        LOG_I("after cleanup");
        log_flush();
    }
    OK();

    printf("\n========================================\n");
    printf("  测试结果: %d pass, %d fail\n", g_pass, g_fail);
    printf("========================================\n");
    return (g_fail > 0) ? 1 : 0;
}
