/**
 * Stream injector — WebRTC code injected into the browser page.
 *
 * When browser_stream_start is called, this code is injected via
 * page.addInitScript() and page.evaluate(). It captures the page
 * visually and streams it via WebRTC through the signaling server.
 *
 * Approach: canvas.captureStream() at 15 FPS.
 * The canvas mirrors the visible viewport content.
 */
/**
 * Inject WebRTC streaming code into a Playwright page.
 * Uses addInitScript so it's present on every navigation.
 */
export async function injectStreamingCode(page, config) {
    const iceServersJson = JSON.stringify(config.iceServers);
    await page.addInitScript(`
    (() => {
      if (window.__spectralStreamInstalled) return;
      window.__spectralStreamInstalled = true;

      const SIGNALING_URL = ${JSON.stringify(config.signalingUrl)};
      const SESSION_ID = ${JSON.stringify(config.sessionId)};
      const ICE_SERVERS = ${iceServersJson};

      let pc = null;
      let localStream = null;
      let ws = null;
      let canvas = null;
      let animationId = null;

      window.__spectralStreamStart = async function() {
        try {
          // Connect signaling WebSocket
          ws = new WebSocket(SIGNALING_URL);

          await new Promise((resolve, reject) => {
            ws.onopen = () => {
              ws.send(JSON.stringify({ type: "streamer-join", sessionId: SESSION_ID }));
              resolve();
            };
            ws.onerror = reject;
          });

          // Capture viewport via canvas
          canvas = document.createElement("canvas");
          canvas.width = window.innerWidth;
          canvas.height = window.innerHeight;
          const ctx = canvas.getContext("2d");

          localStream = canvas.captureStream(15); // 15 FPS

          // Draw a simple visualization frame
          function drawFrame() {
            if (!ctx) return;
            // Background
            ctx.fillStyle = "#1a1a2e";
            ctx.fillRect(0, 0, canvas.width, canvas.height);
            // Status text
            ctx.fillStyle = "#ffffff";
            ctx.font = "20px monospace";
            ctx.fillText("Spectral Browser Stream", 20, 40);
            ctx.fillStyle = "#a0a0c0";
            ctx.font = "14px monospace";
            ctx.fillText("URL: " + window.location.href, 20, 70);
            ctx.fillText("Time: " + new Date().toISOString(), 20, 90);
            animationId = requestAnimationFrame(drawFrame);
          }
          drawFrame();

          // Listen for viewer join messages
          ws.onmessage = async (event) => {
            const msg = JSON.parse(event.data);

            if (msg.type === "viewer-joined") {
              await createOfferForViewer(msg.viewerId);
            }

            if (msg.type === "answer") {
              const desc = new RTCSessionDescription(msg.sdp);
              await pc.setRemoteDescription(desc);
            }

            if (msg.type === "ice-candidate") {
              try {
                const candidate = new RTCIceCandidate(msg.candidate);
                await pc.addIceCandidate(candidate);
              } catch (e) {
                console.warn("[spectral-stream] ICE candidate error:", e);
              }
            }
          };

          async function createOfferForViewer(viewerId) {
            pc = new RTCPeerConnection({ iceServers: ICE_SERVERS });

            for (const track of localStream.getTracks()) {
              pc.addTrack(track, localStream);
            }

            pc.onicecandidate = (e) => {
              if (e.candidate && ws?.readyState === WebSocket.OPEN) {
                ws.send(JSON.stringify({
                  type: "ice-candidate",
                  sessionId: SESSION_ID,
                  receiverId: viewerId,
                  candidate: e.candidate.toJSON(),
                }));
              }
            };

            const offer = await pc.createOffer();
            await pc.setLocalDescription(offer);

            if (ws?.readyState === WebSocket.OPEN) {
              ws.send(JSON.stringify({
                type: "offer",
                sessionId: SESSION_ID,
                receiverId: viewerId,
                sdp: pc.localDescription.toJSON(),
              }));
            }
          }

          console.log("[spectral-stream] Streaming started — canvas capture at 15 FPS");
        } catch (err) {
          console.error("[spectral-stream] Failed to start:", err);
        }
      };

      window.__spectralStreamStop = function() {
        if (animationId) cancelAnimationFrame(animationId);
        if (pc) { pc.close(); pc = null; }
        if (localStream) {
          localStream.getTracks().forEach(t => t.stop());
          localStream = null;
        }
        if (ws) { ws.close(); ws = null; }
        if (canvas) { canvas.remove(); canvas = null; }
        window.__spectralStreamInstalled = false;
        console.log("[spectral-stream] Streaming stopped");
      };
    })();
  `);
    // Trigger if page already loaded
    await page.evaluate(() => {
        if (window.__spectralStreamStart) {
            window.__spectralStreamStart();
        }
    });
}
/**
 * Stop the WebRTC stream and clean up injected code.
 */
export async function stopStreaming(page) {
    await page.evaluate(() => {
        if (window.__spectralStreamStop) {
            window.__spectralStreamStop();
        }
    });
}
