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

ROOT="${1:-/home/itahukamedia/public_html/studio.itahukamedia.com/public}"
JS="$ROOT/assets/js/modules/coproducer.inline-main.js"

if [ ! -f "$JS" ]; then
  echo "File not found: $JS" >&2
  exit 1
fi

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

# 1) Add scheduler before ensureStudioReturnPublish() if not already present
if ! grep -q "function scheduleStudioReturnRepublish" "$JS"; then
  perl -0pi -e '
    s/async function ensureStudioReturnPublish\(\)\{\n  await ensureStudioReturnAudio\(\);\n  await refreshStudioReturnVideo\(\);\n\}/let __studioReturnRepublishTimer = 0;\n\nfunction scheduleStudioReturnRepublish(delay){\n  const d = Math.max(80, Number(delay || 180));\n  try{ if (__studioReturnRepublishTimer) clearTimeout(__studioReturnRepublishTimer); }catch(_){ }\n  __studioReturnRepublishTimer = setTimeout(()=>{\n    __studioReturnRepublishTimer = 0;\n    Promise.resolve().then(()=>ensureStudioReturnPublish()).catch(()=>{});\n  }, d);\n}\n\nasync function ensureStudioReturnPublish(){\n  await ensureStudioReturnAudio();\n  await refreshStudioReturnVideo();\n}/s;
  ' "$JS"
fi

# 2) Replace direct republish calls in TAKE hook
perl -0pi -e '
  s/requestAnimationFrame\(\(\)=>\{\s*try\{\s*ensureStudioReturnPublish\(\);\s*\}catch\(_\)\{\}\s*\}\);/requestAnimationFrame(()=>{\n      try{ scheduleStudioReturnRepublish(320); }catch(_){ }\n    });/s;
' "$JS"

# 3) Replace generic direct calls with scheduled calls
perl -0pi -e '
  s/\bawait ensureStudioReturnPublish\(\);/scheduleStudioReturnRepublish(220);/g;
  s/(?<!await )\bensureStudioReturnPublish\(\);/scheduleStudioReturnRepublish(220);/g;
' "$JS"

# 4) Remove forced republish line inside updateOnAirPanel only
perl -0pi -e '
  s/\n\s*try\{\s*Promise\.resolve\(\)\.then\(\(\)=>scheduleStudioReturnRepublish\(220\)\)\.catch\(\(\)=>\{\}\);\s*\}catch\(_\)\{\s*\}\n/\n/s;
  s/\n\s*try\{\s*Promise\.resolve\(\)\.then\(\(\)=>ensureStudioReturnPublish\(\)\)\.catch\(\(\)=>\{\}\);\s*\}catch\(_\)\{\s*\}\n/\n/s;
' "$JS"

chmod 0644 "$JS"

echo
echo "Patch complete."
echo
echo "Verify:"
grep -n "scheduleStudioReturnRepublish" "$JS" || true
grep -n "ensureStudioReturnPublish" "$JS" || true
grep -n "requestAnimationFrame" "$JS" | grep -n "scheduleStudioReturnRepublish" || true
echo
echo "Hard-refresh BOTH:"
echo "  - coproducer.php"
echo "  - join.php"