#!/bin/bash

# This script prepares and publishes the package to npm

# Colors for better output
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m' # No Color

echo -e "${YELLOW}Starting publish process for claudes-office v0.4.0${NC}"

# Check if logged in to npm
echo -e "${YELLOW}Checking npm login status...${NC}"
NPM_USER=$(npm whoami 2>/dev/null)
if [ $? -ne 0 ]; then
  echo -e "${RED}You are not logged in to npm. Please run 'npm login' first.${NC}"
  exit 1
fi
echo -e "${GREEN}Logged in as $NPM_USER${NC}"

# Clean and rebuild
echo -e "${YELLOW}Cleaning and rebuilding the project...${NC}"
rm -rf dist/
npm run build
if [ $? -ne 0 ]; then
  echo -e "${RED}Build failed. Please fix the errors before publishing.${NC}"
  exit 1
fi
echo -e "${GREEN}Build completed successfully.${NC}"

# Run tests
echo -e "${YELLOW}Running tests...${NC}"
npm test
if [ $? -ne 0 ]; then
  echo -e "${RED}Tests failed. Please fix the tests before publishing.${NC}"
  exit 1
fi
echo -e "${GREEN}Tests passed.${NC}"

# Final confirmation
echo -e "${YELLOW}Ready to publish claudes-office v0.4.0 to npm.${NC}"
read -p "Do you want to continue? (y/n) " -n 1 -r
echo
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
  echo -e "${YELLOW}Publication cancelled.${NC}"
  exit 0
fi

# Publish to npm
echo -e "${YELLOW}Publishing to npm...${NC}"
npm publish
if [ $? -ne 0 ]; then
  echo -e "${RED}Publication failed.${NC}"
  exit 1
fi

echo -e "${GREEN}Successfully published claudes-office v0.4.0 to npm!${NC}"
echo -e "${YELLOW}Remember to create a git tag for this release:${NC}"
echo -e "git tag v0.4.0"
echo -e "git push origin v0.4.0"