#!/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) Disable host auto-selection logic globally.
Only a fixed host should be treated as host.
*/
$search1 = <<<'TXT'
function isHostUid(uid){
  const u = safeUid(uid);
  if (HOST_FIXED) return u === safeUid(HOST_UID);
  return (HOST_AUTO_UID !== null) && (u === safeUid(HOST_AUTO_UID));
}
TXT;

$replace1 = <<<'TXT'
function isHostUid(uid){
  const u = safeUid(uid);
  if (HOST_FIXED) return u === safeUid(HOST_UID);
  return false;
}
TXT;

patch_once($js, $search1, $replace1, 'disable isHostUid auto-host');

/*
2) Remove eager auto-host assignment on participant presence / existing tracks.
This is the block you previously saw around line ~2411.
*/
$search2 = <<<'TXT'
      if (!HOST_FIXED && HOST_AUTO_UID === null && p.videoTrackPublications && p.videoTrackPublications.size > 0){
        HOST_AUTO_UID = uid;
        if (hostLbl) hostLbl.textContent = String(uid);
      }
TXT;

$replace2 = <<<'TXT'
      // auto-host assignment disabled: guests must remain in G1-G5 slots
TXT;

patch_once($js, $search2, $replace2, 'remove participant auto-host assignment');

/*
3) Remove eager auto-host assignment on TrackSubscribed.
This is the exact defect from your snippet.
*/
$search3 = <<<'TXT'
      // AUTO host selection on first subscribed video
      if (!HOST_FIXED && HOST_AUTO_UID === null && track.kind === "video"){
        HOST_AUTO_UID = uid;
        if (hostLbl) hostLbl.textContent = String(uid);
      }
TXT;

$replace3 = <<<'TXT'
      // auto-host assignment disabled: subscribed guest video must remain in guest slots
TXT;

patch_once($js, $search3, $replace3, 'remove TrackSubscribed auto-host assignment');

/*
4) Prevent studio-return from ever being treated like a guest identity.
*/
$search4 = <<<'TXT'
function isGuestIdentity(v){
  const s = String(v || "").trim();
  return !!s && /^guest-/i.test(s);
}
TXT;

$replace4 = <<<'TXT'
function isGuestIdentity(v){
  const s = String(v || "").trim();
  if (!s) return false;
  if (s === "studio-return") return false;
  return /^guest-/i.test(s);
}
TXT;

patch_once($js, $search4, $replace4, 'exclude studio-return from guest identities');

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 "Now hard-refresh coproducer.php with Ctrl+F5 / Shift+Reload."
echo "Then retest a guest join."
echo
echo "Quick verification commands:"
echo "grep -n 'AUTO host selection on first subscribed video\\|HOST_AUTO_UID\\|function isHostUid\\|function isGuestIdentity' \"$JS\""