#!/bin/bash
set -e

IMAGE_NAME="resume:latest"
CONTAINER_NAME="resume_test_container"
DOCKER_DIR="docker"
RESUME_DIR="$DOCKER_DIR/resume"

# Note: We no longer need to manually update the CSS hash here
# as it's handled by the update-csp-hashes.sh script during Docker build

# Build Docker image
cd "$DOCKER_DIR"
echo "Building Docker image..."
docker build -t $IMAGE_NAME ./resume/

# Stop and remove any previous container
if [ $(docker ps -aq -f name=$CONTAINER_NAME) ]; then
  echo "Removing previous test container..."
  docker rm -f $CONTAINER_NAME || true
fi

# Ensure port 8080 is free
echo "Ensuring port 8080 is free..."
lsof -i :8080 | grep LISTEN | awk '{print $2}' | xargs kill -9 || true

# Run Docker container in the background
echo "Starting Docker container..."
docker run -d --name $CONTAINER_NAME -p 8080:8080 $IMAGE_NAME

# Wait for the server to be ready
MAX_TRIES=20
TRIES=0
until curl -s http://localhost:8080/ > /dev/null; do
  TRIES=$((TRIES+1))
  if [ $TRIES -ge $MAX_TRIES ]; then
    echo "Server did not start in time."
    docker rm -f $CONTAINER_NAME
    exit 1
  fi
  echo "Waiting for server... ($TRIES/$MAX_TRIES)"
  sleep 2
done

echo "Server is up. Running tests..."
cd ..

npm install
npm run setup
# Run tests and save output for AI parsing
if npm test > test_output.log 2>&1; then
  echo "Tests passed. Committing and pushing changes."
  git add .
  git commit -m "Automated build, test, and deploy"
  git push
else
  echo "Tests failed. Not deploying."
  cat test_output.log
  docker rm -f $CONTAINER_NAME
  exit 1
fi

# Optionally open report in browser if available, but don't require interaction
echo "Test output saved to test_output.log for AI parsing."
if command -v open >/dev/null 2>&1; then
  echo "Opening HTML report in browser (if available)..."
  open http://localhost:9323 || echo "Could not open browser automatically. Please visit http://localhost:9323 to view the report."
else
  echo "Browser opening not supported. Report available at http://localhost:9323 if a server is running."
fi

echo "Cleaning up Docker container..."
docker rm -f $CONTAINER_NAME

echo "Done." 