import ctypes
import ctypes.wintypes
from PIL import Image

user32 = ctypes.windll.user32
gdi32 = ctypes.windll.gdi32

hwinsta = user32.OpenWindowStationW("WinSta0", False, 0x10000000)
if hwinsta:
    user32.SetProcessWindowStation(hwinsta)

hdesk = user32.OpenDesktopW("Default", 0, False, 0x10000000)
if hdesk:
    user32.SetThreadDesktop(hdesk)

hwnd = 0x016211AE
rect = ctypes.wintypes.RECT()
user32.GetWindowRect(hwnd, ctypes.byref(rect))
w = rect.right - rect.left
h = rect.bottom - rect.top
print(f"Window Rect: ({rect.left}, {rect.top}, {rect.right}, {rect.bottom}), w={w}, h={h}")

desk_dc = user32.GetDC(0)
mem_dc = gdi32.CreateCompatibleDC(desk_dc)
bmp = gdi32.CreateCompatibleBitmap(desk_dc, w, h)
gdi32.SelectObject(mem_dc, bmp)

SRCCOPY = 0x00CC0020
gdi32.BitBlt(mem_dc, 0, 0, w, h, desk_dc, rect.left, rect.top, SRCCOPY)

class BITMAPINFOHEADER(ctypes.Structure):
    _fields_ = [
        ('biSize', ctypes.wintypes.DWORD),
        ('biWidth', ctypes.wintypes.LONG),
        ('biHeight', ctypes.wintypes.LONG),
        ('biPlanes', ctypes.wintypes.WORD),
        ('biBitCount', ctypes.wintypes.WORD),
        ('biCompression', ctypes.wintypes.DWORD),
        ('biSizeImage', ctypes.wintypes.DWORD),
        ('biXPelsPerMeter', ctypes.wintypes.LONG),
        ('biYPelsPerMeter', ctypes.wintypes.LONG),
        ('biClrUsed', ctypes.wintypes.DWORD),
        ('biClrImportant', ctypes.wintypes.DWORD),
    ]
bmi = BITMAPINFOHEADER()
bmi.biSize = ctypes.sizeof(BITMAPINFOHEADER)
bmi.biWidth = w
bmi.biHeight = -h
bmi.biPlanes = 1
bmi.biBitCount = 32
bmi.biCompression = 0
buf = ctypes.create_string_buffer(w * h * 4)
lines = gdi32.GetDIBits(mem_dc, bmp, 0, h, buf, ctypes.byref(bmi), 0)

if lines > 0:
    img = Image.frombuffer("RGBA", (w, h), buf, "raw", "BGRA", 0, 1)
    img.save("captures/poe2_current_full.png")
    print("Saved captures/poe2_current_full.png!")

    # Crop skillbar region (bottom right)
    skillbar_img = img.crop((w - 550, h - 220, w - 10, h - 10))
    skillbar_img.save("captures/poe2_skillbar.png")
    print("Saved captures/poe2_skillbar.png!")
