{ config, lib, pkgs, pkgs-unstable, artifacts, ... }:
with artifacts;
{
  openbox-with-chrome = mkBoundLauncher {
    name = "openbox-with-chrome";
    runtimeInputs = [ pkgs.openbox pkgs.coreutils pkgs.curl pkgs.python3 pkgs.util-linux ];
    script = ''
      set -euo pipefail

      chromeProfileDir="${config.xdg.cacheHome}/desktop-0-google-chrome-profile"
      chromeLogDir="${config.xdg.stateHome}/chrome-remote-desktop"
      chromeLogFile="$chromeLogDir/google-chrome.log"
      chromeWidth=1080
      chromeHeight=1920
      chromeCdpBase="http://${serviceLoopbackBindHostIPv4}:9222"
      healthCheckIntervalSeconds=10
      stalledTargetThresholdSeconds=120
      stalledRestartProfileResetThreshold=2
      consecutiveStallRestarts=0
      localStateResetAttempted=0
      hadBadNetworkTargets=0
      declare -A bad_network_target_since=()
      mkdir -p "$chromeProfileDir" "$chromeLogDir"

      wait_for_cdp_state() {
        local expected_state="''${1:-up}"
        local attempts="''${2:-50}"
        local i=0

        while (( i < attempts )); do
          if curl --max-time 1 -fsS "$chromeCdpBase/json/version" >/dev/null 2>&1; then
            if [[ "$expected_state" == "up" ]]; then
              return 0
            fi
          else
            if [[ "$expected_state" == "down" ]]; then
              return 0
            fi
          fi
          i=$((i + 1))
          sleep 0.2
        done

        return 1
      }

      ensure_regular_page_target() {
        local json has_regular_page

        json="$(curl --max-time 3 -fsS "$chromeCdpBase/json/list" 2>/dev/null)" || return 0
        has_regular_page="$(python3 -c '
import json
import sys

try:
    targets = json.load(sys.stdin)
except Exception:
    print("0")
    raise SystemExit(0)

for target in targets:
    if target.get("type") != "page":
        continue
    url = target.get("url", "")
    if url.startswith("chrome://newtab"):
        continue
    print("1")
    raise SystemExit(0)

print("0")
' <<<"$json")"

        if [[ "$has_regular_page" != "1" ]]; then
          curl --max-time 3 -fsS "$chromeCdpBase/json/new?about:blank" >/dev/null 2>&1 || true
          sleep 0.2
        fi
      }

      reset_local_state() {
        local local_state stamp backup
        local_state="$chromeProfileDir/Local State"
        if [[ -e "$local_state" ]]; then
          stamp="$(date +%Y%m%d-%H%M%S)"
          backup="$chromeLogDir/local-state-bad-$stamp.json"
          mv "$local_state" "$backup"
          echo "[openbox-with-chrome] Reset Chrome Local State; backup: $backup" >&2
        fi
      }

      archive_profile_dir() {
        if [[ -d "$chromeProfileDir" ]]; then
          local stamp archive_dir
          stamp="$(date +%Y%m%d-%H%M%S)"
          archive_dir="${config.xdg.stateHome}/chrome-remote-desktop/google-chrome-profile-bad-$stamp"
          mv "$chromeProfileDir" "$archive_dir"
          echo "[openbox-with-chrome] Archived unhealthy Chrome profile to $archive_dir" >&2
        fi
        mkdir -p "$chromeProfileDir"
      }

      start_chrome() {
        rm -f "$chromeProfileDir/SingletonLock" "$chromeProfileDir/SingletonCookie" "$chromeProfileDir/SingletonSocket"
        rm -f "$chromeProfileDir/Default/Current Session" "$chromeProfileDir/Default/Current Tabs" \
          "$chromeProfileDir/Default/Last Session" "$chromeProfileDir/Default/Last Tabs"
        rm -rf "$chromeProfileDir/Default/Sessions"
        bad_network_target_since=()
        hadBadNetworkTargets=0
        : > "$chromeLogFile"

        setsid "${artifacts.mainDesktopChromeExe}" \
          --remote-debugging-port=9222 \
          --remote-debugging-address=${serviceLoopbackBindHostIPv4} \
          --user-data-dir="$chromeProfileDir" \
          --load-extension=${artifacts.chromiumFingerprintGuard} \
          --proxy-server="direct://" \
          --proxy-bypass-list="*" \
          --start-maximized \
          --window-position=0,0 \
          --window-size="$chromeWidth,$chromeHeight" \
          --force-device-scale-factor=1 \
          --disable-gpu \
          --disable-backgrounding-occluded-windows \
          --disable-renderer-backgrounding \
          --disable-background-timer-throttling \
          --no-first-run --no-default-browser-check \
          --disable-session-crashed-bubble \
          --disable-infobars \
          --no-sandbox \
          about:blank \
          >>"$chromeLogFile" 2>&1 &
        chrome_pid=$!

        if ! wait_for_cdp_state up 75; then
          echo "[openbox-with-chrome] Chrome did not bring up CDP on $chromeCdpBase after restart" >&2
        fi
        ensure_regular_page_target
      }

      stop_chrome() {
        local pid="''${1:-}"
        if [[ -z "$pid" ]]; then
          return 0
        fi

        kill -- -"$pid" 2>/dev/null || kill "$pid" 2>/dev/null || true
        wait "$pid" 2>/dev/null || true
        wait_for_cdp_state down 25 || true
      }

      restart_chrome() {
        local reason="''${1:-Chrome restart requested}"
        echo "[openbox-with-chrome] $reason" >&2
        stop_chrome "''${chrome_pid:-}"
        start_chrome
      }

      check_for_stalled_network_targets() {
        local json now line id url title
        local -a bad_targets=()
        local -A current_bad=()

        json="$(curl --max-time 5 -fsS http://${serviceLoopbackBindHostIPv4}:9222/json/list 2>/dev/null)" || return 0
        mapfile -t bad_targets < <(
          python3 -c '
import json
import sys

try:
    targets = json.load(sys.stdin)
except Exception:
    sys.exit(0)

for target in targets:
    if target.get("type") != "page":
        continue
    url = target.get("url", "")
    if not (url.startswith("http://") or url.startswith("https://")):
        continue
    title = target.get("title", "")
    if title in ("", "New Tab", "about:blank") or title.startswith("Loading"):
        print("{}\t{}\t{}".format(target.get("id", ""), url, title))
' <<<"$json"
        )

        hadBadNetworkTargets=0
        if (( ''${#bad_targets[@]} > 0 )); then
          hadBadNetworkTargets=1
        fi

        now="$(date +%s)"
        for line in "''${bad_targets[@]}"; do
          IFS=$'\t' read -r id url title <<<"$line"
          [[ -n "$id" ]] || continue
          current_bad["$id"]=1
          if [[ -z "''${bad_network_target_since[$id]+x}" ]]; then
            bad_network_target_since["$id"]="$now"
            continue
          fi
          if (( now - bad_network_target_since[$id] >= stalledTargetThresholdSeconds )); then
            echo "[openbox-with-chrome] Stalled network target for $((now - bad_network_target_since[$id]))s: $url (title=''${title:-<empty>})" >&2
            return 1
          fi
        done

        for id in "''${!bad_network_target_since[@]}"; do
          [[ -n "''${current_bad[$id]+x}" ]] || unset 'bad_network_target_since[$id]'
        done

        return 0
      }

      # shellcheck disable=SC2317
      stop_pid() {
        local pid="''${1:-}"
        if [[ -n "$pid" ]]; then
          kill "$pid" 2>/dev/null || true
          wait "$pid" 2>/dev/null || true
        fi
      }

      # shellcheck disable=SC2317
      cleanup() {
        stop_chrome "''${chrome_pid:-}"
        stop_pid "''${openbox_pid:-}"
      }
      trap cleanup EXIT

      "${pkgs.openbox}/bin/openbox" &
      openbox_pid=$!

      start_chrome
      health_check_elapsed=0

      while kill -0 "$openbox_pid" 2>/dev/null; do
        if ! kill -0 "$chrome_pid" 2>/dev/null; then
          wait "$chrome_pid" 2>/dev/null || true
          restart_chrome "Google Chrome exited; restarting"
          health_check_elapsed=0
          sleep 1
          continue
        fi

        health_check_elapsed=$((health_check_elapsed + 1))
        if (( health_check_elapsed >= healthCheckIntervalSeconds )); then
          health_check_elapsed=0
          if ! check_for_stalled_network_targets; then
            consecutiveStallRestarts=$((consecutiveStallRestarts + 1))
            if (( consecutiveStallRestarts >= stalledRestartProfileResetThreshold )); then
              stop_chrome "$chrome_pid"
              if (( localStateResetAttempted == 0 )); then
                echo "[openbox-with-chrome] Repeated stalled navigation detected; resetting Chrome Local State" >&2
                reset_local_state
                localStateResetAttempted=1
              else
                echo "[openbox-with-chrome] Repeated stalled navigation persists after Local State reset; rebuilding Chrome profile" >&2
                archive_profile_dir
                localStateResetAttempted=0
              fi
              consecutiveStallRestarts=0
              start_chrome
              sleep 1
              continue
            fi
            restart_chrome "Restarting Google Chrome after stalled network navigation detection"
            sleep 1
            continue
          fi
          if (( hadBadNetworkTargets == 0 )); then
            consecutiveStallRestarts=0
            localStateResetAttempted=0
          fi
        fi

        sleep 1
      done

      openbox_status=0
      wait "$openbox_pid" || openbox_status=$?
      exit "$openbox_status"
    '';
  };
}
