#!/usr/bin/env bash
set -euo pipefail

if [ "$#" -lt 1 ]; then
  echo "Usage: $0 /home/itahukamedia/public_html/studio.itahukamedia.com/public"
  echo "Example: $0 /home/itahukamedia/public_html/studio.itahukamedia.com/public"
  exit 1
fi

ROOT="$1"
JS="$ROOT/assets/js/modules/coproducer.inline-main.js"

if [ ! -f "$JS" ]; then
  echo "Missing file: $JS" >&2
  exit 1
fi

if ! command -v php >/dev/null 2>&1; then
  echo "ERROR: php CLI not found in PATH." >&2
  exit 1
fi

STAMP="$(date +%Y%m%d_%H%M%S)"
cp -a "$JS" "$JS.bak.$STAMP"
echo "Backup created: $JS.bak.$STAMP"

php <<'PHP' "$JS"
<?php
$path = $argv[1];
$js = file_get_contents($path);
if ($js === false) {
    fwrite(STDERR, "Cannot read: $path\n");
    exit(1);
}

function patch_once(&$text, $search, $replace, $label) {
    if (strpos($text, $replace) !== false) {
        echo "Already patched: $label\n";
        return;
    }
    $count = substr_count($text, $search);
    if ($count !== 1) {
        fwrite(STDERR, "Patch failed for $label: expected 1 exact match, got $count\n");
        exit(1);
    }
    $text = str_replace($search, $replace, $text);
    echo "Patched: $label\n";
}

/*
1) New guest slots must start connected and with camera preview enabled.
*/
$search1 = <<<'TXT'
function allocateSlotForUser(user){
  const existing = findSlotByUid(user.uid);
  if (existing) return existing;

  const empty = slots.find(s => !s.uid);
  if (!empty) return null;

  empty.uid = user.uid;
  empty.name = user.name || user.uid || `G${empty.idx+1}`;
  empty.connected = true;
  empty.hasVideo = false;
  empty.hasAudio = false;
  empty.videoTrack = null;
  empty.audioTrack = null;
  renderUI();
  return empty;
}
TXT;

$replace1 = <<<'TXT'
function allocateSlotForUser(user){
  const existing = findSlotByUid(user.uid);
  if (existing) {
    existing.connected = true;
    if (existing.camPreview !== true) existing.camPreview = true;
    return existing;
  }

  const empty = slots.find(s => !s.uid);
  if (!empty) return null;

  empty.uid = user.uid;
  empty.name = user.name || user.uid || `G${empty.idx+1}`;
  empty.connected = true;
  empty.camPreview = true;
  empty.hasVideo = false;
  empty.hasAudio = false;
  empty.videoTrack = null;
  empty.audioTrack = null;
  renderUI();
  return empty;
}
TXT;

patch_once($js, $search1, $replace1, 'allocateSlotForUser auto-enable preview');

/*
2) When a video track subscribes, force the guest slot preview on.
*/
$search2 = <<<'TXT'
      if (track.kind === "video"){
        s.videoTrack = track;
        s.hasVideo = true;
      }else if (track.kind === "audio"){
TXT;

$replace2 = <<<'TXT'
      if (track.kind === "video"){
        s.videoTrack = track;
        s.hasVideo = true;
        s.connected = true;
        s.camPreview = true;
      }else if (track.kind === "audio"){
TXT;

patch_once($js, $search2, $replace2, 'TrackSubscribed force guest preview on');

/*
3) When participant metadata arrives with existing video publications, keep preview enabled.
*/
$search3 = <<<'TXT'
      const s = findSlotByUid(uid) || allocateSlotForUser({ uid });
      if (!s) return;

      const vTrack = getParticipantVideoTrack(participant);
      const aTrack = getParticipantAudioTrack(participant);

      if (vTrack){
        s.videoTrack = vTrack;
        s.hasVideo = true;
      }
TXT;

$replace3 = <<<'TXT'
      const s = findSlotByUid(uid) || allocateSlotForUser({ uid });
      if (!s) return;

      s.connected = true;
      s.camPreview = true;

      const vTrack = getParticipantVideoTrack(participant);
      const aTrack = getParticipantAudioTrack(participant);

      if (vTrack){
        s.videoTrack = vTrack;
        s.hasVideo = true;
        s.camPreview = true;
      }
TXT;

patch_once($js, $search3, $replace3, 'existing participant seed keeps preview on');

/*
4) Prevent studio-return from being shown as guest name if it somehow enters slots.
*/
$search4 = <<<'TXT'
  empty.name = user.name || user.uid || `G${empty.idx+1}`;
TXT;

$replace4 = <<<'TXT'
  empty.name = (user.uid === "studio-return") ? "Remote: studio-return" : (user.name || user.uid || `G${empty.idx+1}`);
TXT;

patch_once($js, $search4, $replace4, 'studio-return display name');

/*
5) Defensive render path: if there is videoTrack+hasVideo, do not leave tile off merely because camPreview was undefined.
*/
$search5 = <<<'TXT'
    scr.className = "screen" + (s.camPreview && s.hasVideo ? "" : " off");
TXT;

$replace5 = <<<'TXT'
    const __camPreviewOn = (s.camPreview !== false);
    scr.className = "screen" + (__camPreviewOn && s.hasVideo ? "" : " off");
TXT;

patch_once($js, $search5, $replace5, 'renderUI camPreview default-on');

/*
6) Defensive mount path mirrors same logic.
*/
$search6 = <<<'TXT'
    if (s.connected && s.hasVideo && s.camPreview && s.videoTrack){
      mountVideoInto(scr, s.videoTrack, true);
TXT;

$replace6 = <<<'TXT'
    if (s.connected && s.hasVideo && (s.camPreview !== false) && s.videoTrack){
      mountVideoInto(scr, s.videoTrack, true);
TXT;

patch_once($js, $search6, $replace6, 'renderUI mount path default-on');

if (file_put_contents($path, $js) === false) {
    fwrite(STDERR, "Cannot write: $path\n");
    exit(1);
}

echo "Done: $path\n";
PHP

echo
echo "Patch complete."
echo
echo "Hard refresh coproducer.php after this."
echo
echo "Verification:"
echo "grep -n 'camPreview = true\\|camPreview !== false\\|allocateSlotForUser\\|TrackSubscribed force guest preview on' \"$JS\""