#!/bin/bash

# Script to rename the project from iYHCT360 to a new name
# Usage: ./rename-project.sh NewProjectName

set -e

if [ -z "$1" ]; then
    echo "Usage: ./rename-project.sh NewProjectName"
    echo "Example: ./rename-project.sh MyAwesomeApp"
    exit 1
fi

OLD_NAME="iYHCT360"
NEW_NAME="$1"

echo "🔄 Renaming project from '$OLD_NAME' to '$NEW_NAME'..."

# Function to rename files and directories
rename_files() {
    # Rename directories (from deepest to shallowest)
    find . -depth -type d -name "*${OLD_NAME}*" 2>/dev/null | while read dir; do
        new_dir=$(echo "$dir" | sed "s/${OLD_NAME}/${NEW_NAME}/g")
        if [ "$dir" != "$new_dir" ]; then
            echo "  Renaming directory: $dir -> $new_dir"
            mv "$dir" "$new_dir"
        fi
    done

    # Rename files
    find . -type f -name "*${OLD_NAME}*" 2>/dev/null | while read file; do
        new_file=$(echo "$file" | sed "s/${OLD_NAME}/${NEW_NAME}/g")
        if [ "$file" != "$new_file" ]; then
            echo "  Renaming file: $file -> $new_file"
            mv "$file" "$new_file"
        fi
    done
}

# Function to replace content in files
replace_content() {
    echo "📝 Replacing content in files..."
    
    # Find all text files and replace content
    find . -type f \( \
        -name "*.cs" -o \
        -name "*.csproj" -o \
        -name "*.sln" -o \
        -name "*.json" -o \
        -name "*.xml" -o \
        -name "*.md" -o \
        -name "*.props" -o \
        -name "*.targets" -o \
        -name "*.http" \
    \) ! -path "*/bin/*" ! -path "*/obj/*" ! -path "*/.git/*" 2>/dev/null | while read file; do
        if grep -q "${OLD_NAME}" "$file" 2>/dev/null; then
            echo "  Updating: $file"
            sed -i "s/${OLD_NAME}/${NEW_NAME}/g" "$file"
        fi
    done
}

# Clean build artifacts first
echo "🧹 Cleaning build artifacts..."
find . -type d \( -name "bin" -o -name "obj" \) -exec rm -rf {} + 2>/dev/null || true

# Replace content first (before renaming directories)
replace_content

# Then rename files and directories
echo "📁 Renaming files and directories..."
rename_files

echo ""
echo "  Project renamed successfully from '$OLD_NAME' to '$NEW_NAME'!"
echo ""
echo "Next steps:"
echo "  1. Review the changes"
echo "  2. Update your connection string in appsettings.json"
echo "  3. Run 'dotnet restore'"
echo "  4. Run 'dotnet build'"
