import re
import sys
from playwright.sync_api import sync_playwright

URL = "https://slot-machine.zybg4298.odns.fr/#/291qo"
MAX_TRIES = 300
WAIT_RESULT_MS = 6000  # durée de l'animation des rouleaux

# mots-clés à adapter si besoin après le mode debug
WIN = re.compile(r"(gagn|bravo|f[ée]licit|jackpot|win)", re.I)
LOSE = re.compile(r"(perdu|dommage|lose|lost|r[ée]essa)", re.I)
SPIN = re.compile(r"(jouer|lancer|tourner|spin|play|go)", re.I)


def visible_lines(page):
    txt = page.inner_text("body")
    return {l.strip() for l in txt.splitlines() if l.strip()}


def find_spin(page):
    btn = page.get_by_role("button", name=SPIN)
    if btn.count() > 0:
        return btn.first
    # repli : premier élément cliquable de la page
    any_btn = page.locator("button, [role=button]")
    return any_btn.first if any_btn.count() > 0 else None


def main():
    debug = len(sys.argv) > 1 and sys.argv[1] == "debug"
    with sync_playwright() as p:
        browser = p.chromium.launch()
        for i in range(1, MAX_TRIES + 1):
            # contexte neuf à chaque partie = navigation privée
            ctx = browser.new_context(viewport={"width": 430, "height": 932}, is_mobile=True, ignore_https_errors=True)
            page = ctx.new_page()
            try:
                page.goto(URL, wait_until="networkidle", timeout=30000)
                before = visible_lines(page)
                btn = find_spin(page)
                if btn is None:
                    page.screenshot(path="no_button.png", full_page=True)
                    print("Bouton introuvable, voir no_button.png.")
                    return
                btn.click()
                page.wait_for_timeout(WAIT_RESULT_MS)
                page.screenshot(path="last.png", full_page=True)
                new_text = "\n".join(visible_lines(page) - before)
                if debug:
                    print("Nouveau texte après le spin :")
                    print(new_text or "(aucun)")
                    print("Capture enregistrée dans last.png.")
                    return
                if new_text and not LOSE.search(new_text):
                    page.screenshot(path="win.png", full_page=True)
                    print(f"Gagné après {i} parties. Capture dans win.png.")
                    return
                print(f"Partie {i} : perdu ({new_text[:50]!r})")
            except Exception as e:
                print(f"Partie {i} : erreur {e}")
            finally:
                ctx.close()
        print("Pas de victoire après le nombre maximal de parties.")


if __name__ == "__main__":
    main()
