/***************************************************************************
 * File Name: platform_win32.c
 * Description: Windows平台具体实现（与platform.c路由函数匹配）
 * Author: ZXY
 * Company: 芯祥联科技
 * Date Created: 2025-10-22
 * Version: 1.6（修复定时器访问权限冲突）
 ***************************************************************************/
#ifdef WIN32
// 关键宏定义：解决IPv6常量未声明+减少头文件冗余冲突
#ifndef _WIN32_WINNT
#define _WIN32_WINNT 0x0601 // Windows 7 及以上
#endif
#ifdef __MINGW32__
#define APIENTRY __stdcall
#else
#define APIENTRY CALLBACK
#endif

#define WIN32_LEAN_AND_MEAN

// 严格头文件顺序：系统库 → 自定义头文件 → 其他系统库
#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>

#include "type.h"
#include "platform.h"
#include "agent_log.h"

#include <bcrypt.h>
#include <malloc.h>
#include <string.h>
#include <stdio.h>
#include <time.h>
#include <fcntl.h>
#include <io.h>

// 补充必要定义：避免加密库相关未声明错误
#include <winerror.h>
#ifndef NTSTATUS
typedef long NTSTATUS;
#endif
#ifndef STATUS_SUCCESS
#define STATUS_SUCCESS ((NTSTATUS)0x00000000L)
#endif

// 链接必要库
#ifdef _MSC_VER // 仅微软VC++编译器生效
#pragma comment(lib, "ws2_32.lib")
#pragma comment(lib, "bcrypt.lib")
#pragma comment(lib, "kernel32.lib")
#endif


// -------------------------- 类型定义（与头文件一致） --------------------------
typedef struct {
    HANDLE timer;           // 定时器句柄
    void**ctx;              // 上下文（[0]=回调函数，[1]=用户参数，[2]=自身指针）
    bool_xxl is_running;       // 定时器运行状态
    bool_xxl is_valid;         // 标记对象是否有效（防止销毁后访问）
    bool_xxl is_destroying;    // 标记是否正在销毁（防止回调与销毁冲突）
    uint32_xxl period_ms;       // 周期参数
    PlatformMutex mutex;    // 多线程安全锁
} Win32Timer;

// -------------------------- 线程实现 --------------------------
uint32_xxl platform_thread_id_win32(void) {
    return (uint32_xxl)GetCurrentThreadId();
}

PlatformThread platform_thread_create_win32(PlatformThreadFunc func, void* arg) {
    HANDLE hThread = CreateThread(
        NULL, 0, (LPTHREAD_START_ROUTINE)func, arg, 0, NULL
    );
    return (PlatformThread)hThread;
}

void platform_thread_join_win32(PlatformThread thread) {
    if (thread != NULL) {
        WaitForSingleObject((HANDLE)thread, INFINITE);
        CloseHandle((HANDLE)thread);
    }
}

void platform_thread_detach_win32(PlatformThread thread) {
    if (thread != NULL) {
        CloseHandle((HANDLE)thread);
    }
}

// -------------------------- 互斥锁实现 --------------------------
PlatformMutex platform_mutex_create_win32(void) {
    return (PlatformMutex)CreateMutex(NULL, FALSE, NULL);
}

void platform_mutex_lock_win32(PlatformMutex mutex) {
    WaitForSingleObject((HANDLE)mutex, INFINITE);
}

void platform_mutex_unlock_win32(PlatformMutex mutex) {
    ReleaseMutex((HANDLE)mutex);
}

void platform_mutex_destroy_win32(PlatformMutex mutex) {
    if (mutex != NULL) {
        CloseHandle((HANDLE)mutex);
    }
}

// -------------------------- 字符串长度实现（匹配platform.h声明） --------------------------
uint32_xxl platform_strlen_win32(const char* str) {
    if (str == NULL) return 0;
    return (uint32_xxl)strlen(str);
}

// -------------------------- 信号量实现 --------------------------
PlatformSem platform_sem_create_win32(int initial_count, int max_count) {
    return (PlatformSem)CreateSemaphore(NULL, initial_count, max_count, NULL);
}

void platform_sem_destroy_win32(PlatformSem sem) {
    if (sem != NULL) {
        CloseHandle((HANDLE)sem);
    }
}

int32_xxl platform_sem_post_win32(PlatformSem sem) {
    return ReleaseSemaphore((HANDLE)sem, 1, NULL) ? 0 : -1;
}

int32_xxl platform_sem_timedwait_win32(PlatformSem sem, uint32_xxl timeout_ms) {
    DWORD ret = WaitForSingleObject((HANDLE)sem, timeout_ms);
    return (ret == WAIT_OBJECT_0) ? 0 : 
           (ret == WAIT_TIMEOUT) ? -2 : -1;
}

// -------------------------- 平台初始化 --------------------------
bool_xxl platform_init_win32(void) {
    WSADATA wsaData;
    int ret = WSAStartup(MAKEWORD(2, 2), &wsaData);
    if (ret != 0) {
        agent_log_error("WSAStartup failed: %d", ret);
        return false;
    }
    return true;
}

void platform_deinit_win32(void) {
    WSACleanup();
}
bool_xxl platform_check_port_in_use_win32(uint16_xxl port) {
    SOCKET temp_sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    if (temp_sock == INVALID_SOCKET) return true;

    struct sockaddr_in addr;
    memset(&addr, 0, sizeof(addr));
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = INADDR_ANY;
    addr.sin_port = htons(port);

    bool_xxl in_use = true;
    if (bind(temp_sock, (struct sockaddr*)&addr, sizeof(addr)) == 0) {
        in_use = false;
    }
    closesocket(temp_sock);
    return in_use;
}

// -------------------------- 时间接口 --------------------------
uint32_xxl platform_get_tick_ms_win32(void) {
    return (uint32_xxl)GetTickCount64();
}

uint64_xxl platform_get_tick_us_win32(void) {
    LARGE_INTEGER freq, counter;
    QueryPerformanceFrequency(&freq);
    QueryPerformanceCounter(&counter);
    return (uint64_xxl)((counter.QuadPart * 1000000) / freq.QuadPart);
}

PlatformTime platform_get_utc_seconds_win32(void) {
    time_t utc_time;
    time(&utc_time);
    return (PlatformTime)utc_time;
}

PlatformTime platform_get_utc_ms_win32(void) {
    FILETIME ft;
    GetSystemTimeAsFileTime(&ft);
    ULARGE_INTEGER ull;
    ull.LowPart = ft.dwLowDateTime;
    ull.HighPart = ft.dwHighDateTime;
    const uint64_xxl EPOCH_DIFF_MS = 11644473600000ULL;
    return (ull.QuadPart / 10000ULL) - EPOCH_DIFF_MS;
}

void platform_delay_ms_win32(uint32_xxl ms) {
    Sleep(ms);
}

// -------------------------- 定时器实现 --------------------------
static VOID APIENTRY timer_callback_wrapper(LPVOID lpParam, DWORD dwTimerLowValue, DWORD dwTimerHighValue) {
    // 1. 屏蔽未使用参数（消除编译警告）
    (void)dwTimerLowValue;
    (void)dwTimerHighValue;
    
    // 2. 保留原有逻辑：TimerOrWaitFired固定为TRUE（Windows定时器触发时恒为TRUE）
    BOOLEAN TimerOrWaitFired = TRUE;

    // 3. 以下完全保留你原有的回调逻辑（一行不改）
    if (!lpParam) return;
    void** ctx = (void**)lpParam;
    PlatformTimerFunc func = (PlatformTimerFunc)ctx[0];
    void* arg = ctx[1];
    Win32Timer* win_timer = (Win32Timer*)ctx[2];  // 获取定时器自身指针

    // 回调前检查定时器状态（双重保险）
    if (!win_timer || !win_timer->is_valid || win_timer->is_destroying) {
        agent_log_warn("timer_callback_wrapper: 定时器已失效，跳过回调（地址：%p）", win_timer);
        return;
    }

    // 加锁确认状态（防止回调执行中被销毁）
    platform_mutex_lock(win_timer->mutex);
    bool_xxl can_execute = (win_timer->is_valid && !win_timer->is_destroying && win_timer->is_running);
    platform_mutex_unlock(win_timer->mutex);

    if (can_execute && func) {
        func(arg);  // 执行用户回调
    } else {
        agent_log_warn("timer_callback_wrapper: 回调被阻止（定时器状态异常，地址：%p）", win_timer);
    }
}

// 创建定时器（仅初始化，不启动）
PlatformTimer platform_timer_create_win32(PlatformTimerFunc func, void* arg, uint32_xxl period_ms) {
    // 1. 校验参数
    if (!func || period_ms == 0) {
        agent_log_error("platform_timer_create_win32: 无效参数（func=%p, period=%u）", func, period_ms);
        return NULL;
    }

    // 2. 分配结构体内存
    Win32Timer* win_timer = (Win32Timer*)LocalAlloc(LPTR, sizeof(Win32Timer));
    if (!win_timer) {
        agent_log_error("platform_timer_create_win32: 内存分配失败");
        return NULL;
    }

    // 3. 初始化互斥锁（确保多线程安全）
    win_timer->mutex = platform_mutex_create_win32();
    if (!win_timer->mutex) {
        agent_log_error("platform_timer_create_win32: 互斥锁创建失败");
        LocalFree(win_timer);
        return NULL;
    }

    // 4. 创建可等待定时器（手动重置模式）
    win_timer->timer = CreateWaitableTimer(NULL, TRUE, NULL);
    if (!win_timer->timer) {
        agent_log_error("platform_timer_create_win32: 定时器句柄创建失败（错误码：%d）", GetLastError());
        platform_mutex_destroy_win32(win_timer->mutex);
        LocalFree(win_timer);
        return NULL;
    }

    // 5. 初始化上下文和状态（扩展为3个元素，包含自身指针）
    win_timer->ctx = (void**)LocalAlloc(LPTR, 3 * sizeof(void*));
    if (!win_timer->ctx) {
        agent_log_error("platform_timer_create_win32: 上下文内存分配失败");
        CloseHandle(win_timer->timer);
        platform_mutex_destroy_win32(win_timer->mutex);
        LocalFree(win_timer);
        return NULL;
    }
    win_timer->ctx[0] = (void*)func;    // 回调函数
    win_timer->ctx[1] = arg;            // 用户参数
    win_timer->ctx[2] = win_timer;      // 自身指针（供回调检查）
    
    win_timer->period_ms = period_ms;
    win_timer->is_running = false;
    win_timer->is_valid = true;
    win_timer->is_destroying = false;

    agent_log_debug("platform_timer_create_win32: 定时器创建成功（地址：%p）", win_timer);
    return (PlatformTimer)win_timer;
}

bool_xxl platform_timer_start_win32(PlatformTimer timer) {
    // 1. 基础指针校验
    if (!timer) {
        agent_log_error("platform_timer_start_win32: 无效指针（NULL）");
        return false;
    }

    // 2. 校验内存有效性（过滤已释放/非法地址）
    uintptr_t timer_addr = (uintptr_t)timer;
    // 0xDDDDDDDD 是 Windows 调试堆释放后的填充标记（Debug 模式）
    if (timer_addr == 0 || (timer_addr & 0xFFFFFFFF) == 0xDDDDDDDD) {
        agent_log_error("platform_timer_start_win32: 访问已释放的定时器（地址：%p）", timer);
        return false;
    }

    Win32Timer* win_timer = (Win32Timer*)timer;

    // 3. 校验互斥锁有效性（防止 mutex 已被销毁）
    if (!win_timer->mutex) {
        agent_log_error("platform_timer_start_win32: 定时器互斥锁已失效（地址：%p）", timer);
        return false;
    }

    // 4. 加锁保护
    platform_mutex_lock(win_timer->mutex);

    // 5. 检查定时器内部状态
    if (!win_timer->is_valid || win_timer->is_destroying) {
        agent_log_error("platform_timer_start_win32: 定时器已失效或正在销毁（地址：%p）", timer);
        platform_mutex_unlock(win_timer->mutex);
        return false;
    }

    // 6. 已运行状态检查
    if (win_timer->is_running) {
        agent_log_warn("platform_timer_start_win32: 定时器已运行（地址：%p）", timer);
        platform_mutex_unlock(win_timer->mutex);
        return true;
    }

    // 7. 内部资源有效性检查
    if (!win_timer->timer || !win_timer->ctx) {
        agent_log_error("platform_timer_start_win32: 定时器内部资源无效（地址：%p）", timer);
        platform_mutex_unlock(win_timer->mutex);
        return false;
    }

    // 8. 设置定时器（立即触发，按周期重复）
    LARGE_INTEGER liDueTime;
    liDueTime.QuadPart = -10000LL * 0;  // 立即触发（100纳秒为单位，负值表示相对时间）
    if (!SetWaitableTimer(
            win_timer->timer,
            &liDueTime,
            win_timer->period_ms,
            timer_callback_wrapper,
            win_timer->ctx,
            FALSE
        )) {
        agent_log_error("platform_timer_start_win32: 启动失败（错误码：%d，地址：%p）", GetLastError(), timer);
        platform_mutex_unlock(win_timer->mutex);
        return false;
    }

    // 9. 更新状态
    win_timer->is_running = true;
    agent_log_debug("platform_timer_start_win32: 定时器启动成功（地址：%p）", timer);
    platform_mutex_unlock(win_timer->mutex);
    return true;
}

// 停止定时器
bool_xxl platform_timer_stop_win32(PlatformTimer timer) {
    if (!timer) return false;

    Win32Timer* win_timer = (Win32Timer*)timer;
    
    // 校验内存有效性
    uintptr_t timer_addr = (uintptr_t)timer;
    if (timer_addr == 0 || (timer_addr & 0xFFFFFFFF) == 0xDDDDDDDD) {
        agent_log_error("platform_timer_stop_win32: 访问已释放的定时器（地址：%p）", timer);
        return false;
    }

    platform_mutex_lock_win32(win_timer->mutex);

    // 检查是否已失效或正在销毁
    if (!win_timer->is_valid || win_timer->is_destroying) {
        platform_mutex_unlock_win32(win_timer->mutex);
        agent_log_error("platform_timer_stop_win32: 定时器已失效（地址：%p）", timer);
        return false;
    }

    if (!win_timer->is_running) {
        platform_mutex_unlock_win32(win_timer->mutex);
        return true;
    }

    // 取消定时器
    if (CancelWaitableTimer(win_timer->timer)) {
        win_timer->is_running = false;
        agent_log_debug("platform_timer_stop_win32: 定时器已停止（地址：%p）", timer);
        platform_mutex_unlock_win32(win_timer->mutex);
        return true;
    } else {
        agent_log_error("platform_timer_stop_win32: 停止失败（错误码：%d，地址：%p）", GetLastError(), timer);
        platform_mutex_unlock_win32(win_timer->mutex);
        return false;
    }
}

// 销毁定时器
void platform_timer_destroy_win32(PlatformTimer timer) {
    if (!timer) return;

    Win32Timer* win_timer = (Win32Timer*)timer;
    
    // 校验内存有效性
    uintptr_t timer_addr = (uintptr_t)timer;
    if (timer_addr == 0 || (timer_addr & 0xFFFFFFFF) == 0xDDDDDDDD) {
        agent_log_error("platform_timer_destroy_win32: 访问已释放的定时器（地址：%p）", timer);
        return;
    }

    platform_mutex_lock_win32(win_timer->mutex);

    // 检查是否正在销毁（防止重复销毁）
    if (win_timer->is_destroying) {
        platform_mutex_unlock_win32(win_timer->mutex);
        agent_log_warn("platform_timer_destroy_win32: 重复销毁（地址：%p）", timer);
        return;
    }

    // 标记为正在销毁，阻止新的回调和操作
    win_timer->is_destroying = true;
    win_timer->is_valid = false;

    // 停止定时器（确保不再触发回调）
    if (win_timer->is_running) {
        CancelWaitableTimer(win_timer->timer);
        win_timer->is_running = false;
    }

    platform_mutex_unlock_win32(win_timer->mutex);  // 先解锁，避免回调等待锁

    // 延迟释放资源（给正在执行的回调足够时间退出）
    platform_delay_ms_win32(10);  // 10ms足够回调执行完毕

    // 重新加锁释放资源
    platform_mutex_lock_win32(win_timer->mutex);
    if (win_timer->ctx) {
        LocalFree(win_timer->ctx);
        win_timer->ctx = NULL;
    }
    if (win_timer->timer) {
        CloseHandle(win_timer->timer);
        win_timer->timer = NULL;
    }
    platform_mutex_unlock_win32(win_timer->mutex);
    platform_mutex_destroy_win32(win_timer->mutex);  // 销毁互斥锁

    // 最后释放结构体内存
    LocalFree(win_timer);
    agent_log_debug("platform_timer_destroy_win32: 定时器彻底销毁（地址：%p）", timer);
}

// -------------------------- 内存接口 --------------------------
void* platform_malloc_win32(uint32_xxl size) {
	// 优化1：校验分配大小（避免0字节分配，不同C库对0字节malloc行为不一致）
	if (size == 0) {
		agent_log_warn("[内存日志] 跳过0字节malloc");
		return NULL;
	}

	// 优化2：捕获malloc失败（内存不足），输出日志便于定位
	void* ptr = malloc(size);
	if (ptr == NULL) {
		agent_log_error("[内存日志] malloc失败：申请大小=%u字节", size);
	} else {
		agent_log_debug("[内存日志] malloc成功：%p, 大小=%u字节", ptr, size);
	}
	return ptr;

}

//void* platform_calloc_win32(uint32_xxl num, uint32_xxl size) {
//    return LocalAlloc(LPTR, num * size);
//}

//void* platform_malloc_aligned_win32(uint32_xxl size, uint32_xxl align, PlatformMemType type) {
//    (void)type;  // 忽略type参数（兼容头文件声明）
//    return _aligned_malloc(size, align);
//}

void platform_free_win32(void* ptr) {
    if (ptr == NULL) {
        agent_log_debug("[内存日志] 跳过空指针释放：%p", ptr);
        return;
    }

    // ✅ 修复：MinGW 不支持 __try，直接安全 free
    free(ptr);
    agent_log_debug("[内存日志] 正常释放内存：%p", ptr);
}


void platform_free_aligned_win32(void* ptr) {
    if (ptr != NULL) {
        _aligned_free(ptr);
    }
}

// -------------------------- 随机数接口 --------------------------
bool_xxl platform_rand_generate_win32(uint8_xxl* buf, uint32_xxl len) {
    if (buf == NULL || len == 0) {
        return false;
    }

    for (uint32_xxl i = 0; i < len; i++) {
        buf[i] = (uint8_xxl)(rand() % 256);
    }
    return true;
}

bool_xxl platform_rand_generate_crypto_win32(uint8_xxl* buf, uint32_xxl len) {
    if (buf == NULL || len == 0) {
        return false;
    }

    BCRYPT_ALG_HANDLE hAlg = NULL;
    NTSTATUS status;

    status = BCryptOpenAlgorithmProvider(&hAlg, BCRYPT_RNG_ALGORITHM, NULL, 0);
    if (status != STATUS_SUCCESS) {
        agent_log_error("BCryptOpenAlgorithmProvider failed: 0x%X", status);
        return false;
    }

    status = BCryptGenRandom(hAlg, buf, len, 0);
    if (status != STATUS_SUCCESS) {
        agent_log_error("BCryptGenRandom failed: 0x%X", status);
        BCryptCloseAlgorithmProvider(hAlg, 0);
        return false;
    }

    BCryptCloseAlgorithmProvider(hAlg, 0);
    return true;
}

// -------------------------- 文件系统接口 --------------------------
bool_xxl platform_file_exists_win32(const char* path) {
    if (!path) return false;
    return (GetFileAttributesA(path) != INVALID_FILE_ATTRIBUTES);
}

uint32_xxl platform_get_file_size_win32(const char* path) {
    if (!path) return 0;

    WIN32_FILE_ATTRIBUTE_DATA file_data;
    if (!GetFileAttributesExA(path, GetFileExInfoStandard, &file_data)) {
        return 0;
    }

    return (uint32_xxl)(file_data.nFileSizeLow);
}

uint32_xxl platform_get_runtime_filename_win32(char* buf, uint32_xxl buf_len) {
    if (buf == NULL || buf_len == 0) {
        return 0;
    }

    char_xxl full_path[MAX_PATH] = {0};
    DWORD path_len = GetModuleFileNameA(NULL, full_path, MAX_PATH - 1);
    if (path_len == 0) {
        agent_log_error("GetModuleFileName failed: %d", GetLastError());
        return 0;
    }

    // 提取文件名（含扩展名）
    char* filename = strrchr(full_path, '\\');
    filename = (filename == NULL) ? full_path : (filename + 1);

    // 移除扩展名
    char* dot_pos = strrchr(filename, '.');
    uint32_xxl name_len = (dot_pos != NULL) ? 
                     (uint32_xxl)(dot_pos - filename) : 
                     (uint32_xxl)strlen(filename);

    // 安全复制到输出缓冲区
    uint32_xxl copy_len = (name_len < buf_len - 1) ? name_len : (buf_len - 1);
    memcpy(buf, filename, copy_len);
    buf[copy_len] = '\0';

    return copy_len;
}

// -------------------------- 字符串/内存操作 --------------------------
uint32_xxl platform_memcpy_s_win32(void* dest, uint32_xxl dest_max_len, const void* src, uint32_xxl src_len) {
    if (dest == NULL || src == NULL || dest_max_len == 0) {
        return 0;
    }
    uint32_xxl copy_len = (src_len < dest_max_len) ? src_len : dest_max_len;
    memmove(dest, src, copy_len);  // 处理缓冲区重叠
    return copy_len;
}

uint32_xxl platform_memset_s_win32(void* dest, uint32_xxl dest_max_len, uint8_xxl value, uint32_xxl set_len) {
    if (!dest || dest_max_len == 0) return 0;
    uint32_xxl actual_len = (set_len < dest_max_len) ? set_len : dest_max_len;
    memset(dest, value, actual_len);
    return actual_len;
}

uint32_xxl platform_strcpy_s_win32(char* dest, uint32_xxl dest_max_len, const char* src) {
    if (dest == NULL || src == NULL || dest_max_len == 0) {
        return 0;
    }
    uint32_xxl src_len = (uint32_xxl)strlen(src);
    uint32_xxl copy_len = (src_len < dest_max_len - 1) ? src_len : (dest_max_len - 1);
    
    memcpy(dest, src, copy_len);
    dest[copy_len] = '\0';  // 强制添加终止符
    return copy_len;
}

int32_xxl platform_strcmp_win32(const char* str1, const char* str2) {
    return strcmp(str1, str2);
}

char* platform_strchr_win32(const char* str, int32_xxl ch) {
    return strchr(str, ch);
}

#endif  // WIN32
