#!/bin/bash

# Simple NPM package validation script
# Checks package readiness without requiring Node.js dependencies

echo "🚀 Sophia NPM Package Validation"
echo "================================="

ERRORS=0

# Check required files
echo -e "\n📁 Checking required files..."

REQUIRED_FILES=(
    "package.json"
    "README.md" 
    "PRODUCTION_READY.md"
    "CLAUDE.md"
    "AGENTS.md"
    "setup.sh"
    "requirements.txt"
    "src/cli.py"
    "src/groq_client.py"
    "config/security.py"
    "scripts/postinstall.js"
)

for file in "${REQUIRED_FILES[@]}"; do
    if [[ -f "$file" ]]; then
        echo "✅ $file"
    else
        echo "❌ Missing: $file"
        ((ERRORS++))
    fi
done

# Check required directories
echo -e "\n📂 Checking directory structure..."

REQUIRED_DIRS=(
    "src"
    "config" 
    "plugins"
    "tests"
    "scripts"
    "bin"
    "lib"
)

for dir in "${REQUIRED_DIRS[@]}"; do
    if [[ -d "$dir" ]]; then
        echo "✅ $dir/"
    else
        echo "❌ Missing directory: $dir/"
        ((ERRORS++))
    fi
done

# Check package.json version
echo -e "\n📦 Checking package.json..."

if [[ -f "package.json" ]]; then
    VERSION=$(grep '"version"' package.json | sed 's/.*"version": *"\([^"]*\)".*/\1/')
    if [[ "$VERSION" =~ ^1\. ]]; then
        echo "✅ Version: $VERSION (production ready)"
    else
        echo "❌ Version should be 1.0.0+ for production: $VERSION"
        ((ERRORS++))
    fi
    
    # Check if dependencies are pinned (basic check)
    if grep -q '\^' package.json || grep -q '~' package.json; then
        echo "⚠️  Some dependencies may not be pinned (found ^ or ~)"
    else
        echo "✅ Dependencies appear to be pinned"
    fi
else
    echo "❌ package.json not found"
    ((ERRORS++))
fi

# Check git status
echo -e "\n🔄 Checking git status..."
if git status --porcelain | grep -q .; then
    echo "❌ Uncommitted changes found"
    git status --porcelain
    ((ERRORS++))
else
    echo "✅ No uncommitted changes"
fi

# Check for obvious secrets
echo -e "\n🔒 Basic security check..."
if grep -r "gsk_" package.json scripts/ 2>/dev/null | grep -v "your_api_key_here" | grep -v "example" | grep -v "// Groq API key" | grep -v "pattern" | grep -v "regex"; then
    echo "❌ Potential API key found in package files"
    ((ERRORS++))
else
    echo "✅ No obvious secrets in package files"
fi

# Summary
echo -e "\n================================="
if [[ $ERRORS -eq 0 ]]; then
    echo "🎉 ALL CHECKS PASSED - Ready for npm publish!"
    echo ""
    echo "💡 Next steps:"
    echo "   npm publish --dry-run"
    echo "   npm publish"
    exit 0
else
    echo "⚠️  $ERRORS ISSUE(S) FOUND - Fix before publishing"
    exit 1
fi