#pragma once

#ifdef _WIN32

#include "IWindowTracker.hpp"
#include <Windows.h>
#include <Psapi.h>
#include <string>

namespace celuna {

/**
 * @brief Windows implementation of window tracking
 *
 * Uses Win32 APIs:
 * - GetForegroundWindow(): Get active window handle
 * - GetWindowText(): Get window title
 * - GetWindowThreadProcessId() + GetModuleBaseName(): Get process name
 * - GetLastInputInfo(): Track user idle time
 */
class Win32WindowTracker : public IWindowTracker {
public:
    Win32WindowTracker() = default;
    ~Win32WindowTracker() override = default;

    std::string getCurrentAppName() override {
        HWND hwnd = GetForegroundWindow();
        if (!hwnd) return "";

        DWORD processId = 0;
        GetWindowThreadProcessId(hwnd, &processId);
        if (processId == 0) return "";

        HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
                                      FALSE, processId);
        if (!hProcess) return "";

        char processName[MAX_PATH] = {0};
        if (GetModuleBaseNameA(hProcess, NULL, processName, sizeof(processName)) > 0) {
            CloseHandle(hProcess);
            // Remove .exe extension
            std::string name(processName);
            auto pos = name.rfind(".exe");
            if (pos != std::string::npos) {
                name = name.substr(0, pos);
            }
            return name;
        }

        CloseHandle(hProcess);
        return "";
    }

    std::string getCurrentWindowTitle() override {
        HWND hwnd = GetForegroundWindow();
        if (!hwnd) return "";

        char title[256] = {0};
        GetWindowTextA(hwnd, title, sizeof(title));
        return std::string(title);
    }

    bool isUserIdle(int thresholdSeconds) override {
        return getIdleTimeSeconds() >= thresholdSeconds;
    }

    int getIdleTimeSeconds() override {
        LASTINPUTINFO lii;
        lii.cbSize = sizeof(LASTINPUTINFO);

        if (GetLastInputInfo(&lii)) {
            DWORD tickCount = GetTickCount();
            DWORD idleTime = tickCount - lii.dwTime;
            return static_cast<int>(idleTime / 1000);
        }
        return 0;
    }

    bool isAvailable() const override {
        return true;  // Always available on Windows
    }

    std::string getPlatformName() const override {
        return "win32";
    }
};

} // namespace celuna

#endif // _WIN32
