#!/bin/bash
set -e

export ANTHROPIC_API_KEY="${ANTHROPIC_API_KEY}"

echo "Starting Claude Code session..."
echo "Session ID: ${SESSION_ID}"

# Decode the base64 prompt if provided, otherwise use regular prompt
# if [ -n "${USER_PROMPT_B64}" ]; then
USER_PROMPT=$(echo "${USER_PROMPT_B64}" | base64 -d)
# fi
echo "User Prompt: ${USER_PROMPT}"

# Read prompt template and substitute USER_PROMPT
FULL_PROMPT=$(cat /app/prompt-user.md)
FULL_PROMPT="${FULL_PROMPT//\{USER_PROMPT\}/${USER_PROMPT}}"
SYSTEM_PROMPT=$(cat /app/prompt-system.md)

# Run Claude Code with permissions automatically accepted
# https://docs.anthropic.com/en/docs/claude-code/sdk#available-cli-options
timeout 900 claude -p "$FULL_PROMPT" \
  --model sonnet \
  --permission-mode bypassPermissions \
  --system-prompt "$SYSTEM_PROMPT" \
  --verbose
#  --max-turns 30

EXIT_CODE=$?
if [ $EXIT_CODE -eq 124 ]; then
  echo "ERROR: Claude timed out after 10 minutes"
elif [ $EXIT_CODE -ne 0 ]; then
  echo "ERROR: Claude failed with exit code $EXIT_CODE"
fi

echo "=== Checking workspace contents ==="
ls -la /workspace/

if [ -f "/workspace/output.json" ]; then
  echo "=== Generated JSON ==="
  cat /workspace/output.json
  echo ""
  echo "======================"

  # Upload to Cloud Storage
  echo "Uploading to Cloud Storage..."
  gsutil cp /workspace/output.json gs://${BUCKET_NAME}/sessions/${SESSION_ID}/output.json

  if [ $? -eq 0 ]; then
    echo "Successfully uploaded to gs://${BUCKET_NAME}/sessions/${SESSION_ID}/output.json"
  else
    echo "WARNING: Failed to upload to Cloud Storage, but output.json was generated successfully"
  fi

  echo "Successfully generated output.json"
  exit 0
else
  echo "ERROR: No output.json generated"
  echo "=== Workspace contents: ==="
  ls -la /workspace/
  echo "=== TypeScript files found: ==="
  find /workspace -name "*.ts" -type f
  exit 1
fi