#!/usr/bin/env bash
# Exp 1b: Run a saturated rolling deploy triggered by a REAL task-def revision
# change (register new task def with different env vars) rather than
# force-new-deployment against the same revision.
#
# The force-deploy path is what every other experiment used. This verifies
# that the DEPLOYMENT_BLOCKED mechanism fires the same way when old tasks
# are on task def rev N and new tasks are on rev N+1 — the actual production
# rolling-deploy scenario.
#
# Usage: ./run_real_deploy.sh <desired_count> <results_subdir> <new_idle_ms>
# Example: ./run_real_deploy.sh 20 experiment-1b-real-deploy 60

set -euo pipefail

COUNT="${1:?Usage: $0 <desired_count> <results_subdir> <new_idle_ms>}"
RESULTS_SUBDIR="${2:?Usage: $0 <desired_count> <results_subdir> <new_idle_ms>}"
NEW_IDLE_MS="${3:?Usage: $0 <desired_count> <results_subdir> <new_idle_ms>}"

CLUSTER="claude-ecs-task-protection-experiment"
SERVICE="claude-ecs-task-protection-experiment"
LOG_GROUP="/ecs/${SERVICE}"
RESULTS_DIR="$(pwd)/results/${RESULTS_SUBDIR}"

mkdir -p "${RESULTS_DIR}"

echo "[$(date -u +%H:%M:%S)] scaling up to ${COUNT}"
./scripts/set_desired.sh "${COUNT}"

echo "[$(date -u +%H:%M:%S)] waiting for ${COUNT} running..."
until [ "$(aws ecs describe-services --cluster "${CLUSTER}" --services "${SERVICE}" --query 'services[0].runningCount' --output text)" = "${COUNT}" ]; do
    sleep 5
done

sleep 15

PRE_REV=$(aws ecs describe-services --cluster "${CLUSTER}" --services "${SERVICE}" --query 'services[0].taskDefinition' --output text | awk -F: '{print $NF}')
echo "[$(date -u +%H:%M:%S)] ${COUNT} running on revision ${PRE_REV}, starting state capture"
./scripts/tail_state.sh "${RESULTS_DIR}" > "${RESULTS_DIR}/tail_state.log" 2>&1 &
TAIL_STATE_PID=$!

sleep 5

TRIGGER_EPOCH_MS=$(($(date +%s) * 1000))
TRIGGER_ISO=$(date -u +%Y-%m-%dT%H:%M:%SZ)
echo "trigger_time=${TRIGGER_ISO}" > "${RESULTS_DIR}/trigger.txt"
echo "trigger_epoch_ms=${TRIGGER_EPOCH_MS}" >> "${RESULTS_DIR}/trigger.txt"
echo "pre_revision=${PRE_REV}" >> "${RESULTS_DIR}/trigger.txt"

echo "[$(date -u +%H:%M:%S)] registering new task def revision + redeploy"
./scripts/update_env.sh 200 "${NEW_IDLE_MS}" 30 0 0

POST_REV=$(aws ecs describe-services --cluster "${CLUSTER}" --services "${SERVICE}" --query 'services[0].taskDefinition' --output text | awk -F: '{print $NF}')
echo "post_revision=${POST_REV}" >> "${RESULTS_DIR}/trigger.txt"
echo "[$(date -u +%H:%M:%S)] deploy trigger: rev ${PRE_REV} -> rev ${POST_REV}"

START_EPOCH=$(date +%s)

echo "[$(date -u +%H:%M:%S)] polling for convergence..."
while true; do
    STATE=$(aws ecs describe-services --cluster "${CLUSTER}" --services "${SERVICE}" --query 'services[0].{d:length(deployments), r:runningCount, dc:desiredCount, rs:deployments[?status==`PRIMARY`].rolloutState | [0]}' --output json)
    D=$(echo "${STATE}" | python3 -c "import sys, json; print(json.load(sys.stdin)['d'])")
    R=$(echo "${STATE}" | python3 -c "import sys, json; print(json.load(sys.stdin)['r'])")
    DC=$(echo "${STATE}" | python3 -c "import sys, json; print(json.load(sys.stdin)['dc'])")
    RS=$(echo "${STATE}" | python3 -c "import sys, json; print(json.load(sys.stdin)['rs'])")
    if [ "${D}" = "1" ] && [ "${R}" = "${DC}" ] && [ "${RS}" = "COMPLETED" ]; then
        ELAPSED=$(($(date +%s) - START_EPOCH))
        echo "convergence_seconds=${ELAPSED}" >> "${RESULTS_DIR}/trigger.txt"
        echo "[$(date -u +%H:%M:%S)] converged in ${ELAPSED}s"
        break
    fi
    sleep 5
done

kill "${TAIL_STATE_PID}" 2>/dev/null || true

echo "[$(date -u +%H:%M:%S)] waiting 45s for CloudWatch ingestion..."
sleep 45

END_EPOCH_MS=$(($(date +%s) * 1000))
START_EPOCH_MS=$((TRIGGER_EPOCH_MS - 30000))

echo "[$(date -u +%H:%M:%S)] pulling worker logs"
aws logs filter-log-events \
    --log-group-name "${LOG_GROUP}" \
    --start-time "${START_EPOCH_MS}" \
    --end-time "${END_EPOCH_MS}" \
    --query 'events[*].message' \
    --output text | tr '\t' '\n' > "${RESULTS_DIR}/worker-logs.jsonl"

echo "[$(date -u +%H:%M:%S)] done"
echo "--- revision transition ---"
grep "rev_summary\|revision_change" "${RESULTS_DIR}/worker-logs.jsonl" 2>/dev/null || true
echo "--- event counts ---"
grep -oE '"event": "[^"]+"' "${RESULTS_DIR}/worker-logs.jsonl" | sort | uniq -c
echo "--- revisions observed in worker logs ---"
grep -oE '"revision": "[^"]+"' "${RESULTS_DIR}/worker-logs.jsonl" | sort | uniq -c
