import asyncio
import glob
import os
import sys
import time
from playwright.async_api import async_playwright

URL = "https://slot-machine.zybg4298.odns.fr/#/291qo"
SESSIONS = int(sys.argv[1]) if len(sys.argv) > 1 else 20
MAX_PLAYS = 100
COOLDOWN_S = 31
ANIM_MS = 5000
CLICK_X, CLICK_Y = 640, 360
results = {}


async def get(page, key):
    return await page.evaluate(f"localStorage.getItem('{key}')")


async def spin(page, timeout_ms):
    # clique puis attend que les crédits baissent, sinon le coup a été refusé
    before = await get(page, "slotMachine_credits")
    await page.mouse.click(CLICK_X, CLICK_Y)
    end = time.monotonic() + timeout_ms / 1000
    while time.monotonic() < end:
        await asyncio.sleep(0.2)
        if await get(page, "slotMachine_credits") != before:
            return True
    return False


async def session(browser, sid):
    tag = f"S{sid:02d}"
    ctx = await browser.new_context(ignore_https_errors=True)
    page = await ctx.new_page()
    try:
        await page.goto(URL, wait_until="networkidle", timeout=60000)
        fast = None  # none = saut du cooldown pas encore testé
        last_play = 0.0
        plays = 0
        while plays < MAX_PLAYS:
            credits = await get(page, "slotMachine_credits")
            if credits is not None and int(credits) <= 0:
                break
            gains_before = await get(page, "slotMachine_totalGains")
            ok = False
            if fast is not False and plays > 0:
                # tente de sauter le cooldown sans quitter la page
                await page.evaluate("localStorage.setItem('slotMachine_lastPlay', '0')")
                ok = await spin(page, 3000)
                if fast is None:
                    fast = ok
                    print(f"[{tag}] Saut du cooldown : {'actif' if ok else 'inefficace, attente de 31 s'}.")
            if not ok:
                wait = last_play + COOLDOWN_S - time.monotonic()
                if wait > 0:
                    await asyncio.sleep(wait)
                ok = await spin(page, 10000)
            if not ok:
                print(f"[{tag}] Coup refusé, nouvel essai dans 5 s.")
                await asyncio.sleep(5)
                continue
            last_play = time.monotonic()
            plays += 1
            await page.wait_for_timeout(ANIM_MS)
            gains = await get(page, "slotMachine_totalGains")
            if gains != gains_before:
                # on remplace la capture précédente de la session
                for old in glob.glob(f"win_*_{tag}.png"):
                    os.remove(old)
                score = int(float(gains or 0))
                await page.screenshot(path=f"win_{score:05d}_{tag}.png")
                print(f"[{tag}] Coup {plays} : gagné. Total {gains}.")
            else:
                print(f"[{tag}] Coup {plays} : perdu. Total {gains}.")
        gains = await get(page, "slotMachine_totalGains")
        results[tag] = gains
        score = int(float(gains or 0))
        await page.screenshot(path=f"final_{score:05d}_{tag}.png")
        print(f"[{tag}] Terminé. Total {gains}. Capture dans final_{score:05d}_{tag}.png.")
    except Exception as e:
        print(f"[{tag}] Erreur : {e}")
    finally:
        await ctx.close()


async def main():
    async with async_playwright() as p:
        browser = await p.chromium.launch()
        tasks = []
        for i in range(1, SESSIONS + 1):
            tasks.append(asyncio.create_task(session(browser, i)))
            await asyncio.sleep(1)  # démarrage étalé pour ne pas saturer
        await asyncio.gather(*tasks)
        await browser.close()
    print("Classement :")
    for tag, g in sorted(results.items(), key=lambda x: float(x[1] or 0), reverse=True):
        print(f"{tag} : {g}")


if __name__ == "__main__":
    asyncio.run(main())
