#!/bin/bash
set -e

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

BUILD_DIR="../claude-code-build"

# -------------------------
# Clean previous build
# -------------------------
rm -rf ${BUILD_DIR}
mkdir -p ${BUILD_DIR}
cd ${BUILD_DIR}

# -------------------------
# Build source code
# -------------------------
pushd ..

# Build docs & samples
echo "Building documentation..."
yarn build:docs

# Generate .d.ts files
echo "Generating TypeScript declarations..."
npx tsc --declaration --emitDeclarationOnly --outDir dist/types

popd

# -------------------------
# Copy necessary files
# -------------------------
echo "Copying MDK files..."
cp ../package*.json ./
cp ../tsconfig*.json ./
cp ../index.ts ./
cp -r ../dist/docs ./
cp -r ../dist/types/src ./types/
cp -r ../src ./
[ -d "../lib" ] && cp -r ../lib ./

# Copy template app 1
echo "Copying template app 1..."
cp -r ../template-app-1 ./

# Copy Dockerfile
cp ../gcp/Dockerfile ./
cp ../gcp/.dockerignore ./

# Copy your prompt files
cp ../gcp/prompt-user.md ./
cp ../gcp/prompt-system.md ./
cp ../gcp/CLAUDE.md ./

# Copy run-claude.sh file & make it executable
cp ../gcp/run-claude.sh ./
chmod +x run-claude.sh

# -------------------------
# Verify we have what we need
# -------------------------
if [ ! -f "package.json" ]; then
  echo "ERROR: package.json not found"
  exit 1
fi

if [ ! -f "Dockerfile" ]; then
  echo "ERROR: Dockerfile not found in gcp directory"
  exit 1
fi

if [ ! -f "prompt-user.md" ]; then
  echo "ERROR: prompt-user.md not found in gcp directory"
  exit 1
fi

if [ ! -f "prompt-system.md" ]; then
  echo "ERROR: prompt-system.md not found in gcp directory"
  exit 1
fi

if [ ! -f "docs/DOCS.md" ]; then
  echo "ERROR: docs/DOCS.md not found in gcp directory"
  exit 1
fi

if [ ! -f "run-claude.sh" ]; then
  echo "ERROR: run-claude.sh not found in gcp directory"
  exit 1
fi

# -------------------------
# Show what we're building
# -------------------------
echo "Build directory contents:"
ls -la

# -------------------------
# Build and push
# -------------------------
echo "Building Docker image..."
gcloud builds submit \
  --tag="${REGION}-docker.pkg.dev/${PROJECT_ID}/containers/claude-code-jigx" .

# -------------------------
# Clean up build directory
# -------------------------
echo "DEBUG: About to change directory from $(pwd)"
cd ..
echo "DEBUG: Now in directory $(pwd)"
echo "DEBUG: About to remove ${BUILD_DIR}"
rm -rf "${BUILD_DIR}"
echo "Build complete and cleaned up!"
echo "DEBUG: Script ending normally"