"""
m0_probe.py — Milestone 0: prove Flyff accepts trusted CDP input from Playwright.

Re-uses the persistent profile from login.py (so you're already logged in),
gives you a countdown to stand in-game next to a monster, then:
  1) holds W briefly   -> character should MOVE forward
  2) Ctrl+Clicks just above screen center -> should TARGET + ATTACK a monster

Saves probe_before.png / probe_after.png for evidence.

Run:  python m0_probe.py   (after logging in once via login.py)
"""
import time
from pathlib import Path
from playwright.sync_api import sync_playwright
from shots import shot_path

USER_DATA = Path(__file__).parent / "chrome-profile"
FLYFF_URL = "https://universe.flyff.com/play"
COUNTDOWN = 30  # seconds to get in-game and stand near a monster


def main():
    with sync_playwright() as p:
        ctx = p.chromium.launch_persistent_context(
            user_data_dir=str(USER_DATA),
            headless=False,
            no_viewport=True,
            args=["--start-maximized"],
        )
        page = ctx.pages[0] if ctx.pages else ctx.new_page()
        if "flyff" not in (page.url or ""):
            page.goto(FLYFF_URL, wait_until="domcontentloaded")

        print(f"\nYou have {COUNTDOWN}s: be in-game with a MONSTER visible near the")
        print("center-top of the screen, character standing still.\n")
        for i in range(COUNTDOWN, 0, -1):
            print(f"  probing in {i:2d}s ...", end="\r")
            time.sleep(1)
        print("\nProbing now.\n")

        # CSS-pixel size (Playwright mouse uses CSS pixels, DPR-independent).
        size = page.evaluate("({width: window.innerWidth, height: window.innerHeight})")
        w, h = size["width"], size["height"]
        cx, cy = w / 2, h / 2

        page.screenshot(path=shot_path("probe_before.png"))

        # Focus the game canvas.
        page.mouse.click(cx, cy)
        time.sleep(0.4)

        # 1) Movement test: hold W.
        print("-> pressing W (move forward) for ~1.2s")
        page.keyboard.down("w")
        time.sleep(1.2)
        page.keyboard.up("w")
        time.sleep(0.6)

        # 2) Attack test: Ctrl+Click slightly above center (likely a monster).
        print("-> Ctrl+Click above center (target + attack)")
        tx, ty = cx, cy - h * 0.12
        page.keyboard.down("Control")
        page.mouse.click(tx, ty)
        page.keyboard.up("Control")
        time.sleep(2.5)

        page.screenshot(path=shot_path("probe_after.png"))
        print("\nSaved screenshots/probe_before.png and probe_after.png.")
        print("Did the character MOVE and ATTACK? Window closes in 6s.")
        time.sleep(6)
        ctx.close()


if __name__ == "__main__":
    main()
