// Run on the Perfetto HOME page, with the official Perfetto UI extension enabled.
// This records via the extension directly, without the recording page's category discovery.
// After this panel appears, close DevTools and click the recording button. No playback yet.
(() => {
  const extensionId = 'lfmkphfpdbjijhpomgecfikhfohaoine';
  const request = atob('CvUBCgUIgEAgAQoFCIAQIAESwQEKvgEKDGxpbnV4LmZ0cmFjZRAAogaqAQoSc2NoZWQvc2NoZWRfc3dpdGNoChJzY2hlZC9zY2hlZF93YWtpbmcKGHNjaGVkL3NjaGVkX3Byb2Nlc3NfZXhpdAoYc2NoZWQvc2NoZWRfcHJvY2Vzc19mcmVlChF0YXNrL3Rhc2tfbmV3dGFzawoQdGFzay90YXNrX3JlbmFtZQoTcG93ZXIvY3B1X2ZyZXF1ZW5jeQoOcG93ZXIvY3B1X2lkbGViAggBEh4KHAoTbGludXgucHJvY2Vzc19zdGF0cxABugYCEAEYiCc=');
  document.getElementById('g3-system-preflight')?.remove();
  const panel = document.createElement('div');
  panel.id = 'g3-system-preflight';
  panel.style.cssText = 'position:fixed;inset:24px;z-index:2147483647;background:white;color:black;padding:24px;border:3px solid #356;overflow:auto;font:18px sans-serif';
  const title = document.createElement('h2'); title.textContent = 'G3 OS trace: connection check';
  const button = document.createElement('button'); button.textContent = 'Start short trace';
  button.style.cssText = 'font-size:20px;padding:12px';
  const status = document.createElement('pre'); status.textContent = 'Ready. Close DevTools, then click Start short trace.';
  status.style.whiteSpace = 'pre-wrap';
  panel.append(title, button, status); document.body.append(panel);
  button.onclick = () => {
    button.disabled = true; status.textContent = 'Recording. Wait for automatic download.';
    const parts = []; let port, finished = false, timer;
    function end(message) {
      if (finished) return; finished = true; clearTimeout(timer);
      status.textContent = message;
      try { port?.postMessage({method:'FreeBuffers',requestData:''}); } catch {}
      setTimeout(() => { try { port?.disconnect(); } catch {} }, 100);
    }
    try {
      port = chrome.runtime.connect(extensionId);
      timer = setTimeout(() => end('Timed out: no trace received. Copy this status; do not retry playback.'), 20000);
      port.onDisconnect.addListener(() => {
        const error = chrome.runtime.lastError?.message;
        if (!finished) end('Extension disconnected: ' + (error ?? 'unknown reason'));
      });
      port.onMessage.addListener(message => {
        if (message.type === 'ChromeExtensionError') { end(message.error); return; }
        if (message.type === 'EnableTracingResponse') {
          status.textContent = 'Recording ended. Reading trace.';
          port.postMessage({method:'ReadBuffers',requestData:''});
        }
        if (message.type === 'ReadBuffersResponse') for (const slice of message.slices) {
          parts.push(Uint8Array.from(slice.data, c => c.charCodeAt(0)));
          if (slice.lastSliceForPacket) {
            const bytes = parts.reduce((n,p) => n + p.length, 0);
            if (!bytes) { end('Empty trace received.'); return; }
            const gzip = parts[0]?.[0] === 31 && parts[0]?.[1] === 139;
            const blob = new Blob(parts,{type:'application/octet-stream'});
            const link = document.createElement('a');
            link.href = URL.createObjectURL(blob);
            link.download = 'g3-system-preflight.perfetto-trace' + (gzip ? '.gz' : '');
            link.textContent = 'Download trace again'; panel.append(document.createElement('br'),link);
            link.click(); end('Saved ' + bytes + ' bytes. Send the downloaded file for analysis.');
          }
        }
      });
      // No ExtensionVersion/GetCategories/GetTrackEventDescriptor calls here.
      port.postMessage({method:'EnableTracing',requestData:request});
    } catch (error) { end(String(error)); }
  };
})();
