import ctypes, time
from PIL import ImageGrab
import win32gui, shutil

user32 = ctypes.windll.user32
hdesk = user32.OpenInputDesktop(0, False, 0x01FF)
if hdesk: user32.SetThreadDesktop(hdesk)

hwnd = 0x002F0BF4 # PID 32572 (BoCuaCacCon)

def make_lparam(x, y):
    return ((y & 0xFFFF) << 16) | (x & 0xFFFF)

def click(x, y):
    lp = make_lparam(x, y)
    user32.PostMessageW(hwnd, 0x0200, 0, lp)
    time.sleep(0.04)
    user32.PostMessageW(hwnd, 0x0201, 1, lp)
    time.sleep(0.08)
    user32.PostMessageW(hwnd, 0x0202, 0, lp)
    time.sleep(0.05)

def send_key(vk):
    lp = (0x1C << 16) | 1
    user32.PostMessageW(hwnd, 0x0100, vk, lp)
    time.sleep(0.04)
    user32.PostMessageW(hwnd, 0x0101, vk, lp | (3 << 30))
    time.sleep(0.04)

user32.SetForegroundWindow(hwnd)
time.sleep(0.2)

# Click "Xác định" at (92, 561) and send VK_RETURN
print("Entering game world with BoCuaCacCon...")
click(92, 561)
time.sleep(0.1)
send_key(0x0D)

print("Waiting 5.0 seconds for map loading...")
time.sleep(5.0)

# Dismiss any daily popup
click(300, 570)
time.sleep(0.3)
send_key(0x1B) # ESC
time.sleep(0.5)

rect = win32gui.GetWindowRect(hwnd)
img = ImageGrab.grab(bbox=rect, all_screens=True)
path = r"c:\Projects\JX\logs\in_game_bocuacaccon_empirical.png"
img.save(path)
print(f"Empirical game world screenshot saved: {path}")

# Copy to brain artifact
artifact_path = r"C:\Users\Admin\.gemini\antigravity\brain\1b4a0d01-a767-4d3f-966f-116a863fc8de\in_game_bocuacaccon_empirical.png"
shutil.copyfile(path, artifact_path)
