---
# showcase/helpers.yml — Sibling instance discovery via Incus API
#
# Required input vars (set before include_tasks):
#   discovery_prefix  — name prefix to match (e.g., "webapp-db-")
#
# Output facts:
#   discovered_siblings — list of dicts: [{name: "...", ip: "..."}]

- name: "Query all instances from Incus API"
  ansible.builtin.uri:
    url: "{{ incus_api }}/1.0/instances?recursion=1"
    method: GET
    client_cert: "{{ incus_cert }}"
    client_key: "{{ incus_key }}"
    validate_certs: false
    return_content: true
  register: all_instances_response

- name: "Find instances matching prefix '{{ discovery_prefix }}'"
  ansible.builtin.set_fact:
    matching_instance_names: >-
      {{ all_instances_response.json.metadata
         | selectattr('name', 'match', '^' + discovery_prefix)
         | map(attribute='name')
         | list }}

- name: "Report discovery results"
  ansible.builtin.debug:
    msg: "Found {{ matching_instance_names | length }} instances matching '{{ discovery_prefix }}': {{ matching_instance_names | join(', ') }}"

- name: "Get state for each matching instance"
  ansible.builtin.uri:
    url: "{{ incus_api }}/1.0/instances/{{ item }}/state"
    method: GET
    client_cert: "{{ incus_cert }}"
    client_key: "{{ incus_key }}"
    validate_certs: false
    return_content: true
  register: sibling_states
  loop: "{{ matching_instance_names }}"
  when: matching_instance_names | length > 0

- name: "Initialize discovered siblings"
  ansible.builtin.set_fact:
    discovered_siblings: []

- name: "Build discovered siblings list with IPs"
  ansible.builtin.set_fact:
    discovered_siblings: >-
      {{ discovered_siblings + [{
        'name': item.item,
        'ip': (item.json.metadata.network.eth0.addresses | default([])
               | selectattr('family', 'equalto', 'inet')
               | selectattr('scope', 'equalto', 'global')
               | map(attribute='address') | list | first | default(''))
      }] }}
  loop: "{{ sibling_states.results | default([]) }}"
  when:
    - item.json is defined
    - item.json.metadata.network is defined

- name: "Display discovered siblings"
  ansible.builtin.debug:
    msg: "Discovered siblings: {{ discovered_siblings }}"
