---
# Test Connectivity — Full Platform Health Check
# Checks infrastructure AND application-level functionality
#
# Usage:
#   ansible-playbook -i inventory/production.yml playbooks/test-connectivity.yml

- name: Test Connectivity — Full Platform Health Check
  hosts: all
  become: yes

  tasks:
    # ── Infrastructure ──────────────────────────────────────────
    - name: "[1/14] Check Docker is running"
      command: docker info
      register: docker_info
      ignore_errors: yes

    - name: "[2/14] Check container status"
      shell: |
        cd /opt/gravity
        docker compose ps --format '{{ '{{' }}.Name{{ '}}' }} {{ '{{' }}.State{{ '}}' }} {{ '{{' }}.Status{{ '}}' }}' 2>/dev/null || echo "FAILED"
      register: container_status
      ignore_errors: yes

    - name: "[3/14] Check for restarting containers"
      shell: |
        cd /opt/gravity
        docker compose ps --format '{{ '{{' }}.Name{{ '}}' }} {{ '{{' }}.State{{ '}}' }}' 2>/dev/null | grep -i restart || echo "NONE"
      register: restarting_containers
      ignore_errors: yes

    # ── Ports ───────────────────────────────────────────────────
    - name: "[4/14] Test internal service ports"
      wait_for:
        host: localhost
        port: "{{ item.port }}"
        timeout: 5
      # UMAP is deliberately absent: it publishes no port to the host (internal to Docker
      # only). Its reachability is proved by the Docker-DNS check below, which is the only
      # thing that was ever actually load-bearing for it.
      loop:
        - { name: "Canvas", port: 3001 }
        - { name: "Engine", port: 4101 }
        - { name: "Unoverse", port: 4105 }
        - { name: "Memory", port: 4104 }
      register: port_checks
      ignore_errors: yes

    # ── External Dependencies ───────────────────────────────────
    - name: "[5/14] Test Redis connectivity (external)"
      shell: |
        REDIS_HOST=$(grep '^REDIS_HOST=' /opt/gravity/.env 2>/dev/null | cut -d'=' -f2-)
        REDIS_PORT=$(grep '^REDIS_PORT=' /opt/gravity/.env 2>/dev/null | cut -d'=' -f2-)
        REDIS_HOST=${REDIS_HOST:-localhost}
        REDIS_PORT=${REDIS_PORT:-6379}
        echo "host=${REDIS_HOST} port=${REDIS_PORT}"
        timeout 5 bash -c "echo PING | nc -w 3 ${REDIS_HOST} ${REDIS_PORT}" >/dev/null 2>&1
      register: redis_check
      ignore_errors: yes

    - name: "[6/14] Test database connectivity"
      shell: |
        DB_URL=$(grep '^DATABASE_URL=' /opt/gravity/.env 2>/dev/null | cut -d'=' -f2-)
        if [ -z "$DB_URL" ]; then
          echo "DATABASE_URL not set"
          exit 1
        fi
        # Extract host:port from postgresql://user:pass@host:port/db
        DB_HOSTPORT=$(echo "$DB_URL" | sed -E 's|.*@([^/]+)/.*|\1|')
        DB_HOST=$(echo "$DB_HOSTPORT" | cut -d: -f1)
        DB_PORT=$(echo "$DB_HOSTPORT" | cut -d: -f2)
        echo "host=${DB_HOST} port=${DB_PORT}"
        timeout 5 bash -c "echo | nc -w 3 ${DB_HOST} ${DB_PORT}" >/dev/null 2>&1
      register: db_check
      ignore_errors: yes

    # ── Health Endpoints ────────────────────────────────────────
    - name: "[7/14] Test service health endpoints"
      uri:
        url: "http://localhost:{{ item.port }}/health"
        status_code: 200
        timeout: 5
      loop:
        - { name: "Engine", port: 4101 }
        - { name: "Unoverse", port: 4105 }
        - { name: "Memory", port: 4104 }
      register: health_checks
      ignore_errors: yes

    - name: "[7b/9] Test UMAP reachable from unoverse container (Docker DNS)"
      shell: |
        cd /opt/gravity
        RESULT=$(docker compose exec -T unoverse node -e "fetch('http://umap:5001/health').then(r=>r.json()).then(d=>console.log('OK: '+JSON.stringify(d))).catch(e=>console.log('FAILED: '+e.message))" 2>&1)
        echo "$RESULT"
        echo "$RESULT" | grep -q "OK:"
      register: umap_docker_check
      ignore_errors: yes

    # ── Application-Level Checks ────────────────────────────────
    - name: "[8/14] Test API endpoints (read)"
      shell: |
        RESPONSE=$(curl -s -w '\n%{http_code}' --max-time 10 http://localhost:{{ item.port }}{{ item.path }})
        STATUS=$(echo "$RESPONSE" | tail -1)
        BODY=$(echo "$RESPONSE" | head -n -1)
        echo "HTTP $STATUS"
        [ "$STATUS" -ge 200 ] && [ "$STATUS" -lt 300 ]
      loop:
        # The engine surface (:4101) is the ungated internal API — the public
        # /api/* on :4105 is JWT-gated, so anonymous checks go here.
        - { name: "GET /workflows (engine)", port: 4101, path: "/workflows" }
        - { name: "GET /nodes (engine)", port: 4101, path: "/nodes" }
      register: api_checks
      ignore_errors: yes

    - name: "[8b/13] Test prompt blocks (internal :4106, from inside the container)"
      shell: |
        cd /opt/gravity
        RESULT=$(docker compose exec -T unoverse node -e \
          "fetch('http://127.0.0.1:4106/prompt-blocks').then(r=>r.json()).then(d=>console.log('blocks='+(Array.isArray(d)?d.length:(d.blocks||[]).length))).catch(e=>console.log('FAILED: '+e.message))" 2>&1)
        echo "$RESULT"
        echo "$RESULT" | grep -q "blocks="
      register: prompt_blocks_check
      ignore_errors: yes

    - name: "[9/14] Test API write (POST workflow)"
      shell: |
        RESPONSE=$(curl -s -w '\n%{http_code}' --max-time 10 \
          -X POST http://localhost:4101/workflows \
          -H 'Content-Type: application/json' \
          -d '{"name":"_health_check_test","nodes":[],"edges":[]}')
        STATUS=$(echo "$RESPONSE" | tail -1)
        echo "HTTP $STATUS"
        [ "$STATUS" -ge 200 ] && [ "$STATUS" -lt 300 ]
      register: api_write_check
      ignore_errors: yes

    # AN EMPTY CATALOGUE IS NOT A BROKEN ONE. Nodes arrive as rows — installed from the
    # marketplace or published from Studio — so a universe on its first day has none, and
    # that is the correct state, not a fault. This used to fail outright on zero and advise
    # "run deploy.sh rebuild", a command that does not exist, which turned every first
    # deploy into a red line pointing at nothing.
    #
    # What IS worth failing on is the runtime not answering at all: that means the catalogue
    # could not be read, which is a different fact from it being empty.
    - name: "[10/13] Check the node catalogue is readable"
      shell: |
        cd /opt/gravity
        # The internal :4106 runtime is Docker-network-only (never published), and the
        # public :4105 routes are JWT-gated — so read the catalog from INSIDE the
        # container. node:20-slim has no curl; use node fetch.
        NODE_COUNT=$(docker compose exec -T unoverse node -e \
          "fetch('http://127.0.0.1:4106/nodes').then(r=>r.json()).then(d=>console.log((d.nodes||[]).length)).catch(()=>console.log('unreachable'))" 2>/dev/null | tr -d ' \r')
        if [ "$NODE_COUNT" = "unreachable" ]; then
          echo "nodes=unreachable"
          echo "The runtime did not answer on :4106 — the catalogue could not be read"
          exit 1
        fi
        echo "nodes=${NODE_COUNT}"
        if [ "${NODE_COUNT:-0}" -eq 0 ] 2>/dev/null; then
          echo "(none installed yet — install from the marketplace or publish from Studio)"
        fi
      register: plugin_check
      ignore_errors: yes

    # NO PACKAGES CHECK. It looked for /app/host_packages, a bind mount retired when nodes
    # became declarative YAML and marketplace content became rows. Nothing declares
    # PACKAGES_PATH any more and docker-compose.yml has no such volume, so the check could
    # only ever report 0 and tell the operator to run a command that would not fix it.
    # (The original note said nodes "moved to npm at runtime"; that lane never survived and
    # was removed outright on 2026-08-30. MARKETPLACE.md §10 q3.)

    # SINCE THE SERVICES RESTARTED, NOT SINCE FIVE MINUTES AGO.
    #
    # A first setup necessarily boots the services before the schema exists — migrations run
    # THROUGH the unoverse container, so there is nothing to run them in until it is up — and
    # db-setup restarts everything afterwards. A fixed five-minute window straddles that
    # restart and reports the pre-migration errors as if they were current: every first
    # deploy ended with 'relation "memories" does not exist' in red, describing a state that
    # had already been fixed two minutes earlier by this very playbook.
    #
    # The question is "is anything wrong NOW", so the window starts when the services did.
    # `{% raw %}` because DOCKER'S TEMPLATE LANGUAGE AND JINJA SHARE A SYNTAX. `-f
    # '{{.State.StartedAt}}'` is a Go template for docker and a Jinja expression for
    # Ansible, which parses it first and dies on `unexpected '.'` — the whole task fails
    # before the shell ever runs. This block uses no Ansible variables, so the honest fix is
    # to hand it over untouched rather than escape the braces one at a time.
    - name: "[12/14] Check for errors in service logs"
      shell: |
        {% raw %}
        cd /opt/gravity
        # Newest container start: everything before it belongs to a previous run.
        SINCE=$(docker compose ps -q 2>/dev/null | xargs -r docker inspect -f '{{.State.StartedAt}}' 2>/dev/null | sort | tail -1)
        [ -n "$SINCE" ] || SINCE=5m
        ERRORS=$(docker compose logs --tail=50 --since="$SINCE" 2>&1 | grep -iE 'error|fatal|panic|does not exist|ECONNREFUSED' | grep -v 'NOGROUP' | tail -10)
        if [ -n "$ERRORS" ]; then
          echo "$ERRORS"
          exit 1
        else
          echo "No errors since the services started"
        fi
        {% endraw %}
      register: log_errors
      ignore_errors: yes

    # ── Domain (native ingress: the provider LB terminates TLS) ───
    - name: "[13/14] Read DOMAIN from .env"
      shell: grep '^DOMAIN=' /opt/gravity/.env 2>/dev/null | cut -d'=' -f2-
      register: domain_value
      ignore_errors: yes

    - name: "[14/14] Test public domain endpoints (if DOMAIN set)"
      shell: |
        RESULT=$(curl -s -o /dev/null -w '%{http_code}' --max-time 10 -k https://{{ item.sub }}{{ domain_value.stdout }}{{ item.path }} 2>/dev/null)
        echo "HTTP $RESULT"
        [ "$RESULT" -ge 200 ] && [ "$RESULT" -lt 500 ]
      loop:
        # canvas.<domain>, NEVER the bare apex. Neither ground creates an apex record
        # (aws/main.tf and digitalocean/main.tf publish api.<domain> and canvas.<domain>
        # only), so `sub: ""` asked for a hostname that has no DNS at all and reported
        # HTTP 000 FAILED on every healthy deploy.
        - { name: "Canvas", sub: "canvas.", path: "/" }
        - { name: "API Server", sub: "api.", path: "/health" }
      register: domain_checks
      ignore_errors: yes
      when: domain_value.stdout | default('') | length > 0 and domain_value.stdout != 'example.com'

  post_tasks:
    - name: "=== PLATFORM HEALTH CHECK ==="
      debug:
        msg: |
          ============================================
          PLATFORM HEALTH CHECK
          ============================================
          Host: {{ inventory_hostname }} ({{ ansible_host }})

          ── Infrastructure ──
          Docker: {{ 'OK' if docker_info.rc == 0 else 'FAILED' }}

          Containers:
          {% for line in container_status.stdout_lines %}
            {{ line }}
          {% endfor %}

          Restarting: {{ restarting_containers.stdout | trim }}

          ── Ports ──
          {% for result in port_checks.results %}
            - {{ result.item.name }} ({{ result.item.port }}): {{ 'OK' if not result.failed else 'CLOSED' }}
          {% endfor %}

          ── External Dependencies ──
          Redis: {{ 'REACHABLE' if redis_check.rc == 0 else 'UNREACHABLE' }}
            {{ redis_check.stdout_lines[0] | default('') }}
          Database: {{ 'REACHABLE' if db_check.rc == 0 else 'UNREACHABLE' }}
            {{ db_check.stdout_lines[0] | default('') }}

          ── Health Endpoints ──
          {% for result in health_checks.results %}
            - {{ result.item.name }}: {{ 'OK' if not result.failed else 'FAILED' }}
          {% endfor %}

          ── UMAP (Docker DNS) ──
          Unoverse → umap:5001: {{ 'OK' if umap_docker_check.rc == 0 else 'FAILED — run install-umap.yml' }}

          ── API Endpoints (read) ──
          {% for result in api_checks.results %}
            - {{ result.item.name }}: {{ result.stdout | default('???') if not result.failed else 'FAILED (' + result.stdout | default('???') + ')' }}
          {% endfor %}

          ── API Write Test ──
            - POST /workflows (engine): {{ api_write_check.stdout | default('???') if not api_write_check.failed else 'FAILED (' + api_write_check.stdout | default('???') + ')' }}

          ── Prompt Blocks (internal :4106) ──
            {{ prompt_blocks_check.stdout_lines[0] | default('(skipped)') }}

          ── Node catalogue ──
          {{ plugin_check.stdout_lines[0] | default('(skipped)') }}
          {{ plugin_check.stdout_lines[1] | default('') }}

          ── Recent Errors in Logs ──
          {{ log_errors.stdout | default('(skipped)') }}


          ── Public Domain ──
          {% if domain_value.stdout | default('') | length > 0 and domain_value.stdout != 'example.com' %}
          Domain: {{ domain_value.stdout }}
          {% if domain_checks is defined and domain_checks.results is defined %}
          {% for result in domain_checks.results %}
            - https://{{ result.item.sub }}{{ domain_value.stdout }}{{ result.item.path }}: {{ result.stdout | default('SKIPPED') if not result.failed | default(true) else 'FAILED' }}
          {% endfor %}
          {% endif %}
          {% else %}
          Domain: NOT SET (set DOMAIN= in .env to enable public URL checks)
          {% endif %}
          ============================================
