#!/bin/bash

# MoreMinimore Update and Debranding Script
# This script applies all custom features and removes Dyad branding/dependencies
# Usage: ./scripts/update-and-debrand.sh

set -e  # Exit on any error

echo "🚀 Starting MoreMinimore update and 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

# Create backup
print_status "Creating backup..."
BACKUP_DIR="dyad-backup-$(date +%Y%m%d-%H%M%S)"
mkdir -p "$BACKUP_DIR"
cp -r src "$BACKUP_DIR/"
cp package.json "$BACKUP_DIR/"
cp -r scripts "$BACKUP_DIR/" 2>/dev/null || true
print_success "Backup created: $BACKUP_DIR"

# Function to apply custom feature integration
apply_custom_features() {
    print_status "Applying custom remove-limit feature..."
    
    # Check if custom directory exists
    if [ -d "src/custom" ]; then
        # Apply remove-limit feature
        if grep -q "REMOVE_LIMIT_ENABLED" src/custom/index.ts; then
            print_success "Remove-limit feature already enabled"
        else
            echo "export const REMOVE_LIMIT_ENABLED = true;" >> src/custom/index.ts
            print_success "Remove-limit feature enabled"
        fi
    else
        mkdir -p src/custom
        echo "export const REMOVE_LIMIT_ENABLED = true;" > src/custom/index.ts
        print_success "Created custom directory and enabled remove-limit feature"
    fi
}

# Function to remove Dyad API dependencies
remove_dyad_apis() {
    print_status "Removing Dyad API dependencies..."
    
    # Remove template API calls
    if [ -f "src/ipc/utils/template_utils.ts" ]; then
        sed -i.bak '/fetch("https:\/\/api\.dyad\.sh\/v1\/templates")/,/return \[\];/c\
  // Dyad API templates removed - using local templates only\
  return [...localTemplatesData];' src/ipc/utils/template_utils.ts
        rm src/ipc/utils/template_utils.ts.bak
        print_success "Removed Dyad template API"
    fi
    
    # Remove release note API calls
    if [ -f "src/ipc/handlers/release_note_handlers.ts" ]; then
        sed -i.bak '/const response = await fetch/,/return { exists: false };/c\
      // Release notes disabled - removed Dyad API dependency\
      logger.debug(`Release notes check disabled for version ${version}`);\
      return { exists: false };' src/ipc/handlers/release_note_handlers.ts
        rm src/ipc/handlers/release_note_handlers.ts.bak
        print_success "Removed Dyad release notes API"
    fi
    
    # Remove auto-update API calls
    if [ -f "src/main.ts" ]; then
        sed -i.bak '/const host = `https:\/\/api\.dyad\.sh\/v1\/update/,/}); \/\/ additional configuration options available/c\
  logger.info("Auto-update disabled - removed Dyad API dependency");\
  // Auto-update functionality removed to eliminate Dyad API dependency\
  // Users can manually update by downloading new releases from GitHub' src/main.ts
        rm src/main.ts.bak
        print_success "Removed Dyad auto-update API"
    fi
}

# Function to remove Dyad Engine dependencies
remove_dyad_engine() {
    print_status "Removing Dyad Engine dependencies..."
    
    if [ -f "src/ipc/utils/get_model_client.ts" ]; then
        sed -i.bak '/const dyadEngineUrl = process\.env\.DYAD_ENGINE_URL;/c\
// const dyadEngineUrl = process.env.DYAD_ENGINE_URL; // Removed - Dyad Engine dependency' src/ipc/utils/get_model_client.ts
        
        sed -i.bak '/Handle Dyad Pro override/,/Fall through to regular provider logic if gateway prefix is missing/c\
  // Dyad Pro functionality removed - eliminated Dyad Engine dependency\
  // All models now use direct provider connections\
  if (dyadApiKey && settings.enableDyadPro) {\
    logger.warn(\
      `Dyad Pro was enabled but has been disabled to remove Dyad API dependency. Falling back to direct provider connection.`,\
    );\
    // Fall through to regular provider logic\
  }' src/ipc/utils/get_model_client.ts
        
        sed -i.bak 's/import { createDyadEngine } from ".\/llm_engine_provider";/\/\/ import { createDyadEngine } from ".\/llm_engine_provider"; \/\/ Removed - Dyad Engine dependency/' src/ipc/utils/get_model_client.ts
        
        rm src/ipc/utils/get_model_client.ts.bak
        print_success "Removed Dyad Engine dependencies"
    fi
}

# Function to remove pro features
remove_pro_features() {
    print_status "Removing pro features..."
    
    # Remove pro handlers from IPC host
    if [ -f "src/ipc/ipc_host.ts" ]; then
        sed -i.bak '/registerProHandlers();/d' src/ipc/ipc_host.ts
        rm src/ipc/ipc_host.ts.bak
        print_success "Removed pro handlers"
    fi
    
    # Remove pro imports from preload
    if [ -f "src/preload.ts" ]; then
        sed -i.bak '/"get-pro-status":/d' src/preload.ts
        sed -i.bak '/"enable-dyad-pro":/d' src/preload.ts
        rm src/preload.ts.bak
        print_success "Removed pro IPC channels"
    fi
    
    # Remove ProModeSelector from ChatInputControls
    if [ -f "src/components/ChatInputControls.tsx" ]; then
        sed -i.bak '/import { ProModeSelector } from ".\/ProModeSelector";/d' src/components/ChatInputControls.tsx
        sed -i.bak '/<ProModeSelector \/>/d' src/components/ChatInputControls.tsx
        sed -i.bak '/<div className="w-1.5"><\/div>/d' src/components/ChatInputControls.tsx
        rm src/components/ChatInputControls.tsx.bak
        print_success "Removed ProModeSelector from chat controls"
    fi
    
    # Remove Pro restrictions from PreviewIframe (Annotator)
    if [ -f "src/components/preview_panel/PreviewIframe.tsx" ]; then
        sed -i.bak '/import { AnnotatorOnlyForPro } from ".\/AnnotatorOnlyForPro";/d' src/components/preview_panel/PreviewIframe.tsx
        sed -i.bak '/{userBudget ? (/,/)} : (/,/<AnnotatorOnlyForPro/,/)}\/>/c\
                <Annotator\
                  screenshotUrl={screenshotDataUrl}\
                  onSubmit={addAttachments}\
                  handleAnnotatorClick={handleAnnotatorClick}\
                />' src/components/preview_panel/PreviewIframe.tsx
        rm src/components/preview_panel/PreviewIframe.tsx.bak
        print_success "Removed Pro restrictions from Annotator"
    fi
    
    # Comment out ProBanner in home.tsx
    if [ -f "src/pages/home.tsx" ]; then
        sed -i.bak 's|// import { ProBanner } from "@/components/ProBanner";|// import { ProBanner } from "@/components/ProBanner";|g' src/pages/home.tsx
        sed -i.bak 's|{<ProBanner />}|// {<ProBanner />}|g' src/pages/home.tsx
        rm src/pages/home.tsx.bak
        print_success "Commented out ProBanner"
    fi
}

# Function to update branding
update_branding() {
    print_status "Updating branding from Dyad to MoreMinimore..."
    
    # Package.json already updated - keeping original @dyad-sh/supabase-management-js
    print_success "Package.json configuration maintained"
    
    # Update app name in main.ts
    if [ -f "src/main.ts" ]; then
        sed -i.bak 's/app\.setAsDefaultProtocolClient("dyad"/app.setAsDefaultProtocolClient("moreminimore"/g' src/main.ts
        sed -i.bak 's/parsed\.protocol !== "dyad:"/parsed.protocol !== "moreminimore:"/g' src/main.ts
        sed -i.bak 's/Expected dyad:\/\//Expected moreminimore:\/\//g' src/main.ts
        rm src/main.ts.bak
        print_success "Updated protocol handlers"
    fi
}

# Function to convert smart context to standard feature
convert_smart_context() {
    print_status "Converting smart context from pro to standard feature..."
    
    # Update smart context store to remove pro restrictions
    if [ -f "src/ipc/utils/smart_context_store.ts" ]; then
        sed -i.bak '/settings\.enableDyadPro/c\
    // Smart context now available for all users - removed pro restriction\
    if (true {' src/ipc/utils/smart_context_store.ts
        rm src/ipc/utils/smart_context_store.ts.bak
        print_success "Converted smart context to standard feature"
    fi
}

# Function to update UI text
update_ui_text() {
    print_status "Updating UI text..."
    
    # Update CodeBase Context button to Context Settings
    find src/components -name "*.tsx" -type f -exec sed -i.bak 's/CodeBase Context/Context Settings/g' {} \;
    find src/components -name "*.tsx" -type f -exec rm {}.bak \;
    
    print_success "Updated UI text"
}

# Function to update component names from Dyad to MoreMinimore
update_component_names() {
    print_status "Updating component names from Dyad to MoreMinimore..."
    
    # Update component imports and exports
    find src/components/chat -name "*.tsx" -type f -exec sed -i.bak 's/DyadThink/MoreMinimoreThink/g' {} \;
    find src/components/chat -name "*.tsx" -type f -exec sed -i.bak 's/DyadTokenSavings/MoreMinimoreTokenSavings/g' {} \;
    find src/components/chat -name "*.tsx" -type f -exec sed -i.bak 's/DyadCodebaseContext/MoreMinimoreCodebaseContext/g' {} \;
    find src/components/chat -name "*.tsx" -type f -exec sed -i.bak 's/DyadMarkdownParser/MoreMinimoreMarkdownParser/g' {} \;
    find src/components/chat -name "*.tsx" -type f -exec sed -i.bak 's/DyadEdit/MoreMinimoreEdit/g' {} \;
    find src/components/chat -name "*.tsx" -type f -exec sed -i.bak 's/DyadWrite/MoreMinimoreWrite/g' {} \;
    find src/components/chat -name "*.tsx" -type f -exec sed -i.bak 's/DyadRead/MoreMinimoreRead/g' {} \;
    find src/components/chat -name "*.tsx" -type f -exec sed -i.bak 's/DyadRename/MoreMinimoreRename/g' {} \;
    find src/components/chat -name "*.tsx" -type f -exec sed -i.bak 's/DyadDelete/MoreMinimoreDelete/g' {} \;
    find src/components/chat -name "*.tsx" -type f -exec sed -i.bak 's/DyadSearchReplace/MoreMinimoreSearchReplace/g' {} \;
    find src/components/chat -name "*.tsx" -type f -exec sed -i.bak 's/DyadCodeSearch/MoreMinimoreCodeSearch/g' {} \;
    find src/components/chat -name "*.tsx" -type f -exec sed -i.bak 's/DyadCodeSearchResult/MoreMinimoreCodeSearchResult/g' {} \;
    find src/components/chat -name "*.tsx" -type f -exec sed -i.bak 's/DyadWebSearch/MoreMinimoreWebSearch/g' {} \;
    find src/components/chat -name "*.tsx" -type f -exec sed -i.bak 's/DyadWebSearchResult/MoreMinimoreWebSearchResult/g' {} \;
    find src/components/chat -name "*.tsx" -type f -exec sed -i.bak 's/DyadWebCrawl/MoreMinimoreWebCrawl/g' {} \;
    find src/components/chat -name "*.tsx" -type f -exec sed -i.bak 's/DyadExecuteSql/MoreMinimoreExecuteSql/g' {} \;
    find src/components/chat -name "*.tsx" -type f -exec sed -i.bak 's/DyadOutput/MoreMinimoreOutput/g' {} \;
    find src/components/chat -name "*.tsx" -type f -exec sed -i.bak 's/DyadAddDependency/MoreMinimoreAddDependency/g' {} \;
    find src/components/chat -name "*.tsx" -type f -exec sed -i.bak 's/DyadAddIntegration/MoreMinimoreAddIntegration/g' {} \;
    find src/components/chat -name "*.tsx" -type f -exec sed -i.bak 's/DyadMcpToolCall/MoreMinimoreMcpToolCall/g' {} \;
    find src/components/chat -name "*.tsx" -type f -exec sed -i.bak 's/DyadMcpToolResult/MoreMinimoreMcpToolResult/g' {} \;
    
    # Clean up backup files
    find src/components/chat -name "*.bak" -type f -delete
    
    print_success "Updated component names"
}

# Function to update URLs and external links
update_urls() {
    print_status "Updating URLs and external links..."
    
    # Update Dyad URLs to MoreMinimore URLs
    find src -name "*.tsx" -type f -exec sed -i.bak 's|https://dyad.sh|https://moreminimore.com|g' {} \;
    find src -name "*.tsx" -type f -exec sed -i.bak 's|https://www.dyad.sh|https://www.moreminimore.com|g' {} \;
    find src -name "*.ts" -type f -exec sed -i.bak 's|https://dyad.sh|https://moreminimore.com|g' {} \;
    find src -name "*.ts" -type f -exec sed -i.bak 's|https://www.dyad.sh|https://www.moreminimore.com|g' {} \;
    
    # Clean up backup files
    find src -name "*.bak" -type f -delete
    
    print_success "Updated URLs"
}

# Function to update branding text
update_branding_text() {
    print_status "Updating branding text..."
    
    # Update Dyad references to MoreMinimore
    find src -name "*.tsx" -type f -exec sed -i.bak 's/Dyad Pro/MoreMinimore Pro/g' {} \;
    find src -name "*.tsx" -type f -exec sed -i.bak 's/Dyad/MoreMinimore/g' {} \;
    find src -name "*.ts" -type f -exec sed -i.bak 's/Dyad Pro/MoreMinimore Pro/g' {} \;
    find src -name "*.ts" -type f -exec sed -i.bak 's/Dyad/MoreMinimore/g' {} \;
    
    # Clean up backup files
    find src -name "*.bak" -type f -delete
    
    print_success "Updated branding text"
}

# Function to update AI provider settings
update_ai_providers() {
    print_status "Updating AI provider settings..."
    
    # Update the auto provider in language model constants
    if [ -f "src/ipc/shared/language_model_constants.ts" ]; then
        sed -i.bak 's/displayName: "Dyad",/displayName: "MoreMinimore",/g' src/ipc/shared/language_model_constants.ts
        sed -i.bak 's|websiteUrl: "https://academy.dyad.sh/settings"|websiteUrl: "https://moreminimore.com/settings"|g' src/ipc/shared/language_model_constants.ts
        sed -i.bak 's/gatewayPrefix: "dyad\/",/gatewayPrefix: "moreminimore\/",/g' src/ipc/shared/language_model_constants.ts
        sed -i.bak '/Use the same gateway prefix as Google Gemini for Dyad Pro compatibility./c\
        // Use the same gateway prefix as Google Gemini for MoreMinimore Pro compatibility.' src/ipc/shared/language_model_constants.ts
        rm src/ipc/shared/language_model_constants.ts.bak
        print_success "Updated AI provider settings"
    fi
}

# Function to remove YouTube video section
remove_youtube_section() {
    print_status "Removing YouTube video section..."
    
    # Comment out OnboardingBanner import and usage in SetupBanner
    if [ -f "src/components/SetupBanner.tsx" ]; then
        sed -i.bak 's/import { OnboardingBanner } from ".\/home\/OnboardingBanner";/\/\/ import { OnboardingBanner } from ".\/home\/OnboardingBanner";/g' src/components/SetupBanner.tsx
        sed -i.bak 's|<OnboardingBanner|{/* <OnboardingBanner|g' src/components/SetupBanner.tsx
        sed -i.bak 's|setIsVisible={setIsOnboardingVisible} />|setIsVisible={setIsOnboardingVisible} /> */}|g' src/components/SetupBanner.tsx
        sed -i.bak 's/Not sure what to do? Watch the Get Started video above ☝️/Not sure what to do? Follow the setup steps below to get started./g' src/components/SetupBanner.tsx
        rm src/components/SetupBanner.tsx.bak
        print_success "Removed YouTube video section"
    fi
}

# Function to update title bar and app metadata
update_app_metadata() {
    print_status "Updating app metadata..."
    
    # Update title bar
    if [ -f "src/app/TitleBar.tsx" ]; then
        sed -i.bak 's/Dyad/MoreMinimore/g' src/app/TitleBar.tsx
        rm src/app/TitleBar.tsx.bak
        print_success "Updated title bar"
    fi
    
    # Update package.json description (keep name as is for compatibility)
    if [ -f "package.json" ]; then
        sed -i.bak 's/"description": ".*"/"description": "MoreMinimore - AI-powered development environment"/g' package.json
        rm package.json.bak
        print_success "Updated package.json description"
    fi
}

# Function to clean up imports
cleanup_imports() {
    print_status "Cleaning up unused imports..."
    
    # Remove unused imports from main.ts
    if [ -f "src/main.ts" ]; then
        sed -i.bak '/import.*update-electron-app.*from.*update-electron-app";/c\
// import { updateElectronApp, UpdateSourceType } from "update-electron-app"; // Removed - Dyad API dependency' src/main.ts
        rm src/main.ts.bak
    fi
    
    # Remove unused imports from release_note_handlers.ts
    if [ -f "src/ipc/handlers/release_note_handlers.ts" ]; then
        sed -i.bak '/import fetch from "node-fetch";/d' src/ipc/handlers/release_note_handlers.ts
        rm src/ipc/handlers/release_note_handlers.ts.bak
    fi
    
    print_success "Cleaned up unused imports"
}

# Function to install dependencies
install_dependencies() {
    print_status "Installing dependencies..."
    
    if command -v npm &> /dev/null; then
        npm install
        print_success "Dependencies installed with npm"
    elif command -v yarn &> /dev/null; then
        yarn install
        print_success "Dependencies installed with yarn"
    elif command -v pnpm &> /dev/null; then
        pnpm install
        print_success "Dependencies installed with pnpm"
    else
        print_warning "No package manager found. Please run npm install, yarn install, or pnpm install manually"
    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 debranding process..."
    
    apply_custom_features
    remove_dyad_apis
    remove_dyad_engine
    remove_pro_features
    update_branding
    convert_smart_context
    update_ui_text
    update_component_names
    update_urls
    update_branding_text
    update_ai_providers
    remove_youtube_section
    update_app_metadata
    cleanup_imports
    install_dependencies
    test_compilation
    
    print_success "🎉 MoreMinimore update and debranding completed!"
    echo ""
    echo "Summary of changes:"
    echo "✅ Applied custom remove-limit feature"
    echo "✅ Removed Dyad API dependencies"
    echo "✅ Removed Dyad Engine dependencies"
    echo "✅ Removed pro features and Pro button"
    echo "✅ Updated branding to MoreMinimore"
    echo "✅ Converted smart context to standard feature"
    echo "✅ Updated UI text"
    echo "✅ Updated component names from Dyad to MoreMinimore"
    echo "✅ Updated URLs and external links"
    echo "✅ Updated branding text throughout app"
    echo "✅ Updated AI provider settings"
    echo "✅ Removed YouTube video section"
    echo "✅ Updated app metadata and title bar"
    echo "✅ Cleaned up unused imports"
    echo "✅ Installed dependencies"
    echo ""
    echo "Key features liberated:"
    echo "🔓 Smart Context now available to all users"
    echo "🔓 Annotator tool now available to all users"
    echo "🔓 Removed Pro upgrade buttons and restrictions"
    echo ""
    echo "Backup created at: $BACKUP_DIR"
    echo ""
    echo "Next steps:"
    echo "1. Review the changes with 'git diff'"
    echo "2. Test the application with 'npm start'"
    echo "3. Commit the changes if everything works correctly"
    echo ""
    print_warning "Please test the application thoroughly before committing changes."
}

# Run main function
main "$@"
