"""
ringheal.py — Ringmaster permanent heal: HOLD the heal key (default "1") down.

Default mode = true HOLD: presses the key once and keeps it held until you stop
(Ctrl+C), exactly like physically holding "1". This works if the game polls
keyboard state and auto-repeats the cast while the key is down.

If the game instead needs a fresh keydown per cast (a single held keydown casts
only once), use spam mode: it re-presses on an interval.

Attaches to the live window held open by host.py (CDP :9222). Run after logging
in on the Ringmaster char:
    python -u ringheal.py                 # HOLD key "1" until Ctrl+C
    python -u ringheal.py 7               # HOLD key "7"
    python -u ringheal.py 1 spam          # spam key "1" (recast ~1.0s)
    python -u ringheal.py 1 spam 1.5      # spam key "1", recast every 1.5s
Stop with Ctrl+C (the key is released on exit).
"""
import sys
import time
from playwright.sync_api import sync_playwright
from session import get_page

HEAL_KEY = sys.argv[1] if len(sys.argv) > 1 else "1"        # in-game heal keybind
SPAM = len(sys.argv) > 2 and sys.argv[2].lower() == "spam"  # re-press vs. hold
INTERVAL = float(sys.argv[3]) if len(sys.argv) > 3 else 1.0  # spam: secs between casts


def hold(page):
    print(f"RINGHEAL — HOLDING '{HEAL_KEY}' down. Ctrl+C to release & stop.")
    page.keyboard.down(HEAL_KEY)
    try:
        while True:
            time.sleep(0.5)                # just keep the process (and key) alive
    finally:
        page.keyboard.up(HEAL_KEY)         # always release on exit
        print("\nreleased.")


def spam(page):
    print(f"RINGHEAL — spamming '{HEAL_KEY}' every {INTERVAL}s. Ctrl+C to stop.")
    casts = 0
    while True:
        page.keyboard.down(HEAL_KEY); time.sleep(0.06); page.keyboard.up(HEAL_KEY)
        casts += 1
        print(f"[heal] cast #{casts} -> '{HEAL_KEY}'", end="\r")
        time.sleep(INTERVAL)


def main():
    with sync_playwright() as p:
        browser, page = get_page(p)
        (spam if SPAM else hold)(page)


if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        print("\nstopped.")
