"""Discover Aviator UI elements via CDP, atacando direto o iframe da Spribe.

Uso:
    cd /Users/deividsoares/projetos/irondome-operator
    source .venv/bin/activate
    python discover.py
"""
import json
import sys
import urllib.request
sys.path.insert(0, '.')
import websocket  # type: ignore


def main():
    # lista targets
    with urllib.request.urlopen('http://localhost:9222/json', timeout=3) as r:
        targets = json.loads(r.read().decode())
    print(f'total targets CDP: {len(targets)}')
    spribe = None
    for t in targets:
        url = t.get('url', '')
        if 'spribegaming' in url or 'aviator-next' in url:
            spribe = t
            break
    if not spribe:
        print('iframe da Spribe não encontrado.')
        for t in targets:
            print(f"  type={t.get('type')} url={t.get('url')[:80]}")
        return
    print(f'\n🎯 alvo: {spribe.get("url")[:80]}')
    print(f'   ws: {spribe.get("webSocketDebuggerUrl")}')

    # conecta direto no target do iframe
    ws = websocket.create_connection(spribe['webSocketDebuggerUrl'], timeout=5)
    next_id = [1]

    def call(method, params=None):
        msg = {'id': next_id[0], 'method': method, 'params': params or {}}
        next_id[0] += 1
        ws.send(json.dumps(msg))
        while True:
            data = json.loads(ws.recv())
            if data.get('id') == msg['id']:
                return data

    # discovery JS
    js = r"""
    (function() {
      const out = { url: location.href, inputs: [], buttons: [], dataTestIds: [] };
      document.querySelectorAll('input').forEach((el, i) => {
        const r = el.getBoundingClientRect();
        if (r.width < 20 || r.height < 10) return;
        out.inputs.push({
          idx: i,
          type: el.type,
          cls: el.className.slice(0,80),
          id: el.id || null,
          name: el.name || null,
          placeholder: el.placeholder || null,
          value: el.value || null,
          parentCls: el.parentElement ? el.parentElement.className.slice(0,80) : '',
          dataTestId: el.getAttribute('data-test-id') || el.getAttribute('data-testid') || null,
        });
      });
      document.querySelectorAll('button').forEach((el, i) => {
        const txt = (el.textContent || '').trim().slice(0, 40);
        if (!txt) return;
        out.buttons.push({
          idx: i,
          text: txt,
          cls: el.className.slice(0,80),
          parentCls: el.parentElement ? el.parentElement.className.slice(0,80) : '',
          dataTestId: el.getAttribute('data-test-id') || el.getAttribute('data-testid') || null,
        });
      });
      // procura elementos com data-test-id (típico do Aviator)
      document.querySelectorAll('[data-test-id], [data-testid]').forEach(el => {
        const id = el.getAttribute('data-test-id') || el.getAttribute('data-testid');
        if (id) out.dataTestIds.push({ id, tag: el.tagName, text: (el.textContent||'').trim().slice(0,30) });
      });
      return out;
    })()
    """
    res = call('Runtime.evaluate', {'expression': js, 'returnByValue': True, 'awaitPromise': True})
    data = res.get('result', {}).get('result', {}).get('value', {})

    print(f"\n📍 url interno: {data.get('url', '?')}")
    print(f"   {len(data.get('inputs',[]))} inputs · {len(data.get('buttons',[]))} botões · {len(data.get('dataTestIds',[]))} data-test-id")

    print("\n--- INPUTS ---")
    for i in data.get('inputs', []):
        print(f"  [{i['idx']:>2}] type={i['type']} placeholder={i['placeholder']!r} value={i['value']!r}")
        print(f"        cls={i['cls']!r}")
        print(f"        parent.cls={i['parentCls']!r}")
        if i['dataTestId']: print(f"        data-test-id={i['dataTestId']}")

    print("\n--- BUTTONS (texto não-vazio) ---")
    for b in data.get('buttons', []):
        print(f"  [{b['idx']:>2}] text={b['text']!r}")
        print(f"        cls={b['cls']!r}")
        print(f"        parent.cls={b['parentCls']!r}")
        if b['dataTestId']: print(f"        data-test-id={b['dataTestId']}")

    print("\n--- data-test-id (todos os elementos) ---")
    for d in data.get('dataTestIds', []):
        print(f"  {d['id']:<40} <{d['tag']}> text={d['text']!r}")

    ws.close()
    print('\n=== fim ===')


if __name__ == '__main__':
    main()
