---
- name: Deploy BZZZ 1.0.2 to Cluster
  hosts: bzzz_cluster
  become: yes
  vars:
    bzzz_version: "1.0.2"
    bzzz_binary_source: "{{ playbook_dir }}/build/bzzz-{{ bzzz_version }}"
    bzzz_service_name: "bzzz"
    backup_timestamp: "{{ ansible_date_time.epoch }}"
    bzzz_config_paths:
      - "/home/tony/chorus/project-queues/active/BZZZ/bzzz.yaml"
      - "/home/tony/chorus/project-queues/active/BZZZ/config/bzzz.yaml"
      - "/home/tony/.config/bzzz/config.yaml"
      - "/etc/bzzz/config.yaml"

  tasks:
    - name: Check if BZZZ service is running
      systemd:
        name: "{{ bzzz_service_name }}"
      register: bzzz_service_status
      ignore_errors: yes

    - name: Check for existing BZZZ config files
      stat:
        path: "{{ item }}"
      register: config_file_checks
      loop: "{{ bzzz_config_paths }}"

    - name: Identify existing config files
      set_fact:
        existing_config_files: "{{ config_file_checks.results | selectattr('stat.exists') | map(attribute='item') | list }}"

    - name: Display config file status
      debug:
        msg: |
          Config file discovery:
          {% for path in bzzz_config_paths %}
          {{ path }}: {{ 'EXISTS' if path in existing_config_files else 'MISSING' }}
          {% endfor %}
          
    - name: Warn if no config files found
      debug:
        msg: |
          ⚠️  WARNING: No BZZZ config files found!
          The embedded installation server should have generated a config file.
          Expected locations:
          {{ bzzz_config_paths | join('\n') }}
          
          The service may fail to start without proper configuration.
      when: existing_config_files | length == 0

    - name: Display primary config file
      debug:
        msg: "✅ Using primary config file: {{ existing_config_files[0] }}"
      when: existing_config_files | length > 0

    - name: Validate primary config file content
      shell: |
        echo "Config file validation for: {{ existing_config_files[0] }}"
        echo "File size: $(stat -c%s '{{ existing_config_files[0] }}') bytes"
        echo "Last modified: $(stat -c%y '{{ existing_config_files[0] }}')"
        echo ""
        echo "Config file preview (first 10 lines):"
        head -10 '{{ existing_config_files[0] }}'
      register: config_validation
      when: existing_config_files | length > 0
      changed_when: false

    - name: Display config file validation
      debug:
        msg: "{{ config_validation.stdout_lines }}"
      when: existing_config_files | length > 0 and config_validation is defined

    - name: Stop BZZZ service if running
      systemd:
        name: "{{ bzzz_service_name }}"
        state: stopped
      when: bzzz_service_status.status is defined and bzzz_service_status.status.ActiveState == "active"

    - name: Backup existing BZZZ binary
      copy:
        src: "/usr/local/bin/bzzz"
        dest: "/usr/local/bin/bzzz-backup-{{ backup_timestamp }}"
        remote_src: yes
      ignore_errors: yes

    - name: Copy new BZZZ binary to target hosts
      copy:
        src: "{{ bzzz_binary_source }}"
        dest: "/usr/local/bin/bzzz"
        mode: '0755'
        owner: root
        group: root

    - name: Verify binary was copied correctly
      stat:
        path: "/usr/local/bin/bzzz"
      register: bzzz_binary_stat

    - name: Fail if binary wasn't copied
      fail:
        msg: "BZZZ binary was not copied successfully"
      when: not bzzz_binary_stat.stat.exists

    - name: Check if systemd service file exists
      stat:
        path: "/etc/systemd/system/{{ bzzz_service_name }}.service"
      register: service_file_stat

    - name: Display service file status
      debug:
        msg: "Service file exists: {{ service_file_stat.stat.exists }}"

    - name: Reload systemd daemon
      systemd:
        daemon_reload: yes

    - name: Enable BZZZ service
      systemd:
        name: "{{ bzzz_service_name }}"
        enabled: yes

    - name: Start BZZZ service
      systemd:
        name: "{{ bzzz_service_name }}"
        state: started

    - name: Wait for service to be active
      wait_for:
        timeout: 30
      delegate_to: localhost

    - name: Check BZZZ service status
      systemd:
        name: "{{ bzzz_service_name }}"
      register: final_service_status

    - name: Display service status
      debug:
        msg: |
          Service: {{ bzzz_service_name }}
          Active: {{ final_service_status.status.ActiveState }}
          Sub-State: {{ final_service_status.status.SubState }}
          Host: {{ inventory_hostname }}

    - name: Get recent service logs
      command: journalctl -u {{ bzzz_service_name }} --since "2 minutes ago" --no-pager -n 20
      register: service_logs
      changed_when: false

    - name: Display recent service logs
      debug:
        msg: "{{ service_logs.stdout_lines }}"