#!/usr/bin/env bash
# =============================================================================
# setup-apigw-logging.sh
# Configures AWS API Gateway access logging to CloudWatch for Levo.ai ingestion
# =============================================================================
set -euo pipefail

# -----------------------------------------------------------------------------
# CONFIGURATION — edit these before running
# -----------------------------------------------------------------------------
API_ID=""               # Your API Gateway HTTP API ID (e.g. zp4tzrcd6k)
STAGE_NAME='$default'   # Stage name — most HTTP APIs use $default
LOG_GROUP=""            # CloudWatch log group name (e.g. levo/api-gateway-logs)
REGION=""               # AWS region (e.g. us-east-1)
RETENTION_DAYS=7        # Log retention in days
# -----------------------------------------------------------------------------

# ── Validate inputs ──────────────────────────────────────────────────────────
usage() {
  echo ""
  echo "Usage: Set the four variables at the top of this script, then run it."
  echo ""
  echo "  API_ID          Your API Gateway HTTP API ID"
  echo "  STAGE_NAME      Stage name (default: \$default)"
  echo "  LOG_GROUP       CloudWatch log group name"
  echo "  REGION          AWS region"
  echo ""
  echo "Or export them as environment variables before running:"
  echo "  export API_ID=zp4tzrcd6k LOG_GROUP=levo/api-gateway-logs REGION=us-east-1"
  echo "  ./setup-apigw-logging.sh"
  echo ""
}

# Allow env var overrides
API_ID="${API_ID:-${APIGW_API_ID:-}}"
LOG_GROUP="${LOG_GROUP:-${APIGW_LOG_GROUP:-}}"
REGION="${REGION:-${AWS_DEFAULT_REGION:-}}"

MISSING=0
for VAR in API_ID LOG_GROUP REGION; do
  if [[ -z "${!VAR}" ]]; then
    echo "ERROR: \$$VAR is not set."
    MISSING=1
  fi
done
if [[ $MISSING -eq 1 ]]; then
  usage
  exit 1
fi

# ── Helper ───────────────────────────────────────────────────────────────────
info()    { echo "[INFO]  $*"; }
success() { echo "[OK]    $*"; }
warn()    { echo "[WARN]  $*"; }

echo ""
echo "==========================================="
echo " Levo.ai — API Gateway Logging Setup"
echo "==========================================="
echo "  API ID     : $API_ID"
echo "  Stage      : $STAGE_NAME"
echo "  Log Group  : $LOG_GROUP"
echo "  Region     : $REGION"
echo "  Retention  : ${RETENTION_DAYS} days"
echo "==========================================="
echo ""

# ── 1. Verify the API exists ─────────────────────────────────────────────────
info "Verifying API Gateway API..."
API_NAME=$(aws apigatewayv2 get-api \
  --api-id "$API_ID" \
  --region "$REGION" \
  --query 'Name' --output text 2>&1) || {
  echo "ERROR: API ID '$API_ID' not found in region '$REGION'. Check your API_ID and REGION."
  exit 1
}
success "Found API: $API_NAME ($API_ID)"

# ── 2. Create log group (idempotent) ─────────────────────────────────────────
info "Creating log group '$LOG_GROUP'..."
aws logs create-log-group \
  --log-group-name "$LOG_GROUP" \
  --region "$REGION" 2>/dev/null && success "Log group created." || warn "Log group already exists — skipping."

# ── 3. Set retention policy ──────────────────────────────────────────────────
info "Setting retention to ${RETENTION_DAYS} days..."
aws logs put-retention-policy \
  --log-group-name "$LOG_GROUP" \
  --retention-in-days "$RETENTION_DAYS" \
  --region "$REGION"
success "Retention policy set."

# ── 4. Get log group ARN (strip trailing :* that API Gateway rejects) ─────────
info "Fetching log group ARN..."
LOG_GROUP_ARN=$(aws logs describe-log-groups \
  --log-group-name-prefix "$LOG_GROUP" \
  --region "$REGION" \
  --query 'logGroups[0].arn' --output text | sed 's/:*$//')

if [[ -z "$LOG_GROUP_ARN" || "$LOG_GROUP_ARN" == "None" ]]; then
  echo "ERROR: Could not retrieve ARN for log group '$LOG_GROUP'."
  exit 1
fi
success "Log group ARN: $LOG_GROUP_ARN"

# ── 5. Enable access logging on the stage ────────────────────────────────────
# $context.* variables are intentionally single-quoted so bash does not expand them.
FORMAT='{"host":"$context.domainName","method":"$context.httpMethod","path":"$context.path","agent":"$context.identity.userAgent","code":"$context.status","requestId":"$context.requestId","ip":"$context.identity.sourceIp","requestTime":"$context.requestTime","routeKey":"$context.routeKey","protocol":"$context.protocol","responseLength":"$context.responseLength"}'

info "Configuring access logging on stage '$STAGE_NAME'..."
aws apigatewayv2 update-stage \
  --api-id "$API_ID" \
  --stage-name "$STAGE_NAME" \
  --access-log-settings DestinationArn="$LOG_GROUP_ARN",Format="$FORMAT" \
  --region "$REGION" \
  --output table
success "Access logging enabled."

# ── 6. Verify the stage now has logging configured ───────────────────────────
info "Verifying stage configuration..."
CONFIGURED_ARN=$(aws apigatewayv2 get-stage \
  --api-id "$API_ID" \
  --stage-name "$STAGE_NAME" \
  --region "$REGION" \
  --query 'AccessLogSettings.DestinationArn' --output text)

if [[ "$CONFIGURED_ARN" == "$LOG_GROUP_ARN" ]]; then
  success "Stage verified — logs will flow to $LOG_GROUP"
else
  warn "Stage ARN mismatch. Expected: $LOG_GROUP_ARN | Got: $CONFIGURED_ARN"
fi

# ── 7. Tail the log group ────────────────────────────────────────────────────
echo ""
echo "==========================================="
echo " Setup complete. Tailing logs..."
echo " Send a request to your API to generate"
echo " log entries, then Ctrl+C to stop."
echo "  API URL: $(aws apigatewayv2 get-api --api-id "$API_ID" --region "$REGION" --query 'ApiEndpoint' --output text)"
echo "==========================================="
echo ""
aws logs tail --follow "$LOG_GROUP" --region "$REGION"
