"""
AutoClickPro 좌표 헬퍼 서버 v1.1
설치: pip install websockets pyautogui
실행: python mouse_server.py
"""
import asyncio
import json
import websockets
import pyautogui
import sys
import ctypes

PORT = 7700

# ── DPI 보정 ──────────────────────────────────
# Windows 배율 설정에 따라 pyautogui가 논리좌표를 반환하는 문제 해결
# SetProcessDpiAwareness(2) = 모니터별 DPI 인식 → 물리픽셀 좌표로 읽음
try:
    ctypes.windll.shcore.SetProcessDpiAwareness(2)
    print("[DPI] 물리픽셀 모드 설정 완료 (배율 200% 보정 활성)")
except Exception as e:
    print(f"[DPI] 설정 실패 (Windows 아님?): {e}")

async def handler(ws):
    print(f"[연결됨] {ws.remote_address}")
    try:
        async def send_coords():
            while True:
                x, y = pyautogui.position()
                await ws.send(json.dumps({"type": "coords", "x": x, "y": y}))
                await asyncio.sleep(0.05)  # 20fps

        async def recv_msgs():
            async for msg in ws:
                pass

        await asyncio.gather(send_coords(), recv_msgs())

    except websockets.exceptions.ConnectionClosed:
        print(f"[연결종료]")

async def main():
    print("=" * 45)
    print("  AutoClickPro 좌표 헬퍼 서버 v1.1")
    print(f"  ws://localhost:{PORT}")
    print("  [DPI 보정] 물리픽셀 좌표 모드")
    print("  브라우저에서 settings 페이지를 열고")
    print("  [🎯 좌표 헬퍼] 버튼을 눌러주세요")
    print("  종료: Ctrl+C")
    print("=" * 45)
    async with websockets.serve(handler, "localhost", PORT):
        await asyncio.Future()

try:
    asyncio.run(main())
except KeyboardInterrupt:
    print("\n서버 종료됨")
