#!/usr/bin/env bash
# Issue #41796: the Android app's simulator preview never tries H.264/WebRTC and always streams
# full-size MJPEG.
# Claim: already fixed by #41846 (6db795afd7). An iOS viewer without WebCodecs (the Android app's
# WebView on a plain-http environment) now sends a WebRTC offer even though T3 Code's own device
# hub reports transport "http", and shows MJPEG only if the offer is refused or no frame arrives.
# Shows: before #41846 such a viewer goes straight to MJPEG and never sends an offer; on main it
# sends the offer, paints the WebRTC video and never shows the MJPEG image.
# Needs deps installed (`vp i`). Run from the root of a clean t3code checkout.
set -euo pipefail

ok=1
pass() { echo "PASS  $*"; }
fail() { echo "FAIL  $*"; ok=0; }

if [ -n "$(git status --porcelain)" ]; then
  echo "refusing to run on a dirty tree"
  exit 2
fi
ORIG=$(git symbolic-ref -q --short HEAD || git rev-parse HEAD)
TEST=packages/client-runtime/src/device/prove-issue-41796.test.ts
LOG=$(mktemp)
cleanup() {
  rm -f "$TEST" "$LOG"
  git checkout -q -f "$ORIG"
}
trap 'rc=$?; cleanup; [ "${PROOF_DONE:-0}" = 1 ] && exit 0; [ "$rc" -ne 0 ] && exit "$rc"; exit 1' EXIT

git fetch -q origin main
MAIN=$(git rev-parse FETCH_HEAD)
FIX=6db795afd744b4420a3b540d954c83e381fa4259
BEFORE=$(git rev-parse "$FIX^")
echo "main=$MAIN fix=$FIX before=$BEFORE"

subject=$(git log -1 --format=%s "$FIX")
if git merge-base --is-ancestor "$FIX" "$MAIN" \
  && [ "$subject" = "fix(client-runtime): iOS simulators without WebCodecs try WebRTC before MJPEG (#41846)" ]; then
  pass "#41846 ($(git rev-parse --short "$FIX")) is on main: $subject"
else
  fail "#41846 is not on main, or $FIX is a different commit ($subject)"
fi

# The Android app runs this same client in its WebView, on the environment's http origin for
# iOS targets, and never asks for MJPEG.
browser=apps/mobile/src/features/devices/device-stream.browser.ts
document=apps/mobile/src/features/devices/device-stream-document.ts
if git show "$MAIN:$browser" | grep -q '@t3tools/client-runtime/device/stream' \
  && ! git grep -q preferMjpeg "$MAIN" -- apps/mobile/src \
  && git show "$MAIN:$document" | grep -qF 'return `${new URL(httpBase).origin}/`;'; then
  pass "main: the Android app's viewer ($browser) uses client-runtime's stream client, never sets preferMjpeg, and loads iOS targets on the environment's origin"
else
  fail "main: the Android app's viewer no longer matches what this test models"
fi

write_test() {
  cat > "$TEST" <<'EOF'
// prove-issue-41796: an iOS simulator viewed from a page without WebCodecs (the Android app's
// WebView on a plain-http environment), against a device hub that reports transport "http".
import { afterEach, expect, it, vi } from "vite-plus/test";
import { createDeviceStreamClient } from "./stream.ts";

afterEach(() => {
  vi.useRealTimers();
  vi.unstubAllGlobals();
});

it("prove-issue-41796", async () => {
  vi.useFakeTimers();
  expect("VideoDecoder" in globalThis).toBe(false);
  class Socket {
    static OPEN = 1;
    readyState = 1;
    binaryType = "";
    onopen: (() => void) | null = null;
    onmessage: ((event: { data: string }) => void) | null = null;
    onclose: ((event: { code: number; reason: string }) => void) | null = null;
    send = vi.fn();
    close = vi.fn();
    readonly url: string;
    constructor(url: string) {
      this.url = url;
    }
  }
  const videos: Video[] = [];
  class Video {
    muted = false;
    playsInline = false;
    style = { cssText: "" };
    srcObject: unknown = null;
    videoWidth = 400;
    videoHeight = 800;
    setAttribute = vi.fn();
    remove = vi.fn();
    play = vi.fn(async () => {});
    callback: (() => void) | null = null;
    requestVideoFrameCallback(callback: () => void) {
      this.callback = callback;
      return 0;
    }
    constructor() {
      videos.push(this);
    }
  }
  const peers: Peer[] = [];
  class Peer {
    iceGatheringState = "complete";
    connectionState = "connected";
    localDescription = { type: "offer", sdp: "offer-sdp" };
    ontrack: ((event: { streams: unknown[]; track: unknown }) => void) | null = null;
    onconnectionstatechange: (() => void) | null = null;
    close = vi.fn();
    createOffer = vi.fn(async () => this.localDescription);
    setLocalDescription = vi.fn(async () => {});
    setRemoteDescription = vi.fn(async () => {});
    addTransceiver = vi.fn(() => ({ setCodecPreferences: vi.fn() }));
    addEventListener = vi.fn();
    removeEventListener = vi.fn();
    constructor() {
      peers.push(this);
    }
  }
  class MjpegImage extends EventTarget {
    naturalWidth = 0;
    naturalHeight = 0;
    src = "";
    removeAttribute(name: string) {
      if (name === "src") this.src = "";
    }
  }
  vi.stubGlobal("WebSocket", Socket);
  vi.stubGlobal("RTCPeerConnection", Peer);
  vi.stubGlobal("RTCRtpReceiver", { getCapabilities: () => ({ codecs: [] }) });
  vi.stubGlobal("document", { createElement: () => new Video(), body: { append: vi.fn() } });
  // T3 Code's device hub starts serve-sim without --transport, so /api reports "http".
  const fetch = vi.fn((url: string, _init?: RequestInit) =>
    Promise.resolve(
      url.includes("/api?")
        ? Response.json({ stream: { transport: "http", h264Fps: 60 } })
        : url.includes("/webrtc/offer")
          ? Response.json({ type: "answer", sdp: "answer-sdp" })
          : new Response("jpeg"),
    ),
  );
  vi.stubGlobal("fetch", fetch);
  const events = {
    onStatus: vi.fn(),
    onScreen: vi.fn(),
    onUnauthorized: vi.fn(),
    onMjpegFallback: vi.fn(),
    onCanvasVideo: vi.fn(),
    onInputConnected: vi.fn(),
  };
  const present = vi.fn(() => true);
  const client = createDeviceStreamClient(
    {
      platform: "ios",
      deviceId: "sim-1",
      access: {
        httpBase: "http://10.0.2.2:3773/api/device-hub",
        wsBase: "ws://10.0.2.2:3773/api/device-hub",
        credentials: false,
        query: {},
      },
    },
    { present },
    events,
  );
  const image = new MjpegImage();
  client.setMjpegImage(image as unknown as HTMLImageElement);
  client.start();
  await vi.advanceTimersByTimeAsync(0);
  const offers = fetch.mock.calls.filter(([url]) => url.includes("/webrtc/offer"));
  const mjpeg = "http://10.0.2.2:3773/api/device-hub/vendor/serve-sim/helper/sim-1/stream.mjpeg";

  if (process.env.PROOF_EXPECT === "bug") {
    expect(offers).toHaveLength(0);
    expect(peers).toHaveLength(0);
    expect(events.onMjpegFallback).toHaveBeenCalledWith(mjpeg);
    expect(image.src).toBe(mjpeg);
  } else {
    expect(offers.map(([url]) => url)).toEqual([
      "http://10.0.2.2:3773/api/device-hub/vendor/serve-sim/helper/sim-1/webrtc/offer",
    ]);
    expect(peers).toHaveLength(1);
    peers[0]!.ontrack?.({ streams: [{}], track: {} });
    videos[0]!.callback?.();
    expect(present).toHaveBeenCalledWith(videos[0], 400, 800);
    expect(events.onStatus).toHaveBeenLastCalledWith("streaming", undefined);
    await vi.advanceTimersByTimeAsync(20_000);
    expect(events.onMjpegFallback).not.toHaveBeenCalled();
    expect(image.src).toBe("");
  }
  client.stop();
});
EOF
}

run_at() {
  git checkout -q --detach "$1"
  write_test
  local rc=0
  PROOF_EXPECT="$2" vp test run "$TEST" > "$LOG" 2>&1 || rc=$?
  rm -f "$TEST"
  if [ "$rc" -eq 0 ] && ! grep -Eq 'Tests +1 passed' "$LOG"; then rc=3; fi
  if [ "$rc" -ne 0 ]; then sed 's#'"$HOME"'#~#g' "$LOG" | tail -25; fi
  return "$rc"
}

if run_at "$BEFORE" bug; then
  pass "before #41846 ($(git rev-parse --short "$BEFORE")): with no WebCodecs and a hub reporting \"http\", the iOS viewer sends no WebRTC offer and shows the stream.mjpeg image"
else
  fail "before #41846: the no-WebCodecs iOS viewer did not go straight to MJPEG"
fi
if run_at "$MAIN" fixed; then
  pass "main ($(git rev-parse --short "$MAIN")): the same viewer sends one webrtc/offer, paints the WebRTC video, reports streaming, and shows no MJPEG image 20 s later"
else
  fail "main: the no-WebCodecs iOS viewer still does not stream over WebRTC"
fi

if [ "$ok" = 1 ]; then
  echo "VERDICT: #41796 is fixed on main by #41846"
  PROOF_DONE=1; exit 0
fi
echo "VERDICT: not shown"
exit 1
