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

ROOT="${1:-}"
if [ -z "$ROOT" ]; then
  echo "Usage: $0 /home/itahukamedia/public_html/studio.itahukamedia.com/public"
  exit 1
fi

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

if [ ! -f "$PHPF" ]; then
  echo "Missing file: $PHPF"
  exit 1
fi

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

TS="$(date +%Y%m%d_%H%M%S)"
cp -p "$PHPF" "$PHPF.bak.$TS"
cp -p "$JS" "$JS.bak.$TS"

echo "Backups created:"
echo "  $PHPF.bak.$TS"
echo "  $JS.bak.$TS"

python3 - "$PHPF" "$JS" <<'PY'
import re
import sys
from pathlib import Path

php_path = Path(sys.argv[1])
js_path = Path(sys.argv[2])

php = php_path.read_text(encoding="utf-8")
js = js_path.read_text(encoding="utf-8")

orig_php = php
orig_js = js

# ------------------------------------------------------------
# 1) Remove Monitor button from coproducer.php only
# ------------------------------------------------------------
php = re.sub(
    r'\s*<button class="btnMon" id="btnMonitor" type="button" title="Monitor source">MONITOR: ON AIR</button>\s*',
    '\n',
    php,
    count=1,
    flags=re.S
)

# ------------------------------------------------------------
# 2) Neutralize monitor element lookup
# ------------------------------------------------------------
js = re.sub(
    r'const btnMonitor = document\.getElementById\("btnMonitor"\);',
    'const btnMonitor = null;',
    js,
    count=1
)

# ------------------------------------------------------------
# 3) Force fixed monitor mode and kill persistence
# ------------------------------------------------------------
js = re.sub(
    r'let monitorMode = "onair";\s*// "onair" \| "preview"',
    'let monitorMode = "onair"; // fixed: program audio only, preview silent',
    js,
    count=1
)

js = re.sub(
    r'function loadMonitor\(\)\{\s*try\{\s*const v = localStorage\.getItem\(MONITOR_STORE_KEY\);\s*if \(v === "preview" \|\| v === "onair"\) monitorMode = v;\s*\}catch\(_\)\{\}\s*\}',
    '''function loadMonitor(){
  monitorMode = "onair";
}''',
    js,
    count=1,
    flags=re.S
)

js = re.sub(
    r'function saveMonitor\(\)\{\s*try\{\s*localStorage\.setItem\(MONITOR_STORE_KEY, monitorMode\);\s*\}catch\(_\)\{\}\s*\}',
    '''function saveMonitor(){
  monitorMode = "onair";
}''',
    js,
    count=1,
    flags=re.S
)

js = re.sub(
    r'function applyMonitorUi\(\)\{\s*if \(!btnMonitor\) return;\s*btnMonitor\.textContent = \(monitorMode === "preview"\) \? "MONITOR: PREVIEW" : "MONITOR: ON AIR";\s*btnMonitor\.setAttribute\("aria-pressed", monitorMode === "preview" \? "true" : "false"\);\s*\}',
    '''function applyMonitorUi(){
  monitorMode = "onair";
}''',
    js,
    count=1,
    flags=re.S
)

# ------------------------------------------------------------
# 4) Remove Monitor click handler block entirely
# ------------------------------------------------------------
js = re.sub(
    r'if \(btnMonitor\)\{\s*btnMonitor\.addEventListener\("click",\s*\(\)=>\{\s*monitorMode = \(monitorMode === "onair"\) \? "preview" : "onair";\s*saveMonitor\(\);\s*applyMonitorUi\(\);\s*// Re-render both sides so media elements connect to the correct monitor target\.\s*updatePreviewPanel\(\);\s*(?:updateOnAirPanel\(\);\s*)?\}\);\s*\}',
    '',
    js,
    count=1,
    flags=re.S
)

# ------------------------------------------------------------
# 5) Force audio routing:
#    - preview silent
#    - program audible
# ------------------------------------------------------------
js = js.replace(
    'const hear = (src.type === "media") ? true : ((monitorMode === "preview") ? !!isPreview : !isPreview);',
    'const hear = !isPreview;',
)
js = js.replace(
    'const hear = (src.type ==="media") ? true : ((monitorMode === "preview") ? !!isPreview : !isPreview);',
    'const hear = !isPreview;',
)

# ------------------------------------------------------------
# 6) Remove monitor field from stream payload
# ------------------------------------------------------------
js = re.sub(
    r'\s*monitor:\s*\(typeof monitorMode\s*!==\s*"undefined"\s*\?\s*monitorMode\s*:\s*"onair"\),\n',
    '\n',
    js,
    count=1
)

# ------------------------------------------------------------
# 7) Clean duplicated startup calls harmlessly by forcing fixed mode
# ------------------------------------------------------------
# Keep existing loadMonitor/applyMonitorUi calls; they now do nothing harmful.

if php == orig_php:
    print("WARNING: coproducer.php Monitor button line was not changed")
else:
    print("Patched: removed Monitor button from coproducer.php")

if js == orig_js:
    print("WARNING: JS file was not changed")
else:
    print("Patched: fixed monitor mode to permanent onair/program")
    print("Patched: removed monitor click toggle")
    print("Patched: forced preview silent / program audible")
    print("Patched: removed monitor field from stream payload")

php_path.write_text(php, encoding="utf-8")
js_path.write_text(js, encoding="utf-8")
PY

echo
echo "Syntax check:"
php -l "$PHPF"

echo
echo "Verify key lines:"
grep -n 'btnMonitor\|monitorMode\|function loadMonitor\|function saveMonitor\|function applyMonitorUi\|const hear = !isPreview\|btnTake.onclick\|monitor:' "$JS" || true

echo
echo "Done."
echo
echo "Hard-refresh ONLY:"
echo "  - coproducer.php"
echo
echo "Expected:"
echo "  - MONITOR button removed"
echo "  - Preview is always silent"
echo "  - Program / On Air / Master Out carries audio"
echo "  - TAKE remains the only commit action from Preview -> Program"
