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

BASE="/home/yeff/public_html/devon"
JS="$BASE/panel/assets/js/panel.runtime.fix.20260408_1.js"
SRC="$BASE/_backup/panel.runtime.fix.20260408_1.js.center_content_20260409_173857.bak"
SAFE="$BASE/_backup/panel.runtime.fix.20260408_1.js.restore_boot_from_center_content_$(date +%Y%m%d_%H%M%S).bak"

cp -av "$JS" "$SAFE"

python3 - <<'PY'
from pathlib import Path
import re
import sys

js = Path("/home/yeff/public_html/devon/panel/assets/js/panel.runtime.fix.20260408_1.js")
src = Path("/home/yeff/public_html/devon/_backup/panel.runtime.fix.20260408_1.js.center_content_20260409_173857.bak")

if not src.exists():
    print("FAIL missing source backup:", src)
    sys.exit(1)

active = js.read_text()
source = src.read_text()

if re.search(r'\bfunction\s+boot\s*\(', active):
    print("PASS active already has function boot(); no injection needed")
    sys.exit(0)

m = re.search(r'\bfunction\s+boot\s*\(\)\s*\{', source)
if not m:
    print("FAIL source backup has no function boot()")
    sys.exit(1)

start = m.start()
brace_pos = source.find("{", m.start())
depth = 0
in_str = None
escape = False
end = None

for i in range(brace_pos, len(source)):
    ch = source[i]
    if in_str:
        if escape:
            escape = False
        elif ch == "\\":
            escape = True
        elif ch == in_str:
            in_str = None
        continue
    if ch in ("'", '"', "`"):
        in_str = ch
        continue
    if ch == "{":
        depth += 1
    elif ch == "}":
        depth -= 1
        if depth == 0:
            end = i + 1
            break

if end is None:
    print("FAIL could not close function boot() from source backup")
    sys.exit(1)

boot_src = source[start:end].rstrip() + "\n\n"

marker = "boot();"
pos = active.rfind(marker)
if pos == -1:
    print("FAIL active file missing boot() call")
    sys.exit(1)

patched = active[:pos] + boot_src + active[pos:]
js.write_text(patched)
print("PASS restored function boot() from", src)
PY

echo
echo "=== validation ==="
grep -n 'function boot' "$JS" || true
grep -n 'boot();' "$JS" || true
grep -n 'function selectStage(stageKey)' "$JS" || true
grep -n 'function renderCanonicalSelection()' "$JS" || true
nl -ba "$JS" | sed -n '680,780p'
