---
- name: Get Tailscale status as JSON
  ansible.builtin.command: tailscale status --json
  register: openclaw_tailscale_status_raw
  changed_when: false
  failed_when: false

- name: Parse Tailscale status JSON
  ansible.builtin.set_fact:
    openclaw_tailscale_status: "{{ openclaw_tailscale_status_raw.stdout | from_json }}"
  when: openclaw_tailscale_status_raw.rc == 0
  changed_when: false

- name: Extract Tailscale backend state
  ansible.builtin.set_fact:
    openclaw_tailscale_backend_state: "{{ openclaw_tailscale_status.BackendState | default('') }}"
  when: openclaw_tailscale_status is defined
  changed_when: false

- name: Set Tailscale IP fact
  ansible.builtin.set_fact:
    openclaw_tailscale_ip: "{{ openclaw_tailscale_status.Self.TailscaleIPs[0] }}"
  when:
    - openclaw_tailscale_status_raw.rc == 0
    - openclaw_tailscale_backend_state == "Running"
    - openclaw_tailscale_status.Self is defined
    - openclaw_tailscale_status.Self.TailscaleIPs is defined
    - openclaw_tailscale_status.Self.TailscaleIPs | length > 0
  changed_when: false

- name: Set gateway bind address
  ansible.builtin.set_fact:
    openclaw_gateway_bind: "{{ openclaw_tailscale_ip | default('127.0.0.1') }}"

- name: Display Tailscale IP
  ansible.builtin.debug:
    msg: "OpenClaw will bind to Tailscale IP: {{ openclaw_tailscale_ip }}"
  when: openclaw_tailscale_ip is defined

- name: Warn if Tailscale not found
  ansible.builtin.debug:
    msg: "WARNING: Tailscale not running or not authenticated. OpenClaw will bind to localhost only."
  when: openclaw_tailscale_ip is not defined

- name: Get user UID
  ansible.builtin.command: id -u {{ openclaw_user }}
  register: openclaw_user_uid
  changed_when: false

- name: Check if linger is already enabled for user
  ansible.builtin.stat:
    path: "/var/lib/systemd/linger/{{ openclaw_user }}"
  register: openclaw_linger_file

- name: Enable linger for user
  ansible.builtin.command: loginctl enable-linger {{ openclaw_user }}
  when: not openclaw_linger_file.stat.exists
  changed_when: true

- name: Install required packages for Node.js
  ansible.builtin.apt:
    name:
      - ca-certificates
      - curl
      - gnupg
    state: present

- name: Create directory for NodeSource GPG key
  ansible.builtin.file:
    path: /etc/apt/keyrings
    state: directory
    mode: "0755"

- name: Add NodeSource GPG key
  ansible.builtin.shell:
    cmd: |
      set -o pipefail
      curl -fsSL https://deb.nodesource.com/gpgkey/nodesource-repo.gpg.key | \
        gpg --dearmor -o /etc/apt/keyrings/nodesource.gpg
      chmod a+r /etc/apt/keyrings/nodesource.gpg
    creates: /etc/apt/keyrings/nodesource.gpg
    executable: /bin/bash

- name: Add NodeSource repository
  ansible.builtin.shell:
    cmd: |
      set -o pipefail
      echo "deb [signed-by=/etc/apt/keyrings/nodesource.gpg] \
        https://deb.nodesource.com/node_{{ openclaw_node_version }} nodistro main" | \
        tee /etc/apt/sources.list.d/nodesource.list > /dev/null
    creates: /etc/apt/sources.list.d/nodesource.list
    executable: /bin/bash

- name: Update apt cache after adding NodeSource repo
  ansible.builtin.apt:
    update_cache: true

- name: Check current Node.js version
  ansible.builtin.command: node --version
  register: openclaw_current_node_version
  changed_when: false
  failed_when: false

- name: Get latest NodeSource Node.js 22.x version
  ansible.builtin.shell: |
    set -o pipefail
    apt-cache madison nodejs | grep nodesource | grep '^nodejs' | head -1 | awk '{print $3}'
  args:
    executable: /bin/bash
  register: openclaw_nodesource_version
  changed_when: false
  when: >
    openclaw_current_node_version.rc != 0 or
    (openclaw_current_node_version.stdout | regex_replace('^v', '') | split('.') | first | int) < 22

- name: Install Node.js from NodeSource with specific version
  ansible.builtin.apt:
    name: "nodejs={{ openclaw_nodesource_version.stdout }}"
    state: present
    allow_downgrade: true
    force: true
  when: >
    openclaw_current_node_version.rc != 0 or
    (openclaw_current_node_version.stdout | regex_replace('^v', '') | split('.') | first | int) < 22

- name: Verify Node.js installation
  ansible.builtin.command: node --version
  register: openclaw_node_version_output
  changed_when: false

- name: Verify npm installation
  ansible.builtin.command: npm --version
  register: openclaw_npm_version_output
  changed_when: false

- name: Display Node.js and npm versions
  ansible.builtin.debug:
    msg:
      - "Node.js version: {{ openclaw_node_version_output.stdout }}"
      - "npm version: {{ openclaw_npm_version_output.stdout }}"

- name: Create systemd user directory
  ansible.builtin.file:
    path: "{{ openclaw_home }}/.config/systemd/user"
    state: directory
    owner: "{{ openclaw_user }}"
    group: "{{ openclaw_group }}"
    mode: "0755"

- name: Create OpenClaw directories
  ansible.builtin.file:
    path: "{{ item }}"
    state: directory
    owner: "{{ openclaw_user }}"
    group: "{{ openclaw_group }}"
    mode: "0750"
  loop:
    - "{{ openclaw_config_dir }}"
    - "{{ openclaw_workspace_dir }}"

- name: Install OpenClaw globally
  community.general.npm:
    name: "openclaw@{{ openclaw_version }}"
    global: true
    state: present

- name: Verify openclaw binary in PATH
  ansible.builtin.command: which openclaw
  become: true
  become_user: "{{ openclaw_user }}"
  register: openclaw_which_result
  changed_when: false
  failed_when: openclaw_which_result.rc != 0

- name: Deploy OpenClaw gateway systemd service
  ansible.builtin.template:
    src: openclaw-gateway.service.j2
    dest: "{{ openclaw_home }}/.config/systemd/user/openclaw-gateway.service"
    owner: "{{ openclaw_user }}"
    group: "{{ openclaw_group }}"
    mode: "0644"
  notify: Reload systemd user

- name: Enable and start OpenClaw gateway service
  become: true
  become_user: "{{ openclaw_user }}"
  ansible.builtin.systemd:
    name: openclaw-gateway
    enabled: true
    state: started
    scope: user
  environment:
    XDG_RUNTIME_DIR: "/run/user/{{ openclaw_user_uid.stdout }}"

- name: Display deployment summary
  ansible.builtin.debug:
    msg:
      - "==================================="
      - "OpenClaw Deployment Complete!"
      - "==================================="
      - "Gateway Bind: {{ openclaw_gateway_bind }}"
      - "Gateway Port: {{ openclaw_gateway_port }}"
      - "Config Dir: {{ openclaw_config_dir }}"
      - "Workspace: {{ openclaw_workspace_dir }}"
      - ""
      - "Next steps:"
      - "1. Check service: systemctl --user status openclaw-gateway"
      - "2. View logs: journalctl --user -u openclaw-gateway -f"
      - "3. SSH to VPS: ssh {{ openclaw_user }}@{{ inventory_hostname }}"
      - "4. Run onboarding: openclaw onboard"
      - "5. Connect channels (WhatsApp/Telegram/etc)"
      - ""
      - "Web UI access:"
      - "{% if openclaw_tailscale_ip is defined %}http://{{ openclaw_tailscale_ip }}:{{ openclaw_gateway_port }}{% else %}SSH tunnel required{% endif %}"
      - ""
      - "Install Tailscale on laptop:"
      - "https://tailscale.com/download"
