#!/usr/bin/env bash
# Opens the DANKE HMI Control Center as an app window.
# This is what the "DANKE HMI" entry in the application menu runs.
set -u
PORT="${DANKE_PORT:-8765}"
URL="http://127.0.0.1:${PORT}/setup"

up() {
  if command -v curl >/dev/null 2>&1; then
    curl -fsS --max-time 1 "http://127.0.0.1:${PORT}/api/health" >/dev/null 2>&1
  else
    python3 - "$PORT" >/dev/null 2>&1 <<'PY'
import sys, urllib.request
urllib.request.urlopen(f"http://127.0.0.1:{sys.argv[1]}/api/health", timeout=1)
PY
  fi
}

if ! up; then
  systemctl --user start danke-hmi.service >/dev/null 2>&1 || true
  for _ in $(seq 1 60); do up && break; sleep 0.25; done
fi

if ! up; then
  # Show a readable page with the reason instead of a browser error.
  PAGE="${XDG_RUNTIME_DIR:-/tmp}/danke-hmi-offline.html"
  LOGS="$(journalctl --user -u danke-hmi.service -n 25 --no-pager -o cat 2>/dev/null \
          | sed -e 's/&/\&amp;/g' -e 's/</\&lt;/g' -e 's/>/\&gt;/g')"
  cat > "$PAGE" <<HTML
<!doctype html><meta charset="utf-8"><title>DANKE HMI</title>
<style>body{margin:0;background:#0b0c0f;color:#ecebe6;font:15px/1.5 system-ui,sans-serif;padding:40px}
.h{height:6px;background:repeating-linear-gradient(135deg,#ffd600 0 14px,#000 14px 28px);margin:-40px -40px 32px}
h1{font-size:22px}code,pre{font-family:ui-monospace,monospace}code{background:#1b1e23;padding:3px 7px;border-radius:6px}
pre{background:#000;border:1px solid #23272e;border-radius:10px;padding:14px;white-space:pre-wrap;color:#c9ccd2;max-height:50vh;overflow:auto}</style>
<div class="h"></div>
<h1>DANKE HMI n'a pas pu démarrer</h1>
<p>Le plus simple : ouvre un terminal et lance <code>danke-hmi-repair</code>. Il réinstalle ce qui manque et redémarre le service.</p>
<p>Si ça ne suffit pas, envoie ce journal à celui qui t'aide :</p>
<pre>${LOGS:-(journal vide)}</pre>
HTML
  URL="file://${PAGE}"
fi

launch() { setsid -f "$@" >/dev/null 2>&1 < /dev/null; exit 0; }

# 1. Omarchy's own web-app launcher (app window, own icon in the dock)
command -v omarchy-launch-webapp >/dev/null 2>&1 && [ "${URL#file:}" = "$URL" ] && launch omarchy-launch-webapp "$URL"
# 2. Any Chromium-family browser in --app mode = a real app window, no tabs, no URL bar
for b in chromium chromium-browser brave brave-browser google-chrome-stable google-chrome \
         vivaldi-stable vivaldi microsoft-edge-stable thorium-browser helium-browser; do
  command -v "$b" >/dev/null 2>&1 && launch "$b" --app="$URL" --class=danke-hmi --window-size=1180,860
done
# 3. Firefox has no app mode: a plain window
for b in firefox librewolf zen-browser; do
  command -v "$b" >/dev/null 2>&1 && launch "$b" --new-window "$URL"
done
# 4. Whatever the desktop uses for links
command -v xdg-open >/dev/null 2>&1 && launch xdg-open "$URL"
echo "Ouvre ${URL} dans un navigateur."
