#!/bin/bash
# CI watcher for astra — polls WAM for ci-trigger tickets and runs CI.
#
# Runs as a background service on astra. Checks WAM every 30 seconds for
# open tickets with source=ci-trigger. When found, claims the ticket
# (marks it in-progress), runs CI, and updates the ticket with results.
#
# Location on astra: /home/max/mnw-ci/server/deploy/ci-watcher.sh
# Systemd unit: ci-watcher.service
#
# Usage: ci-watcher.sh

set -uo pipefail

export PATH="$HOME/.cargo/bin:$PATH"

WAM_URL="${WAM_URL:-http://100.120.174.96:7890}"
REPO_DIR="$HOME/mnw-ci"
POLL_INTERVAL=30
CI_SCRIPT="$REPO_DIR/server/deploy/ci-on-push.sh"

echo "CI watcher started (polling WAM every ${POLL_INTERVAL}s)"

while true; do
    sleep "$POLL_INTERVAL"

    # Check for open ci-trigger tickets
    RESPONSE=$(curl -sf "$WAM_URL/tickets?source=ci-trigger&status=open" 2>/dev/null) || continue
    COUNT=$(echo "$RESPONSE" | python3 -c 'import sys,json; print(json.load(sys.stdin).get("count",0))' 2>/dev/null || echo "0")

    if [ "$COUNT" = "0" ] || [ -z "$COUNT" ]; then
        continue
    fi

    # Get the first trigger ticket
    TICKET_ID=$(echo "$RESPONSE" | python3 -c 'import sys,json; d=json.load(sys.stdin); print(d["data"][0]["id"])' 2>/dev/null) || continue
    COMMIT=$(echo "$RESPONSE" | python3 -c 'import sys,json; d=json.load(sys.stdin); print(d["data"][0].get("source_ref","unknown"))' 2>/dev/null || echo "unknown")

    echo ""
    echo "=== CI trigger found: $COMMIT ==="

    # Claim the ticket (mark in-progress so we don't pick it up again)
    curl -sf -X PATCH "$WAM_URL/tickets/$TICKET_ID" \
        -H "Content-Type: application/json" \
        -d '{"status": "in-progress"}' >/dev/null 2>&1

    # Run CI
    if "$CI_SCRIPT" main 2>&1; then
        # CI passed — close the trigger ticket
        curl -sf -X PATCH "$WAM_URL/tickets/$TICKET_ID" \
            -H "Content-Type: application/json" \
            -d '{"status": "closed"}' >/dev/null 2>&1
    else
        # CI failed — ci-on-push.sh already created a failure ticket and reverted.
        # Close the trigger ticket.
        curl -sf -X PATCH "$WAM_URL/tickets/$TICKET_ID" \
            -H "Content-Type: application/json" \
            -d '{"status": "closed"}' >/dev/null 2>&1
    fi

    echo "=== CI run complete ==="
done
