#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "../plugin.h"
#include "../libs/virtualdesktopaccessor/virtualdesktopaccessor.h"

typedef int (*NoArg)(void);
typedef int (*WithIndex)(int);
typedef int (*WithWindow)(HWND);
typedef int (*MoveDesktopWindow)(HWND, int);

int main(void) {
    HMODULE dll = LoadLibraryA("plugin.dll");
    if (!dll) { fprintf(stderr, "DLL load failed: %lu\n", GetLastError()); return 1; }
    NoArg count = (NoArg)GetProcAddress(dll, "GetDesktopCount");
    NoArg current = (NoArg)GetProcAddress(dll, "GetCurrentDesktopNumber");
    WithIndex go = (WithIndex)GetProcAddress(dll, "GoToDesktopNumber");
    if (!count || !current || !go ||
        !GetProcAddress(dll, "GetWindowDesktopNumber") ||
        !GetProcAddress(dll, "IsWindowOnCurrentVirtualDesktop") ||
        !GetProcAddress(dll, "MoveWindowToDesktopNumber")) {
        fprintf(stderr, "Missing export\n");
        FreeLibrary(dll);
        return 1;
    }
    sxhkd_plugin_abi_fn abi = (sxhkd_plugin_abi_fn)GetProcAddress(dll, "sxhkd_plugin_abi");
    sxhkd_plugin_invoke_fn invoke = (sxhkd_plugin_invoke_fn)GetProcAddress(dll, "sxhkd_plugin_invoke");
    if (!abi || !invoke || abi() != SXHKD_PLUGIN_ABI ||
        invoke("unknown", "1") == 0 || invoke("move-to-desktop", "invalid") == 0 ||
        invoke("pin-app", "unexpected") == 0 || invoke("app-pin-status", "unexpected") == 0)
        return 1;
    const char *exports[] = {
        "GetDesktopIdByNumber", "GetDesktopNumberById", "GetWindowDesktopId",
        "GetDesktopName", "SetDesktopName", "IsPinnedWindow", "PinWindow",
        "UnPinWindow", "IsPinnedApp", "PinApp", "UnPinApp",
        "IsWindowOnDesktopNumber", "CreateDesktop", "RemoveDesktop", "MoveDesktop",
        "RegisterPostMessageHook", "UnregisterPostMessageHook", "RestartVirtualDesktopAccessor"
    };
    for (size_t i = 0; i < sizeof exports / sizeof exports[0]; i++) {
        if (!GetProcAddress(dll, exports[i])) {
            fprintf(stderr, "Missing export: %s\n", exports[i]);
            return 1;
        }
    }
    int n = count(), index = current();
    printf("desktops: %d; current: %d\n", n, index);
    if (n <= 0 || index < 0 || index >= n || go(-1) != -1 || go(n) != -1) {
        fprintf(stderr, "COM interface unavailable or invalid result (requires Windows 11 24H2+)\n");
        return 1;
    }
    GUID (*id_by_number)(int) = (GUID (*)(int))GetProcAddress(dll, "GetDesktopIdByNumber");
    int (*number_by_id)(GUID) = (int (*)(GUID))GetProcAddress(dll, "GetDesktopNumberById");
    int (*get_name)(int, char *, size_t) = (int (*)(int, char *, size_t))GetProcAddress(dll, "GetDesktopName");
    char name[512];
    if (number_by_id(id_by_number(index)) != index || get_name(index, name, sizeof name) != 1)
        return 1;
    printf("desktop name: %s\n", name);
    WithWindow window_number = (WithWindow)GetProcAddress(dll, "GetWindowDesktopNumber");
    GUID (*window_id)(HWND) = (GUID (*)(HWND))GetProcAddress(dll, "GetWindowDesktopId");
    WithWindow pinned_window = (WithWindow)GetProcAddress(dll, "IsPinnedWindow");
    GUID zero = {0};
    GUID invalid = window_id(NULL);
    if (window_number(NULL) != -1 || memcmp(&invalid, &zero, sizeof zero) ||
        pinned_window(NULL) != -1) return 1;
    HWND listener = CreateWindowExA(0, "STATIC", "notification smoke", 0,
        0, 0, 0, 0, HWND_MESSAGE, NULL, GetModuleHandleA(NULL), NULL);
    int (*subscribe)(HWND, UINT) = (int (*)(HWND, UINT))GetProcAddress(dll, "RegisterPostMessageHook");
    void (*unsubscribe)(HWND) = (void (*)(HWND))GetProcAddress(dll, "UnregisterPostMessageHook");
    if (!listener || subscribe(listener, WM_APP + 10) != 1) return 1;
    int notification_ok = 1;
    if (getenv("VDA_TEST_NOTIFY") && n > 1) {
        int target = index == 0 ? 1 : 0;
        if (go(target) != 1) notification_ok = 0;
        Sleep(700);
        MSG message;
        int received = 0;
        while (PeekMessageW(&message, listener, WM_APP + 10, WM_APP + 10, PM_REMOVE))
            if (message.wParam == (WPARAM)index && message.lParam == (LPARAM)target)
                received = 1;
        if (go(index) != 1 || !received) notification_ok = 0;
    }
    unsubscribe(listener);
    DestroyWindow(listener);
    if (!notification_ok) { fprintf(stderr, "Desktop switch notification failed\n"); return 1; }
    if (getenv("VDA_TEST_MUTATE")) {
        int (*create)(void) = (int (*)(void))GetProcAddress(dll, "CreateDesktop");
        int (*remove_desktop)(int, int) = (int (*)(int, int))GetProcAddress(dll, "RemoveDesktop");
        int (*move_desktop)(int, int) = (int (*)(int, int))GetProcAddress(dll, "MoveDesktop");
        int (*set_name)(int, const char *) = (int (*)(int, const char *))GetProcAddress(dll, "SetDesktopName");
        int added = create();
        if (added < 0) { fprintf(stderr, "CreateDesktop failed\n"); return 1; }
        char renamed[128];
        int ok = count() == n + 1 &&
            set_name(added, "dwhkd-port-smoke") == 1 &&
            get_name(added, renamed, sizeof renamed) == 1 &&
            strcmp(renamed, "dwhkd-port-smoke") == 0 &&
            move_desktop(added, added) == 1;
        /* Always attempt cleanup even when validation fails. */
        int removed = remove_desktop(added, index);
        if (!ok || removed != 1 || count() != n) return 1;
    }
    if (getenv("VDA_BENCH")) {
        DWORD start = GetTickCount();
        for (int i = 0; i < 50; i++) if (count() < 1) return 1;
        printf("50 desktop-count calls: %lu ms\n", GetTickCount() - start);
    }
    if (getenv("VDA_TEST_MOVE")) {
        WithWindow window_index = (WithWindow)GetProcAddress(dll, "GetWindowDesktopNumber");
        WithWindow visible = (WithWindow)GetProcAddress(dll, "IsWindowOnCurrentVirtualDesktop");
        MoveDesktopWindow move = (MoveDesktopWindow)GetProcAddress(dll, "MoveWindowToDesktopNumber");
        HWND window = CreateWindowExA(0, "STATIC", "VDA smoke window", WS_OVERLAPPEDWINDOW,
            20, 20, 200, 100, NULL, NULL, GetModuleHandleA(NULL), NULL);
        if (!window) return 1;
        ShowWindow(window, SW_SHOWNOACTIVATE);
        Sleep(300);
        int before = window_index(window), on_current = visible(window);
        int moved = move(window, index);
        int (*is_pinned)(HWND) = (int (*)(HWND))GetProcAddress(dll, "IsPinnedWindow");
        int (*pin)(HWND) = (int (*)(HWND))GetProcAddress(dll, "PinWindow");
        int (*unpin)(HWND) = (int (*)(HWND))GetProcAddress(dll, "UnPinWindow");
        int was_pinned = is_pinned(window);
        int pin_result = pin(window);
        int now_pinned = is_pinned(window);
        int unpin_result = unpin(window); /* Always try to restore before destroying. */
        printf("test window: desktop %d, current %d, move %d, pin %d/%d/%d\n",
            before, on_current, moved, pin_result, now_pinned, unpin_result);
        DestroyWindow(window);
        if (before != index || on_current != 1 || moved != 1 || was_pinned != 0 ||
            pin_result != 1 || now_pinned != 1 || unpin_result != 1) return 1;
    }
    if (getenv("VDA_TEST_SWITCH") && go(index) != 1) {
        fprintf(stderr, "Switching to current desktop failed\n");
        FreeLibrary(dll);
        return 1;
    }
    FreeLibrary(dll);
    return 0;
}
