#!/usr/bin/env bash
# Voeg webbuilder toe aan Herman orchestrator op VM105
set -euo pipefail

ORCH_HOST="${ORCH_HOST:-aissa@10.4.7.19}"
MAIN="$HOME/foodlinkk-ai/herman-orchestrator/main.py"

ssh -o StrictHostKeyChecking=no "$ORCH_HOST" bash -s <<'REMOTE'
set -euo pipefail
MAIN=~/foodlinkk-ai/herman-orchestrator/main.py
cp "$MAIN" "${MAIN}.bak.$(date +%Y%m%d%H%M)"

python3 <<'PY'
from pathlib import Path
p = Path.home() / "foodlinkk-ai/herman-orchestrator/main.py"
text = p.read_text()

if "webbuilder" in text and '"webbuilder"' in text:
    print("webbuilder already present")
else:
    text = text.replace(
        '    "browser",\n)',
        '    "browser",\n    "webbuilder",\n)',
    )
    insert = '''    "webbuilder": {
        "name": "Web Builder",
        "persona": (
            "Website development via Hermes/agy on NAS. HTML/CSS/JS sites, "
            "landing pages, preview servers. Reports back to Herman when done."
        ),
        "keywords": "website,bouw website,maak website,landingspagina,webbuilder,webpagina,nieuwe site",
    },
'''
    marker = '    "browser": {'
    if insert.strip() not in text:
        text = text.replace(marker, insert + marker, 1)

    text = text.replace(
        '"keywords": "website,browser,site,monitor,crawl,bidfood,web,url",',
        '"keywords": "browser,site,monitor,crawl,bidfood,url,concurrent,scrape",',
    )
    p.write_text(text)
    print("patched orchestrator main.py")
PY

# Restart orchestrator if systemd service exists
if systemctl is-active herman-orchestrator >/dev/null 2>&1; then
  sudo systemctl restart herman-orchestrator
elif pgrep -f "herman-orchestrator/main.py" >/dev/null; then
  pkill -f "herman-orchestrator/main.py" || true
  sleep 1
  cd ~/foodlinkk-ai/herman-orchestrator && nohup python3 -m uvicorn main:app --host 0.0.0.0 --port 8090 >> /tmp/herman-orchestrator.log 2>&1 &
fi
sleep 2
curl -sf http://127.0.0.1:8090/health | python3 -c "import sys,json; d=json.load(sys.stdin); print('agents:', d.get('agents'))"
REMOTE
