#!/bin/bash
set -e

source ./config.sh
echo "Using project: ${PROJECT_ID} in region: ${REGION}"

clear

# Option 1: Get logs for the most recent execution using gcloud logging
echo "Getting logs for most recent execution..."
LATEST_EXECUTION=$(gcloud run jobs executions list \
  --job=claude-code-jigx \
  --region=${REGION} \
  --format="value(name)" \
  --limit=1)

if [ -n "$LATEST_EXECUTION" ]; then
  echo "Latest execution: $LATEST_EXECUTION"
  echo ""
  
  # Extract execution ID from the full name
  EXECUTION_ID=$(echo $LATEST_EXECUTION | rev | cut -d'-' -f1 | rev)
  
  # Use gcloud logging to read logs
  gcloud logging read \
    "resource.type=cloud_run_job AND \
     resource.labels.job_name=claude-code-jigx AND \
     resource.labels.location=${REGION} AND \
     labels.execution_name=$LATEST_EXECUTION" \
    --limit=200 \
    --format="table(timestamp,textPayload)" \
    --order="asc"
else
  echo "No executions found"
fi

# Option 2: Show recent logs without filtering by execution
# echo -e "\n--- Recent job logs (all executions) ---\n"
# gcloud logging read \
#   "resource.type=cloud_run_job AND \
#    resource.labels.job_name=claude-code-jigx AND \
#    resource.labels.location=${REGION}" \
#   --limit=200 \
#   --format="table(timestamp,textPayload)" \
#   --order="desc"