---
# Comprehensive smoke tests for Veza V5 Ultra deployment
# Validates all services and endpoints

- name: Run smoke tests for Veza V5 Ultra
  hosts: edge
  become: false
  gather_facts: true

  vars:
    domain: "{{ domain | default('veza.talas.fr') }}"
    haproxy_container: "veza-haproxy"
    backend_container: "veza-backend"
    chat_container: "veza-chat"
    stream_container: "veza-stream"
    web_container: "veza-web"

  tasks:
    - name: Test container connectivity
      block:
        - name: Check if containers are running
          command: incus list --format=json
          register: containers_status
          failed_when: false

        - name: Display container status
          debug:
            msg: "Container {{ item.name }}: {{ 'Running' if item.status == 'Running' else item.status }}"
          loop: "{{ containers_status.stdout | from_json }}"

        - name: Verify all required containers are running
          assert:
            that:
              - containers_status.stdout | from_json | selectattr('name', 'in', [haproxy_container, backend_container, chat_container, stream_container, web_container]) | selectattr('status', 'equalto', 'Running') | list | length == 5
            fail_msg: "Not all required containers are running"
            success_msg: "All required containers are running"

      rescue:
        - name: Container connectivity test failed
          debug:
            msg: "Container connectivity test failed, continuing with other tests"

    - name: Test HAProxy service
      block:
        - name: Check HAProxy service status
          command: |
            incus exec {{ haproxy_container }} -- systemctl is-active haproxy
          register: haproxy_active
          failed_when: false

        - name: Display HAProxy status
          debug:
            msg: "HAProxy service: {{ haproxy_active.stdout }}"

        - name: Test HAProxy configuration
          command: |
            incus exec {{ haproxy_container }} -- haproxy -c -f /etc/haproxy/haproxy.cfg
          register: haproxy_config_test
          failed_when: false

        - name: Display HAProxy config test
          debug:
            var: haproxy_config_test.stdout_lines

        - name: Check HAProxy statistics
          command: |
            incus exec {{ haproxy_container }} -- curl -s http://localhost:8404/stats | head -10
          register: haproxy_stats
          failed_when: false

        - name: Display HAProxy statistics
          debug:
            var: haproxy_stats.stdout_lines

      rescue:
        - name: HAProxy test failed
          debug:
            msg: "HAProxy test failed, continuing with other tests"

    - name: Test Backend API service
      block:
        - name: Check backend service status
          command: |
            incus exec {{ backend_container }} -- systemctl is-active veza-backend
          register: backend_active
          failed_when: false

        - name: Display backend status
          debug:
            msg: "Backend service: {{ backend_active.stdout }}"

        - name: Test backend health endpoint
          command: |
            incus exec {{ backend_container }} -- curl -s http://localhost:8080/api/health
          register: backend_health
          failed_when: false

        - name: Display backend health response
          debug:
            var: backend_health.stdout_lines

        - name: Test backend API endpoint
          command: |
            incus exec {{ backend_container }} -- curl -s http://localhost:8080/api/
          register: backend_api
          failed_when: false

        - name: Display backend API response
          debug:
            var: backend_api.stdout_lines

        - name: Verify backend responses
          assert:
            that:
              - backend_health.stdout | from_json | selectattr('status', 'equalto', 'ok') | list | length > 0
              - backend_api.stdout | from_json | selectattr('message', 'defined') | list | length > 0
            fail_msg: "Backend API responses are invalid"
            success_msg: "Backend API is responding correctly"

      rescue:
        - name: Backend test failed
          debug:
            msg: "Backend test failed, continuing with other tests"

    - name: Test Chat WebSocket service
      block:
        - name: Check chat service status
          command: |
            incus exec {{ chat_container }} -- systemctl is-active veza-chat
          register: chat_active
          failed_when: false

        - name: Display chat status
          debug:
            msg: "Chat service: {{ chat_active.stdout }}"

        - name: Test chat health endpoint
          command: |
            incus exec {{ chat_container }} -- curl -s http://localhost:8081/health
          register: chat_health
          failed_when: false

        - name: Display chat health response
          debug:
            var: chat_health.stdout_lines

        - name: Test WebSocket connection (basic)
          command: |
            incus exec {{ chat_container }} -- timeout 5 bash -c 'echo "test message" | nc localhost 8081' || true
          register: websocket_test
          failed_when: false

        - name: Display WebSocket test result
          debug:
            var: websocket_test.stdout_lines

      rescue:
        - name: Chat test failed
          debug:
            msg: "Chat test failed, continuing with other tests"

    - name: Test Stream HLS service
      block:
        - name: Check stream service status
          command: |
            incus exec {{ stream_container }} -- systemctl is-active veza-stream
          register: stream_active
          failed_when: false

        - name: Display stream status
          debug:
            msg: "Stream service: {{ stream_active.stdout }}"

        - name: Test stream health endpoint
          command: |
            incus exec {{ stream_container }} -- curl -s http://localhost:8082/stream/health
          register: stream_health
          failed_when: false

        - name: Display stream health response
          debug:
            var: stream_health.stdout_lines

        - name: Test HLS endpoint
          command: |
            incus exec {{ stream_container }} -- curl -s http://localhost:8082/stream/test.m3u8
          register: hls_test
          failed_when: false

        - name: Display HLS test response
          debug:
            var: hls_test.stdout_lines

        - name: Verify HLS response
          assert:
            that:
              - hls_test.stdout is search('EXTM3U')
            fail_msg: "HLS endpoint is not returning valid M3U8 content"
            success_msg: "HLS endpoint is working correctly"

      rescue:
        - name: Stream test failed
          debug:
            msg: "Stream test failed, continuing with other tests"

    - name: Test Web application
      block:
        - name: Check web service status
          command: |
            incus exec {{ web_container }} -- systemctl is-active veza-web
          register: web_active
          failed_when: false

        - name: Display web status
          debug:
            msg: "Web service: {{ web_active.stdout }}"

        - name: Test web application
          command: |
            incus exec {{ web_container }} -- curl -s http://localhost:3000/
          register: web_test
          failed_when: false

        - name: Display web test response
          debug:
            msg: "Web response length: {{ web_test.stdout | length }} characters"

        - name: Verify web response
          assert:
            that:
              - web_test.stdout is search('Veza V5 Ultra')
            fail_msg: "Web application is not returning expected content"
            success_msg: "Web application is working correctly"

      rescue:
        - name: Web test failed
          debug:
            msg: "Web test failed, continuing with other tests"

    - name: Test external access through HAProxy
      block:
        - name: Test HTTP redirect
          uri:
            url: "http://{{ domain }}"
            method: GET
            follow_redirects: none
            status_code: 301
          register: http_redirect
          failed_when: false

        - name: Display HTTP redirect result
          debug:
            msg: "HTTP redirect: {{ 'Working' if http_redirect.status == 301 else 'Failed' }}"

        - name: Test HTTPS access (if certificate available)
          uri:
            url: "https://{{ domain }}"
            method: GET
            validate_certs: false
            status_code: 200
          register: https_test
          failed_when: false

        - name: Display HTTPS test result
          debug:
            msg: "HTTPS access: {{ 'Working' if https_test.status == 200 else 'Failed or certificate not available' }}"

        - name: Test API through HAProxy
          uri:
            url: "https://{{ domain }}/api/health"
            method: GET
            validate_certs: false
            status_code: 200
          register: api_proxy_test
          failed_when: false

        - name: Display API proxy test result
          debug:
            msg: "API through HAProxy: {{ 'Working' if api_proxy_test.status == 200 else 'Failed' }}"

      rescue:
        - name: External access test failed
          debug:
            msg: "External access test failed (expected if DNS not configured)"

    - name: Test network connectivity between containers
      block:
        - name: Test backend connectivity from web container
          command: |
            incus exec {{ web_container }} -- curl -s http://10.10.0.101:8080/api/health
          register: backend_connectivity
          failed_when: false

        - name: Display backend connectivity
          debug:
            msg: "Backend connectivity from web: {{ 'Working' if backend_connectivity.rc == 0 else 'Failed' }}"

        - name: Test chat connectivity from web container
          command: |
            incus exec {{ web_container }} -- curl -s http://10.10.0.102:8081/health
          register: chat_connectivity
          failed_when: false

        - name: Display chat connectivity
          debug:
            msg: "Chat connectivity from web: {{ 'Working' if chat_connectivity.rc == 0 else 'Failed' }}"

        - name: Test stream connectivity from web container
          command: |
            incus exec {{ web_container }} -- curl -s http://10.10.0.103:8082/stream/health
          register: stream_connectivity
          failed_when: false

        - name: Display stream connectivity
          debug:
            msg: "Stream connectivity from web: {{ 'Working' if stream_connectivity.rc == 0 else 'Failed' }}"

      rescue:
        - name: Network connectivity test failed
          debug:
            msg: "Network connectivity test failed"

    - name: Performance and resource checks
      block:
        - name: Check container resource usage
          command: |
            incus exec {{ haproxy_container }} -- free -h
            incus exec {{ backend_container }} -- free -h
            incus exec {{ chat_container }} -- free -h
            incus exec {{ stream_container }} -- free -h
            incus exec {{ web_container }} -- free -h
          register: resource_usage
          failed_when: false

        - name: Display resource usage
          debug:
            var: resource_usage.stdout_lines

        - name: Check disk usage
          command: |
            incus exec {{ haproxy_container }} -- df -h
            incus exec {{ backend_container }} -- df -h
            incus exec {{ chat_container }} -- df -h
            incus exec {{ stream_container }} -- df -h
            incus exec {{ web_container }} -- df -h
          register: disk_usage
          failed_when: false

        - name: Display disk usage
          debug:
            var: disk_usage.stdout_lines

      rescue:
        - name: Performance check failed
          debug:
            msg: "Performance check failed"

  post_tasks:
    - name: Generate smoke test summary
      debug:
        msg: |
          ========================================
          Veza V5 Ultra Smoke Test Summary
          ========================================
          
          Tests completed:
          - Container connectivity: {{ 'PASS' if containers_status is defined and containers_status.rc == 0 else 'FAIL' }}
          - HAProxy service: {{ 'PASS' if haproxy_active is defined and haproxy_active.stdout == 'active' else 'FAIL' }}
          - Backend API: {{ 'PASS' if backend_health is defined and backend_health.rc == 0 else 'FAIL' }}
          - Chat WebSocket: {{ 'PASS' if chat_health is defined and chat_health.rc == 0 else 'FAIL' }}
          - Stream HLS: {{ 'PASS' if stream_health is defined and stream_health.rc == 0 else 'FAIL' }}
          - Web application: {{ 'PASS' if web_test is defined and web_test.rc == 0 else 'FAIL' }}
          - External access: {{ 'PASS' if https_test is defined and https_test.status == 200 else 'FAIL (expected if DNS not configured)' }}
          
          Next steps:
          1. Configure DNS A record for {{ domain }} to point to this host
          2. Re-run HAProxy playbook to get Let's Encrypt certificate
          3. Re-run smoke tests to verify HTTPS access
          4. Monitor application logs for any issues
          
          ========================================

    - name: Show container logs (last 10 lines each)
      command: |
        echo "=== HAProxy Logs ==="
        incus exec {{ haproxy_container }} -- journalctl -u haproxy --no-pager -n 10 || true
        echo "=== Backend Logs ==="
        incus exec {{ backend_container }} -- journalctl -u veza-backend --no-pager -n 10 || true
        echo "=== Chat Logs ==="
        incus exec {{ chat_container }} -- journalctl -u veza-chat --no-pager -n 10 || true
        echo "=== Stream Logs ==="
        incus exec {{ stream_container }} -- journalctl -u veza-stream --no-pager -n 10 || true
        echo "=== Web Logs ==="
        incus exec {{ web_container }} -- journalctl -u veza-web --no-pager -n 10 || true
      register: container_logs
      failed_when: false

    - name: Display container logs
      debug:
        var: container_logs.stdout_lines
