---
# pm2-service role — 確保 PM2 管理的服務運作中
# 呼叫方式: include_role: name=pm2-service
#   vars:
#     pm2_app_name: wooo-aiops   # PM2 process name
#     pm2_user: wooo             # 執行 PM2 的使用者

- name: "{{ pm2_app_name }} | 確認 PM2 process 狀態"
  ansible.builtin.command:
    cmd: "pm2 jlist"
  become_user: "{{ pm2_user }}"
  register: pm2_list
  changed_when: false

- name: "{{ pm2_app_name }} | 解析 process 狀態"
  ansible.builtin.set_fact:
    _pm2_online: "{{ (pm2_list.stdout | from_json | selectattr('name', 'equalto', pm2_app_name) | selectattr('pm2_env.status', 'equalto', 'online') | list | length) > 0 }}"

- name: "{{ pm2_app_name }} | 警告：服務未 online"
  ansible.builtin.debug:
    msg: "⚠️  PM2 process '{{ pm2_app_name }}' 未 online，請手動檢查"
  when: not _pm2_online
