#!/usr/bin/env python3.12
"""Injeta o snippet Aviator Signals no iframe do Spribe via CDP."""

import json
import os
import sys
import time
import urllib.request
import websocket

CDP_HOST = 'http://localhost:9222'
SNIPPET_PATH = os.path.join(os.path.dirname(__file__), 'static', 'snippet.js')


def list_targets():
    try:
        r = urllib.request.urlopen(CDP_HOST + '/json/list', timeout=3)
        return json.loads(r.read())
    except Exception as e:
        return None


def find_spribe_target(timeout=60):
    """Procura o iframe do Spribe rodando. Aguarda até timeout."""
    start = time.time()
    while time.time() - start < timeout:
        targets = list_targets()
        if not targets:
            print('.', end='', flush=True)
            time.sleep(1)
            continue
        for t in targets:
            url = t.get('url', '')
            if 'spribegaming.com' in url or 'spribe.games' in url:
                return t
        # Alternativa: pega a página do 7k aviator mesmo que sem iframe detectado
        for t in targets:
            if '7k.bet.br/games/spribe/aviator' in t.get('url', ''):
                print(' [7k encontrado, aguardando iframe...]', end='', flush=True)
        time.sleep(1)
        print('.', end='', flush=True)
    return None


def inject_snippet(target):
    """Conecta ao target via WebSocket e executa Runtime.evaluate com o snippet."""
    with open(SNIPPET_PATH) as f:
        snippet_code = f.read()

    ws_url = target['webSocketDebuggerUrl']
    print(f'\nConectando em: {ws_url}')
    ws = websocket.create_connection(ws_url, timeout=10)

    # Enable Runtime domain
    ws.send(json.dumps({'id': 1, 'method': 'Runtime.enable'}))
    r1 = json.loads(ws.recv())

    # Execute snippet
    ws.send(json.dumps({
        'id': 2,
        'method': 'Runtime.evaluate',
        'params': {
            'expression': snippet_code,
            'includeCommandLineAPI': True,
            'awaitPromise': False,
            'returnByValue': True,
        }
    }))

    while True:
        msg = json.loads(ws.recv())
        if msg.get('id') == 2:
            result = msg.get('result', {})
            if result.get('exceptionDetails'):
                print(f'ERRO: {result["exceptionDetails"].get("text")}')
                print(json.dumps(result["exceptionDetails"], indent=2))
                return False
            else:
                print('Snippet injetado com sucesso')
                return True

    ws.close()


def main():
    print(f'Procurando iframe do Spribe em {CDP_HOST}...')
    target = find_spribe_target(timeout=90)
    if not target:
        print('\nNenhum target do Spribe encontrado. Garanta que você clicou JOGAR no Aviator.')
        # Lista tudo pra debug
        targets = list_targets()
        if targets:
            print('\nTargets visíveis:')
            for t in targets:
                print(f'  - [{t.get("type")}] {t.get("url")[:90]}')
        sys.exit(1)

    print(f'\nTarget encontrado: {target["url"][:80]}')
    if inject_snippet(target):
        print('\n✓ Snippet rodando no iframe do Spribe.')
        print('  Dashboard em http://localhost:8766/ começará a receber crashes em tempo real.')
    else:
        sys.exit(1)


if __name__ == '__main__':
    main()
