#!/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
USER_PROMPT=$(echo "${USER_PROMPT_B64}" | base64 -d)
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" \
  --permission-mode bypassPermissions \
  --system-prompt "$SYSTEM_PROMPT" \
  --verbose \
  --model sonnet
# --max-turns 30

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

echo "=== Generating output.json from built application ==="
cd /app/template-app-1/

# Check if app.ts exists
if [ ! -f "app.ts" ]; then
  echo "ERROR: app.ts not found in /app/template-app-1/"
  exit 1
fi

echo "Running type check..."
npx tsc --noEmit --incremental false

if [ $? -ne 0 ]; then
  echo "ERROR: Type check failed. Fix TypeScript errors before generating output."
  exit 1
fi

echo "Type check passed. Executing app.ts to generate JSON..."

# Execute the generation script using tsx
cd /app
npx tsx /app/generate-output.js
GENERATE_EXIT_CODE=$?

if [ $GENERATE_EXIT_CODE -ne 0 ]; then
  echo "ERROR: Failed to generate output.json"
  exit 1
fi

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

if [ ! -f "/workspace/output.json" ]; then
  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

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 [ $? -ne 0 ]; then
  echo "ERROR: Failed to upload to Cloud Storage"
  exit 1
fi

echo "Successfully uploaded to gs://${BUCKET_NAME}/sessions/${SESSION_ID}/output.json"
echo "Successfully generated output.json"
exit 0