#!/bin/bash

# Clean script for Stock Bot Trading Platform

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

# Default options
MODULES=false
DIST=false
CACHE=false
TSBUILDINFO=false
ALL=false
FRESH=false
FORCE=false

# Parse command line arguments
while [[ $# -gt 0 ]]; do
    case $1 in
        --modules|-m)
            MODULES=true
            shift
            ;;
        --dist|-d)
            DIST=true
            shift
            ;;
        --cache|-c)
            CACHE=true
            shift
            ;;
        --tsbuildinfo|-t)
            TSBUILDINFO=true
            shift
            ;;
        --all|-a)
            ALL=true
            shift
            ;;
        --fresh|-f)
            FRESH=true
            shift
            ;;
        --force)
            FORCE=true
            shift
            ;;
        --help|-h)
            echo "Usage: $0 [options]"
            echo "  --modules, -m      Remove node_modules directories"
            echo "  --dist, -d         Remove dist directories and build caches"
            echo "  --cache, -c        Remove cache directories"
            echo "  --tsbuildinfo, -t  Remove TypeScript build info files"
            echo "  --all, -a          Remove everything (destructive)"
            echo "  --fresh, -f        Remove everything and reinstall dependencies"
            echo "  --force            Skip confirmation prompts"
            echo "  --help, -h         Show this help message"
            exit 0
            ;;
        *)
            echo "Unknown option: $1"
            echo "Use --help for usage information"
            exit 1
            ;;
    esac
done

remove_directories_by_name() {
    local name="$1"
    local description="$2"
    
    echo -e "${BLUE}Removing $description...${NC}"
    
    # Find and remove directories
    found_dirs=$(find . -name "$name" -type d 2>/dev/null)
    
    if [ -n "$found_dirs" ]; then
        count=$(echo "$found_dirs" | wc -l)
        echo -e "${GRAY}Found $count $description to remove${NC}"
        echo "$found_dirs" | while read -r dir; do
            if [ -d "$dir" ]; then
                rm -rf "$dir" 2>/dev/null
                echo -e "${GRAY}  Removed: $dir${NC}"
            fi
        done
    else
        echo -e "${GRAY}No $description found${NC}"
    fi
}

remove_files_by_pattern() {
    local pattern="$1"
    local description="$2"
    
    echo -e "${BLUE}Removing $description...${NC}"
    
    # Find and remove files
    found_files=$(find . -name "$pattern" -type f 2>/dev/null)
    
    if [ -n "$found_files" ]; then
        count=$(echo "$found_files" | wc -l)
        echo -e "${GRAY}Found $count $description to remove${NC}"
        echo "$found_files" | while read -r file; do
            if [ -f "$file" ]; then
                rm -f "$file" 2>/dev/null
                echo -e "${GRAY}  Removed: $file${NC}"
            fi
        done
    else
        echo -e "${GRAY}No $description found${NC}"
    fi
}

echo -e "${YELLOW}Starting cleanup...${NC}"

if [ "$ALL" = true ] || [ "$FRESH" = true ]; then
    if [ "$FORCE" != true ]; then
        echo -e "${RED}WARNING: This will remove ALL build artifacts, caches, dependencies, and temporary files!${NC}"
        echo -e "${YELLOW}This includes: node_modules, dist, all caches, logs, databases, and lock files${NC}"
        read -p "Are you sure you want to continue? (y/N): " confirmation
        
        if [[ "$confirmation" != "y" && "$confirmation" != "Y" ]]; then
            echo -e "${YELLOW}Operation cancelled.${NC}"
            exit 0
        fi
    fi
    
    echo -e "${RED}=== NUCLEAR CLEAN: Removing EVERYTHING ===${NC}"
    
    # Dependencies and packages
    remove_directories_by_name "node_modules" "node_modules directories"
    
    # Build outputs
    remove_directories_by_name "dist" "dist directories"
    remove_directories_by_name "build" "build directories"
    # remove_directories_by_name "lib" "lib directories"
    remove_directories_by_name "out" "out directories"
    remove_directories_by_name ".out" "build output directories"
    
    # Cache directories
    remove_directories_by_name ".turbo" "Turborepo cache directories"
    remove_directories_by_name ".next" "Next.js cache directories"
    remove_directories_by_name ".parcel-cache" "Parcel cache directories"
    remove_directories_by_name ".angular" "Angular CLI cache directories"
    remove_directories_by_name ".nuxt" "Nuxt.js cache directories"
    remove_directories_by_name ".vite" "Vite cache directories"
    remove_directories_by_name ".webpack" "Webpack cache directories"
    remove_directories_by_name ".rollup.cache" "Rollup cache directories"
    
    # Test and coverage
    remove_directories_by_name "coverage" "test coverage directories"
    remove_directories_by_name ".nyc_output" "NYC coverage directories"
    remove_directories_by_name ".jest" "Jest cache directories"
    remove_directories_by_name ".vitest" "Vitest cache directories"
    
    # Storybook
    remove_directories_by_name ".storybook-out" "Storybook build directories"
    remove_directories_by_name "storybook-static" "Storybook static directories"
    
    # Temporary and log directories
    remove_directories_by_name "tmp" "temporary directories"
    remove_directories_by_name "temp" "temp directories"
    remove_directories_by_name ".tmp" "hidden temp directories"
    remove_directories_by_name "logs" "log directories"
    remove_directories_by_name ".logs" "hidden log directories"
    
    # Project specific (from .gitignore)
    remove_directories_by_name ".data" "data directories"
    remove_directories_by_name ".backtest-results" "backtest result directories"
    remove_directories_by_name ".old" "old backup directories"
    remove_directories_by_name ".mongo" "MongoDB data directories"
    remove_directories_by_name ".chat" "chat directories"
    
    echo -e "${BLUE}Removing lock files...${NC}"
    rm -f bun.lockb package-lock.json yarn.lock pnpm-lock.yaml 2>/dev/null
    find . -name "bun.lockb" -type f -delete 2>/dev/null
    find . -name "package-lock.json" -type f -delete 2>/dev/null
    find . -name "yarn.lock" -type f -delete 2>/dev/null
    find . -name "pnpm-lock.yaml" -type f -delete 2>/dev/null
    
    # TypeScript and build files
    remove_files_by_pattern "*.tsbuildinfo" "TypeScript build info files"
    remove_files_by_pattern "*.d.ts" "TypeScript build info files"
    remove_files_by_pattern ".eslintcache" "ESLint cache files"
    remove_files_by_pattern ".stylelintcache" "Stylelint cache files"
    remove_files_by_pattern ".prettiercache" "Prettier cache files"
    
    # Database files
    remove_files_by_pattern "*.db" "database files"
    remove_files_by_pattern "*.sqlite" "SQLite database files"
    remove_files_by_pattern "*.sqlite3" "SQLite3 database files"
    
    # Log files
    remove_files_by_pattern "*.log" "log files"
    remove_files_by_pattern "npm-debug.log*" "npm debug logs"
    remove_files_by_pattern "yarn-debug.log*" "yarn debug logs"
    remove_files_by_pattern "yarn-error.log*" "yarn error logs"
    remove_files_by_pattern "lerna-debug.log*" "lerna debug logs"
    
    # OS generated files
    remove_files_by_pattern ".DS_Store" "macOS .DS_Store files"
    remove_files_by_pattern "Thumbs.db" "Windows thumbnail files"
    remove_files_by_pattern "ehthumbs.db" "Windows thumbnail cache files"
    remove_files_by_pattern "Desktop.ini" "Windows desktop files"
    
    echo -e "${RED}=== NUCLEAR CLEAN COMPLETE ===${NC}"
    echo -e "${BLUE}Cleanup complete - no need for turbo clean${NC}"
    
elif [ "$MODULES" = true ]; then
    remove_directories_by_name "node_modules" "node_modules directories"
    
    echo -e "${BLUE}Removing lock files...${NC}"
    rm -f bun.lockb 2>/dev/null
    find . -name "bun.lockb" -type f -delete 2>/dev/null
    
elif [ "$DIST" = true ]; then
    remove_directories_by_name "dist" "dist directories"
    remove_directories_by_name ".turbo" "Turborepo cache directories"
    remove_directories_by_name ".next" "Next.js cache directories"
    remove_directories_by_name ".parcel-cache" "Parcel cache directories"
    remove_directories_by_name ".angular" "Angular CLI cache directories"
    
    remove_files_by_pattern "*.tsbuildinfo" "TypeScript build info files"
    remove_files_by_pattern ".eslintcache" "ESLint cache files"
    
elif [ "$CACHE" = true ]; then
    remove_directories_by_name ".turbo" "Turborepo cache directories"
    remove_directories_by_name ".next" "Next.js cache directories"
    remove_directories_by_name ".parcel-cache" "Parcel cache directories"
    remove_directories_by_name ".angular" "Angular CLI cache directories"
    remove_directories_by_name "coverage" "test coverage directories"
    remove_directories_by_name ".nyc_output" "NYC coverage directories"
    remove_files_by_pattern ".eslintcache" "ESLint cache files"
    
elif [ "$TSBUILDINFO" = true ]; then
    remove_files_by_pattern "*.tsbuildinfo" "TypeScript build info files"
    
else
    echo -e "${BLUE}Running turbo clean...${NC}"
    # Only run turbo clean for the default case
    turbo run clean
fi

if [ "$FRESH" = true ]; then
    echo -e "${GREEN}Installing dependencies...${NC}"
    bun install
fi

echo -e "${GREEN}Cleanup complete!${NC}"
