#!/bin/bash

# Frontend Debranding Script for MoreMinimore
# This script handles comprehensive frontend debranding and UI fixes
# Usage: ./scripts/frontend-debrand.sh

set -e  # Exit on any error

echo "🎨 Starting frontend debranding process..."

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

# Function to print colored output
print_status() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# Check if we're in the right directory
if [ ! -f "package.json" ] || [ ! -d "src" ]; then
    print_error "Please run this script from the project root directory"
    exit 1
fi

# Function to fix TitleBar component
fix_titlebar() {
    print_status "Fixing TitleBar component..."
    
    if [ -f "src/app/TitleBar.tsx" ]; then
        # Create a backup
        cp src/app/TitleBar.tsx src/app/TitleBar.tsx.bak
        
        # Remove Dyad Pro related imports and components
        sed -i '' '/import.*DyadProSuccessDialog/d' src/app/TitleBar.tsx
        sed -i '' '/import.*useUserBudgetInfo/d' src/app/TitleBar.tsx
        sed -i '' '/import.*UserBudgetInfo/d' src/app/TitleBar.tsx
        
        # Remove Dyad Pro button and related logic
        sed -i '' '/const isDyadPro =/d' src/app/TitleBar.tsx
        sed -i '' '/const isDyadProEnabled =/d' src/app/TitleBar.tsx
        sed -i '' '/showDyadProSuccessDialog/d' src/app/TitleBar.tsx
        sed -i '' '/DyadProSuccessDialog/,/<\/DyadProSuccessDialog>/d' src/app/TitleBar.tsx
        sed -i '' '/{isDyadPro && <DyadProButton/d' src/app/TitleBar.tsx
        
        # Update logo alt text
        sed -i '' 's/Dyad Logo/MoreMinimore Logo/g' src/app/TitleBar.tsx
        
        # Remove DyadProButton component
        sed -i '' '/export function DyadProButton/,/^}/d' src/app/TitleBar.tsx
        sed -i '' '/export function AICreditStatus/,/^}/d' src/app/TitleBar.tsx
        
        # Remove deep link handling for dyad-pro-return
        sed -i '' '/dyad-pro-return/d' src/app/TitleBar.tsx
        
        rm src/app/TitleBar.tsx.bak
        print_success "Fixed TitleBar component"
    fi
}

# Function to remove DyadProSuccessDialog component
remove_pro_dialog() {
    print_status "Removing DyadProSuccessDialog component..."
    
    if [ -f "src/components/DyadProSuccessDialog.tsx" ]; then
        mv src/components/DyadProSuccessDialog.tsx src/components/DyadProSuccessDialog.tsx.disabled
        print_success "Disabled DyadProSuccessDialog component"
    fi
}

# Function to fix ContextFilesPicker
fix_context_files_picker() {
    print_status "Fixing ContextFilesPicker component..."
    
    if [ -f "src/components/ContextFilesPicker.tsx" ]; then
        # Create a backup
        cp src/components/ContextFilesPicker.tsx src/components/ContextFilesPicker.tsx.bak
        
        # Update tooltip text
        sed -i '' 's/Codebase Context/Context Settings/g' src/components/ContextFilesPicker.tsx
        
        # Update smart context logic to remove pro restrictions
        sed -i '' 's/settings?.enableDyadPro && settings?.enableProSmartFilesContextMode/true/g' src/components/ContextFilesPicker.tsx
        
        # Update text references
        sed -i '' 's/Dyad uses/MoreMinimore uses/g' src/components/ContextFilesPicker.tsx
        sed -i '' 's/With Smart Context, Dyad uses/With Smart Context, MoreMinimore uses/g' src/components/ContextFilesPicker.tsx
        
        rm src/components/ContextFilesPicker.tsx.bak
        print_success "Fixed ContextFilesPicker component"
    fi
}

# Function to fix DyadTokenSavings component
fix_token_savings() {
    print_status "Fixing DyadTokenSavings component..."
    
    if [ -f "src/components/chat/DyadTokenSavings.tsx" ]; then
        # Create a backup
        cp src/components/chat/DyadTokenSavings.tsx src/components/chat/DyadTokenSavings.tsx.bak
        
        # Update component name and references
        sed -i '' 's/DyadTokenSavings/TokenSavings/g' src/components/chat/DyadTokenSavings.tsx
        
        rm src/components/chat/DyadTokenSavings.tsx.bak
        print_success "Fixed DyadTokenSavings component"
    fi
}

# Function to fix DyadThink component
fix_dyad_think() {
    print_status "Fixing DyadThink component..."
    
    if [ -f "src/components/chat/DyadThink.tsx" ]; then
        # Create a backup
        cp src/components/chat/DyadThink.tsx src/components/chat/DyadThink.tsx.bak
        
        # Update component name and references
        sed -i '' 's/DyadThink/AIThink/g' src/components/chat/DyadThink.tsx
        
        rm src/components/chat/DyadThink.tsx.bak
        print_success "Fixed DyadThink component"
    fi
}

# Function to update smart context settings
update_smart_context_settings() {
    print_status "Updating smart context settings..."
    
    # Update smart context store to remove pro restrictions
    if [ -f "src/ipc/utils/smart_context_store.ts" ]; then
        cp src/ipc/utils/smart_context_store.ts src/ipc/utils/smart_context_store.ts.bak
        sed -i '' 's/settings\.enableDyadPro/true/g' src/ipc/utils/smart_context_store.ts
        rm src/ipc/utils/smart_context_store.ts.bak
        print_success "Updated smart context store"
    fi
    
    # Update chat stream handlers to enable smart context for all users
    if [ -f "src/ipc/handlers/chat_stream_handlers.ts" ]; then
        cp src/ipc/handlers/chat_stream_handlers.ts src/ipc/handlers/chat_stream_handlers.ts.bak
        sed -i '' 's/isDeepContextEnabled/true/g' src/ipc/handlers/chat_stream_handlers.ts
        rm src/ipc/handlers/chat_stream_handlers.ts.bak
        print_success "Updated chat stream handlers"
    fi
}

# Function to fix remaining Dyad references
fix_remaining_references() {
    print_status "Fixing remaining Dyad references..."
    
    # Find and replace remaining Dyad references in components
    find src/components -name "*.tsx" -type f -exec sed -i '' 's/Dyad/MoreMinimore/g' {} \;
    find src/app -name "*.tsx" -type f -exec sed -i '' 's/Dyad/MoreMinimore/g' {} \;
    
    # Fix specific cases where we don't want to replace
    find src/components -name "*.tsx" -type f -exec sed -i '' 's/MoreMinimorePro/DyadPro/g' {} \;
    find src/app -name "*.tsx" -type f -exec sed -i '' 's/MoreMinimorePro/DyadPro/g' {} \;
    
    print_success "Fixed remaining Dyad references"
}

# Function to add missing user budget handler
add_missing_handlers() {
    print_status "Adding missing IPC handlers..."
    
    # Create a simple user budget handler that returns default values
    if [ -f "src/ipc/ipc_host.ts" ]; then
        cp src/ipc/ipc_host.ts src/ipc/ipc_host.ts.bak
        
        # Add a simple user budget handler
        if ! grep -q "get-user-budget" src/ipc/ipc_host.ts; then
            sed -i '' '/registerDebugHandlers();/a\
\
  // Add missing user budget handler\
  ipcMain.handle("get-user-budget", async () => {\
    return {\
      totalCredits: 1000,\
      usedCredits: 0,\
      resetDate: new Date().toISOString()\
    };\
  });' src/ipc/ipc_host.ts
        fi
        
        rm src/ipc/ipc_host.ts.bak
        print_success "Added missing user budget handler"
    fi
}

# Function to update preload script
update_preload() {
    print_status "Updating preload script..."
    
    if [ -f "src/preload.ts" ]; then
        cp src/preload.ts src/preload.ts.bak
        
        # Add get-user-budget to preload if not present
        if ! grep -q "get-user-budget" src/preload.ts; then
            sed -i '' '/"get-system-debug-info":/a\
    "get-user-budget": () => ipcRenderer.invoke("get-user-budget"),' src/preload.ts
        fi
        
        rm src/preload.ts.bak
        print_success "Updated preload script"
    fi
}

# Function to update IPC client
update_ipc_client() {
    print_status "Updating IPC client..."
    
    if [ -f "src/ipc/ipc_client.ts" ]; then
        cp src/ipc/ipc_client.ts src/ipc/ipc_client.ts.bak
        
        # Add getUserBudget method if not present
        if ! grep -q "getUserBudget" src/ipc/ipc_client.ts; then
            sed -i '' '/async getSystemDebugInfo()/a\
\
  async getUserBudget() {\
    return this.ipcRenderer.invoke("get-user-budget");\
  }' src/ipc/ipc_client.ts
        fi
        
        rm src/ipc/ipc_client.ts.bak
        print_success "Updated IPC client"
    fi
}

# Function to test compilation
test_compilation() {
    print_status "Testing compilation..."
    
    if command -v npm &> /dev/null; then
        if npm run ts 2>/dev/null; then
            print_success "TypeScript compilation successful"
        else
            print_warning "TypeScript compilation failed. Check the errors above."
        fi
    fi
}

# Main execution
main() {
    print_status "Starting frontend debranding..."
    
    fix_titlebar
    remove_pro_dialog
    fix_context_files_picker
    fix_token_savings
    fix_dyad_think
    update_smart_context_settings
    fix_remaining_references
    add_missing_handlers
    update_preload
    update_ipc_client
    test_compilation
    
    print_success "🎉 Frontend debranding completed!"
    echo ""
    echo "Summary of changes:"
    echo "✅ Fixed TitleBar component (removed Pro elements)"
    echo "✅ Removed DyadProSuccessDialog component"
    echo "✅ Fixed ContextFilesPicker component"
    echo "✅ Fixed DyadTokenSavings component"
    echo "✅ Fixed DyadThink component"
    echo "✅ Updated smart context settings"
    echo "✅ Fixed remaining Dyad references"
    echo "✅ Added missing IPC handlers"
    echo "✅ Updated preload script"
    echo "✅ Updated IPC client"
    echo ""
    echo "Next steps:"
    echo "1. Test the application with 'npm start'"
    echo "2. Verify all UI elements are properly debranded"
    echo "3. Test smart context functionality"
    echo ""
    print_warning "Please test the application thoroughly before committing changes."
}

# Run main function
main "$@"
