#!/bin/bash
#
# Release script for Sentinel Package Manager
# Usage: ./scripts/release.sh [patch|minor|major|1.0.0]
#

set -e

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

# Get current version
CURRENT_VERSION=$(node -p "require('./package.json').version")
echo -e "${BLUE}📦 Current version: ${CURRENT_VERSION}${NC}"

# Determine new version
if [ -z "$1" ]; then
  echo -e "${RED}❌ Error: Version or bump type required${NC}"
  echo "Usage: ./scripts/release.sh [patch|minor|major|1.0.0]"
  exit 1
fi

# Check if it's a semantic version or bump type
if [[ "$1" =~ ^[0-9]+\.[0-9]+\.[0-9]+ ]]; then
  # Direct version specified
  NEW_VERSION="$1"
else
  # Bump type (patch, minor, major)
  BUMP_TYPE="$1"
  if [[ ! "$BUMP_TYPE" =~ ^(patch|minor|major)$ ]]; then
    echo -e "${RED}❌ Error: Invalid bump type. Use: patch, minor, or major${NC}"
    exit 1
  fi
  
  # Calculate new version using npm version command (dry run)
  NEW_VERSION=$(npm version "$BUMP_TYPE" --dry-run --no-git-tag-version | sed 's/v//')
  # Reset package.json (npm version modified it)
  git checkout package.json
fi

echo -e "${BLUE}🚀 New version: ${NEW_VERSION}${NC}"

# Auto-update CHANGELOG.md if "Unreleased" section exists
if [ -f CHANGELOG.md ]; then
  if grep -q "## \[$NEW_VERSION\]" CHANGELOG.md; then
    echo -e "${GREEN}✅ CHANGELOG.md already has entry for $NEW_VERSION${NC}"
  elif grep -q "## \[Unreleased\]" CHANGELOG.md; then
    echo -e "${BLUE}📝 Auto-updating CHANGELOG.md...${NC}"
    RELEASE_DATE=$(date +%Y-%m-%d)
    # Replace "## [Unreleased]" with "## [$NEW_VERSION] - $RELEASE_DATE"
    if [[ "$OSTYPE" == "darwin"* ]]; then
      # macOS
      sed -i '' "s/## \[Unreleased\]/## [$NEW_VERSION] - $RELEASE_DATE/" CHANGELOG.md
    else
      # Linux
      sed -i "s/## \[Unreleased\]/## [$NEW_VERSION] - $RELEASE_DATE/" CHANGELOG.md
    fi
    echo -e "${GREEN}✅ Updated CHANGELOG.md: '## [$NEW_VERSION] - $RELEASE_DATE'${NC}"
  else
    echo -e "${YELLOW}⚠️  CHANGELOG.md doesn't have 'Unreleased' section${NC}"
    echo -e "${YELLOW}   Consider adding changelog entry manually${NC}"
    read -p "$(echo -e ${YELLOW}Continue without CHANGELOG update? [y/N]: ${NC})" -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
      echo -e "${YELLOW}Cancelled${NC}"
      exit 1
    fi
  fi
else
  echo -e "${YELLOW}⚠️  CHANGELOG.md not found - creating it...${NC}"
  RELEASE_DATE=$(date +%Y-%m-%d)
  cat > CHANGELOG.md <<EOF
# Changelog

All notable changes to this project will be documented in this file.

The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [$NEW_VERSION] - $RELEASE_DATE

### Added
- Initial release

## [Unreleased]

EOF
  echo -e "${GREEN}✅ Created CHANGELOG.md${NC}"
fi

# Confirm
read -p "$(echo -e ${YELLOW}Continue with release? [y/N]: ${NC})" -n 1 -r
echo
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
  echo -e "${YELLOW}Cancelled${NC}"
  exit 1
fi

# Update package.json version
echo -e "${BLUE}📝 Updating package.json...${NC}"
node -e "
const fs = require('fs');
const pkg = require('./package.json');
pkg.version = '$NEW_VERSION';
fs.writeFileSync('./package.json', JSON.stringify(pkg, null, 2) + '\n');
"

# Security: Verify package.json has zero dependencies
echo -e "${BLUE}🔐 Verifying security...${NC}"
if ! node -e "const pkg = require('./package.json'); if (pkg.dependencies || pkg.devDependencies) { console.error('ERROR: Dependencies found!'); process.exit(1); }"; then
  echo -e "${RED}❌ ERROR: Dependencies detected in package.json${NC}"
  echo -e "${RED}   This package should have zero dependencies${NC}"
  exit 1
fi
echo -e "${GREEN}✅ Zero dependencies verified${NC}"

# Security: Verify no node_modules directory exists
if [ -d "node_modules" ]; then
  echo -e "${RED}❌ ERROR: node_modules directory found!${NC}"
  echo -e "${RED}   This repository should not have any installed dependencies${NC}"
  exit 1
fi
echo -e "${GREEN}✅ No node_modules directory found${NC}"

# Run tests
echo -e "${BLUE}🧪 Running tests...${NC}"
npm run test:smoke

# Commit changes
echo -e "${BLUE}📝 Committing version bump...${NC}"
git add package.json
# Always include CHANGELOG.md if it exists (it was auto-updated)
if [ -f CHANGELOG.md ]; then
  git add CHANGELOG.md
fi
git commit -m "chore: bump version to $NEW_VERSION"

# Create tag
TAG="v$NEW_VERSION"
echo -e "${BLUE}🏷️  Creating tag: $TAG${NC}"
git tag -a "$TAG" -m "Release $TAG"

# Show summary
echo ""
echo -e "${GREEN}✅ Release prepared!${NC}"
echo ""
echo -e "${BLUE}Next steps:${NC}"
echo -e "  1. Review changes: ${YELLOW}git log HEAD~1..HEAD${NC}"
echo -e "  2. Push commits: ${YELLOW}git push${NC}"
echo -e "  3. Push tag: ${YELLOW}git push origin $TAG${NC}"
echo ""
echo -e "${BLUE}Or push both at once:${NC}"
echo -e "  ${YELLOW}git push && git push origin $TAG${NC}"
echo ""
echo -e "${BLUE}The GitHub Actions workflow will:${NC}"
echo -e "  • Publish to npm as @dreamhorizonorg/sentinel@$NEW_VERSION"
echo -e "  • Create GitHub release: $TAG"
echo -e "  • Link npm package and GitHub release"
echo ""

