/* Aviator Signals — Snippet v2
   Hook WebSocket dentro do iframe Spribe e guarda crashes em window.__aviatorSignalsBuffer.
   O poller Python lê via CDP a cada 1s e repassa pro backend HTTPS.
   (arquitetura sem fetch do iframe pra evitar restrições de mixed content / PNA.)
*/

(function () {
  if (window.__aviatorSignalsHook) {
    console.log('[Aviator Signals] já ativo, ignorando.');
    return;
  }
  window.__aviatorSignalsHook = true;
  window.__aviatorSignalsBuffer = [];
  window.__aviatorSignalsStats = {
    wsConnected: false,
    wsMsgs: 0,
    lastMsgAt: 0,
    wsUrls: [],
  };

  const state = {
    lastRegistered: { value: null, at: 0 },
  };

  async function tryInflate(buf, format) {
    try {
      const stream = new DecompressionStream(format);
      const writer = stream.writable.getWriter();
      writer.write(new Uint8Array(buf));
      writer.close();
      return new Uint8Array(await new Response(stream.readable).arrayBuffer());
    } catch { return null; }
  }

  function bytesToAscii(bytes) {
    let s = '';
    for (let i = 0; i < bytes.length; i++) {
      const b = bytes[i];
      s += (b >= 32 && b < 127) ? String.fromCharCode(b) : ' ';
    }
    return s;
  }

  function registerCrash(v) {
    const now = Date.now();
    if (state.lastRegistered.value === v && (now - state.lastRegistered.at) < 5000) return;
    state.lastRegistered = { value: v, at: now };
    window.__aviatorSignalsBuffer.push({ value: v, at: now });
    console.log('[Aviator Signals] crash:', v);
  }

  function extractMultiplier(text) {
    const patterns = [
      /["']?multiplier["']?\s*[:=]\s*(\d+\.\d+)/i,
      /["']?crashPoint["']?\s*[:=]\s*(\d+\.\d+)/i,
      /["']?coefficient["']?\s*[:=]\s*(\d+\.\d+)/i,
      /["']?rate["']?\s*[:=]\s*(\d+\.\d+)/i,
      /["']?result["']?\s*[:=]\s*(\d+\.\d+)/i,
      /\b(\d+\.\d{2,3})\b/,
    ];
    for (const re of patterns) {
      const m = text.match(re);
      if (m) {
        const v = parseFloat(m[1]);
        if (v > 1.0 && v < 1000 && !Number.isInteger(v)) return v;
      }
    }
    return null;
  }

  async function handleBinary(buf) {
    let decomp = await tryInflate(buf, 'deflate');
    if (!decomp) decomp = await tryInflate(buf, 'deflate-raw');
    if (!decomp) decomp = await tryInflate(buf, 'gzip');
    const source = decomp ? bytesToAscii(decomp) : bytesToAscii(new Uint8Array(buf).slice(0, 4096));
    const v = extractMultiplier(source);
    if (v) registerCrash(v);
  }

  function handleMessage(data) {
    window.__aviatorSignalsStats.wsMsgs++;
    window.__aviatorSignalsStats.lastMsgAt = Date.now();
    if (typeof data === 'string') {
      const v = extractMultiplier(data);
      if (v) registerCrash(v);
    } else if (data instanceof Blob) {
      data.arrayBuffer().then(handleBinary);
    } else if (data instanceof ArrayBuffer) {
      handleBinary(data);
    }
  }

  // Hook constructor pra WebSockets NOVAS
  const OrigWS = window.WebSocket;
  window.WebSocket = new Proxy(OrigWS, {
    construct(target, args) {
      const [url, ...rest] = args;
      console.log('[Aviator Signals] WS criado:', url);
      window.__aviatorSignalsStats.wsUrls.push(String(url));
      const ws = new target(url, ...rest);
      ws.addEventListener('open', () => { window.__aviatorSignalsStats.wsConnected = true; });
      ws.addEventListener('close', () => { window.__aviatorSignalsStats.wsConnected = false; });
      ws.addEventListener('message', (ev) => handleMessage(ev.data));
      return ws;
    },
  });

  // Hook addEventListener pra WebSockets JÁ EXISTENTES (se algum listener for adicionado depois)
  const origAdd = EventTarget.prototype.addEventListener;
  EventTarget.prototype.addEventListener = function (type, listener, ...rest) {
    if (this instanceof OrigWS && type === 'message' && typeof listener === 'function') {
      const wrapped = function (event) {
        try { handleMessage(event.data); } catch {}
        return listener.apply(this, arguments);
      };
      return origAdd.call(this, type, wrapped, ...rest);
    }
    return origAdd.apply(this, arguments);
  };

  // Heuristica: procura por WebSocket instances ativas via performance API
  try {
    const wsEntries = performance.getEntriesByType('resource').filter(e =>
      e.name && (e.name.startsWith('ws://') || e.name.startsWith('wss://'))
    );
    window.__aviatorSignalsStats.wsResources = wsEntries.map(e => e.name);
  } catch {}

  console.log('[Aviator Signals] snippet v2 ativo. Buffer em window.__aviatorSignalsBuffer');
})();
