"""
session.py — attach to the live browser started by host.py.

Usage:
    from playwright.sync_api import sync_playwright
    from session import get_page
    with sync_playwright() as p:
        browser, page = get_page(p)
        ...                       # operate on the live game page
    # leaving the `with` disconnects the CDP client; host.py keeps the window open.
"""
CDP_URL = "http://localhost:9222"


def get_page(p):
    """Return (browser, page) for the live Flyff window held open by host.py."""
    browser = p.chromium.connect_over_cdp(CDP_URL)
    if not browser.contexts:
        raise RuntimeError("No browser context found — is host.py running?")
    ctx = browser.contexts[0]
    page = ctx.pages[0] if ctx.pages else ctx.new_page()
    return browser, page


def viewport(page):
    """CSS-pixel (width, height) — the coordinate space Playwright mouse uses."""
    s = page.evaluate("({width: window.innerWidth, height: window.innerHeight})")
    return s["width"], s["height"]
