{ config, lib, pkgs, pkgs-unstable, artifacts, ... }:
with artifacts;

let
  defaultRedirectUrl = "https://remotedesktop.google.com/_/oauthredirect";
in {
  chromeRemoteDesktopEnroll = pkgs.writeShellApplication {
    name = "chrome-remote-desktop-enroll";
    runtimeInputs = with pkgs; [
      coreutils
      curl
      gnugrep
      jq
      python3
      systemd
    ];
    text = ''
      set -euo pipefail

      service_unit=${lib.escapeShellArg artifacts.serviceUnits.chromeRemoteDesktop}
      cfg_dir="$HOME/.config/chrome-remote-desktop"
      default_redirect_url=${lib.escapeShellArg defaultRedirectUrl}
      default_host_name="$(cat /proc/sys/kernel/hostname 2>/dev/null || echo chrome-remote-desktop)"

      usage() {
        cat <<EOF
Usage:
  chrome-remote-desktop-enroll --code <oauth-code> --pin <6+ digit pin> [--name <host-name>] [--redirect-url <url>]
  chrome-remote-desktop-enroll --command '<command copied from remotedesktop.google.com/headless>' --pin <6+ digit pin>

Recommended flow:
  1. Open https://remotedesktop.google.com/headless
  2. Sign in with the Google account that should own this host
  3. Copy the generated command (or just the --code value)
  4. Run chrome-remote-desktop-enroll with that code and your chosen PIN
  5. Connect later at https://remotedesktop.google.com/access

Notes:
  - No inbound firewall ports need to be opened for Chrome Remote Desktop.
  - This wrapper uses the official enrollment helper but starts ${artifacts.serviceNames.chromeRemoteDesktop}
    itself, so the upstream /usr/bin/sudo auto-start failure is treated as non-fatal
    when the host config was written successfully.
  - If enrollment succeeds, the desktop browser will be available locally on
    http://127.0.0.1:9222 via the ${artifacts.serviceNames.chromeRemoteDesktop} service.
EOF
      }

      collect_snapshot() {
        shopt -s nullglob
        local files=("$cfg_dir"/host#*.json)
        shopt -u nullglob
        if [ "''${#files[@]}" -eq 0 ]; then
          return 0
        fi
        sha256sum "''${files[@]}"
      }

      code=""
      pin=""
      redirect_url="$default_redirect_url"
      host_name="$default_host_name"
      pasted_command=""

      while [ "$#" -gt 0 ]; do
        case "$1" in
          --code)
            code="''${2:-}"
            shift 2
            ;;
          --pin)
            pin="''${2:-}"
            shift 2
            ;;
          --redirect-url)
            redirect_url="''${2:-}"
            shift 2
            ;;
          --name)
            host_name="''${2:-}"
            shift 2
            ;;
          --command)
            pasted_command="''${2:-}"
            shift 2
            ;;
          -h|--help)
            usage
            exit 0
            ;;
          *)
            echo "chrome-remote-desktop-enroll: unknown argument: $1" >&2
            usage >&2
            exit 1
            ;;
        esac
      done

      if [ -n "$pasted_command" ]; then
        mapfile -t parsed < <(python3 - "$pasted_command" <<'PY'
import shlex
import sys

command = sys.argv[1]
parts = shlex.split(command)
code = ""
redirect = ""
name = ""

i = 0
while i < len(parts):
    part = parts[i]

    def take_value(current_index):
        current = parts[current_index]
        if "=" in current:
            return current.split("=", 1)[1], current_index
        if current_index + 1 < len(parts):
            return parts[current_index + 1], current_index + 1
        return "", current_index

    if part.startswith("--code"):
        code, i = take_value(i)
    elif part.startswith("--redirect-url"):
        redirect, i = take_value(i)
    elif part.startswith("--name") or part.startswith("--display-name"):
        name, i = take_value(i)
    i += 1

print(code)
print(redirect)
print(name)
PY
)
        if [ -z "$code" ] && [ -n "''${parsed[0]:-}" ]; then
          code="''${parsed[0]}"
        fi
        if [ "$redirect_url" = "$default_redirect_url" ] && [ -n "''${parsed[1]:-}" ]; then
          redirect_url="''${parsed[1]}"
        fi
        if [ "$host_name" = "$default_host_name" ] && [ -n "''${parsed[2]:-}" ] && ! printf '%s\n' "''${parsed[2]}" | grep -qx "\$(hostname)"; then
          host_name="''${parsed[2]}"
        fi
      fi

      [ -n "$code" ] || {
        echo "chrome-remote-desktop-enroll: missing --code (or parseable --command)." >&2
        usage >&2
        exit 1
      }

      if ! [[ "$pin" =~ ^[0-9]{6,}$ ]]; then
        echo "chrome-remote-desktop-enroll: PIN must be 6 or more digits." >&2
        exit 1
      fi

      mkdir -p "$cfg_dir"
      before_snapshot="$(collect_snapshot || true)"
      tmpdir="${TMPDIR:-/tmp}"
      workdir="$tmpdir/chrome-remote-desktop-enroll"
      mkdir -p "$workdir"
      log_file="$workdir/$(date +%Y%m%dT%H%M%S).log"

      run_helper() {
        local name_flag="$1"
        env DISPLAY= ${lib.getExe chrome-remote-desktop-start-host} \
          --code="$code" \
          --redirect-url="$redirect_url" \
          "$name_flag"="$host_name" \
          --pin="$pin"
      }

      echo "Running official CRD enrollment helper..."
      set +e
      run_helper --name >"$log_file" 2>&1
      status=$?
      set -e

      after_snapshot="$(collect_snapshot || true)"
      config_changed=0
      if [ -n "$after_snapshot" ] && [ "$before_snapshot" != "$after_snapshot" ]; then
        config_changed=1
      fi

      if [ "$status" -ne 0 ] && [ "$config_changed" -eq 0 ]; then
        echo "Retrying official helper with --display-name..."
        set +e
        run_helper --display-name >"$log_file" 2>&1
        status=$?
        set -e
        after_snapshot="$(collect_snapshot || true)"
        config_changed=0
        if [ -n "$after_snapshot" ] && [ "$before_snapshot" != "$after_snapshot" ]; then
          config_changed=1
        fi
      fi

      if [ "$status" -ne 0 ] && [ "$config_changed" -eq 0 ]; then
        echo "CRD enrollment failed before writing a usable host config." >&2
        echo "See log: $log_file" >&2
        sed -n '1,120p' "$log_file" >&2
        exit "$status"
      fi

      if [ "$status" -ne 0 ]; then
        if grep -q '/usr/bin/sudo' "$log_file"; then
          echo "Official helper wrote the host config but could not auto-start via /usr/bin/sudo; continuing with $service_unit."
        else
          echo "Official helper exited non-zero after updating the host config; continuing with $service_unit."
        fi
      fi

      systemctl --user restart "$service_unit"
      sleep 5
      if ! systemctl --user is-active --quiet "$service_unit"; then
        echo "Enrollment wrote a host config, but $service_unit did not become active." >&2
        echo "Recent logs:" >&2
        journalctl --user -u "$service_unit" -n 40 --no-pager >&2 || true
        exit 1
      fi

      shopt -s nullglob
      cfg_files=("$cfg_dir"/host#*.json)
      shopt -u nullglob
      cfg="''${cfg_files[0]}"

      echo
      echo "Enrollment complete."
      echo "Host config: $cfg"
      jq -r '"Host owner: " + (.host_owner // "unknown") + "\nHost name: " + .host_name + "\nHost id: " + .host_id' "$cfg"
      echo "Service: $service_unit (active)"
      echo
      echo "Connect steps:"
      echo "  1. Open https://remotedesktop.google.com/access"
      echo "  2. Sign in with the Google account shown above"
      echo "  3. Look for the host name shown above"
      echo "  4. Enter the PIN you chose during enrollment"
      echo
      echo "No inbound firewall ports need to be opened for Chrome Remote Desktop."
      echo "If the host does not appear after a refresh, run: chrome-remote-desktop-debug"
      echo "Enrollment log: $log_file"
    '';
  };

  chromeRemoteDesktopDebug = pkgs.writeShellApplication {
    name = "chrome-remote-desktop-debug";
    runtimeInputs = with pkgs; [
      coreutils
      curl
      gnugrep
      iproute2
      jq
      procps
      systemd
    ];
    text = ''
      set -euo pipefail

      service_unit=${lib.escapeShellArg artifacts.serviceUnits.chromeRemoteDesktop}
      cfg_dir="$HOME/.config/chrome-remote-desktop"

      shopt -s nullglob
      cfg_files=("$cfg_dir"/host#*.json)
      shopt -u nullglob

      active="$(systemctl --user show "$service_unit" -p ActiveState --value 2>/dev/null || echo not-found)"
      sub="$(systemctl --user show "$service_unit" -p SubState --value 2>/dev/null || echo dead)"

      echo "Chrome Remote Desktop debug"
      echo "==================="
      echo "Service unit: $service_unit"
      echo "Service state: $active/$sub"

      if [ "''${#cfg_files[@]}" -gt 0 ]; then
        cfg="''${cfg_files[0]}"
        echo "Host config: $cfg"
        jq -r '"Host owner: " + (.host_owner // "unknown") + "\nHost name: " + .host_name + "\nHost id: " + .host_id + "\nHost secret hash: " + (if .host_secret_hash then "present" else "missing" end) + "\nPrivate key: " + (if .private_key then "present" else "missing" end) + "\nOAuth refresh token: " + (if .oauth_refresh_token then "present" else "missing" end)' "$cfg"
      else
        echo "Host config: missing"
      fi

      if journalctl --user -u "$service_unit" --grep 'Signaling connected' -n 1 --no-pager >/dev/null 2>&1; then
        echo "CRD signaling: yes"
      else
        echo "CRD signaling: no recent success seen"
      fi
      if journalctl --user -u "$service_unit" --grep 'Host ready to receive connections' -n 1 --no-pager >/dev/null 2>&1; then
        echo "CRD host ready: yes"
      else
        echo "CRD host ready: no recent success seen"
      fi

      display_server="unknown"
      if pgrep -af 'Xorg :[0-9]+' >/tmp/chrome-remote-desktop-display.txt 2>/dev/null; then
        display_server="$(head -n 1 /tmp/chrome-remote-desktop-display.txt)"
      elif pgrep -af 'Xvfb :[0-9]+' >/tmp/chrome-remote-desktop-display.txt 2>/dev/null; then
        display_server="$(head -n 1 /tmp/chrome-remote-desktop-display.txt)"
      fi
      rm -f /tmp/chrome-remote-desktop-display.txt
      echo "Display server: $display_server"

      if curl --max-time 3 -fsS http://127.0.0.1:9222/json/version >/tmp/chrome-remote-desktop-debug.json 2>/dev/null; then
        echo "Desktop browser CDP: healthy on http://127.0.0.1:9222"
        jq -r '"Desktop browser: " + .Browser' /tmp/chrome-remote-desktop-debug.json
        rm -f /tmp/chrome-remote-desktop-debug.json
      else
        echo "Desktop browser CDP: not responding on http://127.0.0.1:9222"
        ss -ltnp | awk '/9222/' || true
      fi

      echo
      echo "Connect steps:"
      echo "  1. Open https://remotedesktop.google.com/access"
      echo "  2. Sign in with the same Google account used during enrollment"
      echo "  3. Look for the host name shown above"
      echo "  4. Enter the PIN you chose at enrollment"
      echo
      echo "Firewall notes:"
      echo "  - No inbound firewall ports need to be opened for Chrome Remote Desktop."
      echo "  - If you run outbound filtering, allow HTTPS/WebRTC egress to Google."
      echo
      echo "Recent CRD journal:"
      journalctl --user -u "$service_unit" -n 25 --no-pager || true
    '';
  };
}
