#!/bin/bash

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

echo -e "${BLUE}=========================================${NC}"
echo -e "${BLUE}  Payload CMS MCP Server NPM Publisher   ${NC}"
echo -e "${BLUE}=========================================${NC}"
echo ""

# Check if user is logged in to npm
echo -e "${BLUE}Checking npm login status...${NC}"
NPM_USER=$(npm whoami 2>/dev/null)
NPM_STATUS=$?

if [ $NPM_STATUS -ne 0 ]; then
    echo -e "${YELLOW}You are not logged in to npm. Please log in:${NC}"
    npm login
    
    if [ $? -ne 0 ]; then
        echo -e "${RED}Failed to log in to npm. Aborting.${NC}"
        exit 1
    fi
    
    NPM_USER=$(npm whoami)
fi

echo -e "${GREEN}Logged in as: $NPM_USER${NC}"
echo ""

# Get package version
PACKAGE_VERSION=$(node -p "require('./package.json').version")
echo -e "${BLUE}Publishing version ${YELLOW}$PACKAGE_VERSION${BLUE} to npm...${NC}"
echo ""

# Confirm with user
read -p "Are you sure you want to publish version $PACKAGE_VERSION? (y/n) " -n 1 -r
echo ""

if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    echo -e "${YELLOW}Publication aborted.${NC}"
    exit 0
fi

echo ""
echo -e "${BLUE}Running tests...${NC}"
npm test

if [ $? -ne 0 ]; then
    echo -e "${RED}Tests failed. Aborting publication.${NC}"
    exit 1
fi

echo ""
echo -e "${BLUE}Publishing to npm...${NC}"
npm publish --access public

if [ $? -eq 0 ]; then
    echo ""
    echo -e "${GREEN}Successfully published version $PACKAGE_VERSION to npm!${NC}"
    echo -e "${GREEN}Package URL: ${BLUE}https://www.npmjs.com/package/payload-cms-mcp${NC}"
    
    # Create and push git tag
    echo ""
    echo -e "${BLUE}Creating git tag v$PACKAGE_VERSION...${NC}"
    git tag -a "v$PACKAGE_VERSION" -m "Release v$PACKAGE_VERSION"
    
    echo -e "${BLUE}Pushing tags to remote repository...${NC}"
    git push --tags
    
    echo ""
    echo -e "${GREEN}Publication complete!${NC}"
else
    echo ""
    echo -e "${RED}Failed to publish to npm. Please check the error messages above.${NC}"
    exit 1
fi 