#!/bin/bash

# =====================================================
# Seraph3 Demo Preparation Script
# =====================================================
# This script prepares the Seraph3 project for demo distribution
# by removing sensitive data and cleaning up unnecessary files.
#
# Usage: ./prepare-demo.sh [--full]
#   --full    Perform full cleanup including dependencies and builds
#
# =====================================================

set -e

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

# Determine cleanup level
FULL_CLEAN=false
if [ "$1" == "--full" ]; then
    FULL_CLEAN=true
fi

echo -e "${BLUE}╔════════════════════════════════════════╗${NC}"
echo -e "${BLUE}║   Seraph3 Demo Preparation Script     ║${NC}"
echo -e "${BLUE}╔════════════════════════════════════════╗${NC}"
echo ""

if [ "$FULL_CLEAN" = true ]; then
    echo -e "${YELLOW}Mode: FULL CLEANUP (for distribution)${NC}"
else
    echo -e "${YELLOW}Mode: QUICK CLEANUP (for testing)${NC}"
    echo -e "${YELLOW}Tip: Use --full for complete cleanup${NC}"
fi
echo ""

# Confirmation
read -p "Are you sure you want to proceed? (yes/no): " confirm
if [ "$confirm" != "yes" ]; then
    echo -e "${RED}Aborted.${NC}"
    exit 1
fi
echo ""

# =====================================================
# Step 1: Remove Sensitive Environment Files
# =====================================================
echo -e "${GREEN}[1/8] Removing sensitive environment files...${NC}"

if [ -f .env ]; then
    echo "  - Removing .env"
    rm -f .env
fi

rm -f .env.production .env.local .env.staging .env.backup 2>/dev/null || true

if [ -f .env.demo ]; then
    echo -e "  ${GREEN}✓${NC} .env.demo preserved"
else
    echo -e "  ${RED}⚠${NC} .env.demo not found!"
fi
echo ""

# =====================================================
# Step 2: Clear Logs and Cache
# =====================================================
echo -e "${GREEN}[2/8] Clearing logs and cache...${NC}"

# Clear logs
if [ -d storage/logs ]; then
    rm -f storage/logs/*.log 2>/dev/null || true
    echo "  - Cleared storage/logs/"
fi

# Clear framework cache
rm -rf storage/framework/cache/* 2>/dev/null || true
rm -rf storage/framework/sessions/* 2>/dev/null || true
rm -rf storage/framework/views/* 2>/dev/null || true
echo "  - Cleared framework cache"

# Clear bootstrap cache
rm -rf bootstrap/cache/*.php 2>/dev/null || true
echo "  - Cleared bootstrap cache"
echo ""

# =====================================================
# Step 3: Remove User Uploads and Data
# =====================================================
echo -e "${GREEN}[3/8] Removing user uploads and data...${NC}"

rm -rf public/uploads/* 2>/dev/null || true
rm -rf storage/app/public/uploads/* 2>/dev/null || true
rm -rf storage/files/* 2>/dev/null || true
echo "  - Cleared upload directories"
echo ""

# =====================================================
# Step 4: Remove Database Files
# =====================================================
echo -e "${GREEN}[4/8] Removing database dumps and exports...${NC}"

# Find and remove SQL files
SQL_COUNT=$(find . -name "*.sql" -type f 2>/dev/null | wc -l)
if [ $SQL_COUNT -gt 0 ]; then
    find . -name "*.sql" -type f -delete 2>/dev/null || true
    echo "  - Removed $SQL_COUNT SQL dump files"
fi

# Remove compressed SQL files
SQLGZ_COUNT=$(find . -name "*.sql.gz" -type f 2>/dev/null | wc -l)
if [ $SQLGZ_COUNT -gt 0 ]; then
    find . -name "*.sql.gz" -type f -delete 2>/dev/null || true
    echo "  - Removed $SQLGZ_COUNT compressed SQL files"
fi

# Remove schema exports
rm -rf database/schema/*.sql 2>/dev/null || true
rm -rf database/backups/* 2>/dev/null || true
echo "  - Cleared schema and backup directories"
echo ""

# =====================================================
# Step 5: Remove Security Keys
# =====================================================
echo -e "${GREEN}[5/8] Removing OAuth and security keys...${NC}"

rm -f storage/oauth-*.key 2>/dev/null || true
rm -f storage/oauth-public.key storage/oauth-private.key 2>/dev/null || true
echo "  - Removed OAuth keys"

# Remove SSL certificates
rm -rf certbot/conf/live/* 2>/dev/null || true
rm -rf certbot/conf/archive/* 2>/dev/null || true
rm -rf certbot/conf/renewal/* 2>/dev/null || true
echo "  - Removed SSL certificates"
echo ""

# =====================================================
# Step 6: Remove IDE Files
# =====================================================
echo -e "${GREEN}[6/8] Removing IDE and development files...${NC}"

rm -rf .idea .vscode 2>/dev/null || true
rm -f .phpstorm.meta.php _ide_helper.php _ide_helper_models.php 2>/dev/null || true
rm -f .phpunit.result.cache 2>/dev/null || true
echo "  - Removed IDE files"
echo ""

# =====================================================
# Step 7: Full Cleanup (Optional)
# =====================================================
if [ "$FULL_CLEAN" = true ]; then
    echo -e "${GREEN}[7/8] Performing full cleanup...${NC}"

    # Remove dependencies
    if [ -d vendor ]; then
        echo "  - Removing vendor/ directory..."
        rm -rf vendor/
    fi

    if [ -d node_modules ]; then
        echo "  - Removing node_modules/ directory..."
        rm -rf node_modules/
    fi

    # Remove compiled assets
    rm -f public/js/app.js 2>/dev/null || true
    rm -f public/js/vendor.js 2>/dev/null || true
    rm -f public/css/main.css 2>/dev/null || true
    rm -f public/mix-manifest.json 2>/dev/null || true
    rm -f public/hot 2>/dev/null || true
    echo "  - Removed compiled assets"

    # Remove Docker volumes data
    rm -rf docker/mysql/data/* 2>/dev/null || true
    rm -rf docker/redis/data/* 2>/dev/null || true
    echo "  - Cleared Docker volume data"
else
    echo -e "${YELLOW}[7/8] Skipping full cleanup (use --full to enable)${NC}"
fi
echo ""

# =====================================================
# Step 8: Verification
# =====================================================
echo -e "${GREEN}[8/8] Verifying cleanup...${NC}"

# Check for .env files
ENV_COUNT=$(find . -maxdepth 1 -name ".env*" -not -name ".env.demo" -not -name ".env.example" 2>/dev/null | wc -l)
if [ $ENV_COUNT -gt 0 ]; then
    echo -e "  ${RED}⚠ Warning: Found $ENV_COUNT .env files${NC}"
    find . -maxdepth 1 -name ".env*" -not -name ".env.demo" -not -name ".env.example"
else
    echo -e "  ${GREEN}✓${NC} No sensitive .env files found"
fi

# Check for SQL files
SQL_COUNT=$(find . -name "*.sql" 2>/dev/null | wc -l)
if [ $SQL_COUNT -gt 0 ]; then
    echo -e "  ${RED}⚠ Warning: Found $SQL_COUNT SQL files${NC}"
else
    echo -e "  ${GREEN}✓${NC} No SQL dump files found"
fi

# Check for OAuth keys
OAUTH_COUNT=$(find storage -name "oauth-*.key" 2>/dev/null | wc -l)
if [ $OAUTH_COUNT -gt 0 ]; then
    echo -e "  ${RED}⚠ Warning: Found $OAUTH_COUNT OAuth key files${NC}"
else
    echo -e "  ${GREEN}✓${NC} No OAuth keys found"
fi

echo ""

# =====================================================
# Summary
# =====================================================
echo -e "${BLUE}╔════════════════════════════════════════╗${NC}"
echo -e "${BLUE}║         Cleanup Complete! ✓            ║${NC}"
echo -e "${BLUE}╔════════════════════════════════════════╗${NC}"
echo ""
echo -e "${GREEN}Next Steps:${NC}"
echo ""
echo "1. Review git status:"
echo "   ${YELLOW}git status${NC}"
echo ""
echo "2. Check for sensitive data:"
echo "   ${YELLOW}grep -r 'computerassistance\\|@gmail' . --exclude-dir=vendor --exclude-dir=node_modules${NC}"
echo ""
echo "3. Test the demo setup:"
echo "   ${YELLOW}cp .env.demo .env${NC}"
echo "   ${YELLOW}docker-compose up -d${NC}"
echo ""

if [ "$FULL_CLEAN" = true ]; then
    echo "4. Install dependencies:"
    echo "   ${YELLOW}docker-compose exec app composer install${NC}"
    echo "   ${YELLOW}docker-compose exec app npm install${NC}"
    echo ""
fi

echo "5. Read the demo setup guide:"
echo "   ${YELLOW}cat DEMO_SETUP_GUIDE.md${NC}"
echo ""
echo -e "${GREEN}Your project is ready for demo distribution! 🚀${NC}"
echo ""
