#!/bin/bash

# =============================================================================
# FIX SCRIPT: Capacitor Auto-Generated Files for Plugin Development Projects
# =============================================================================
# 
# PURPOSE: This script fixes common issues in Capacitor plugin development
# projects where auto-generated files have incorrect paths or references.
#
# WHEN TO USE:
# - After running 'npx cap sync'
# - After running 'npx cap update'  
# - After running 'npx cap add android'
# - After any Capacitor CLI command that regenerates integration files
# - When you get build errors about missing files or incorrect paths
#
# WHAT IT DOES:
# 1. Fixes capacitor.build.gradle (missing cordova.variables.gradle)
# 2. Fixes capacitor.settings.gradle (incorrect plugin path in test-apps)
#
# FIX 1: capacitor.build.gradle
# THE PROBLEM:
# Capacitor generates this line in capacitor.build.gradle:
#   apply from: "../capacitor-cordova-android-plugins/cordova.variables.gradle"
# But plugin development projects don't have this file, causing:
#   "Could not read script '.../cordova.variables.gradle' as it does not exist"
#
# FIX 2: capacitor.settings.gradle (Test App)
# THE PROBLEM:
# Capacitor generates this path in test-apps:
#   project(':timesafari-daily-notification-plugin').projectDir = new File('../node_modules/@timesafari/daily-notification-plugin/android')
# But the plugin module is actually in android/plugin/, not android root, causing:
#   "No matching variant of project :timesafari-daily-notification-plugin was found"
#
# =============================================================================

set -e

CAPACITOR_BUILD_GRADLE="android/app/capacitor.build.gradle"
CAPACITOR_SETTINGS_GRADLE="android/capacitor.settings.gradle"

echo "🔧 DailyNotification Plugin - Capacitor Build Fix Script"
echo "========================================================"

# =============================================================================
# FIX 1: capacitor.build.gradle
# =============================================================================
if [ -f "$CAPACITOR_BUILD_GRADLE" ]; then
    echo "📁 Found capacitor.build.gradle at: $CAPACITOR_BUILD_GRADLE"
    
    # Check if the problematic line exists and isn't already commented
    if grep -q "^apply from: \"../capacitor-cordova-android-plugins/cordova.variables.gradle\"" "$CAPACITOR_BUILD_GRADLE"; then
        echo "🔧 Applying fix to capacitor.build.gradle..."
        echo "   Problem: Line tries to load non-existent cordova.variables.gradle"
        echo "   Solution: Commenting out the problematic line"
        
        # Apply the fix by commenting out the problematic line
        # Handle macOS vs Linux sed differences
        if [[ "$OSTYPE" == "darwin"* ]]; then
            # macOS sed requires empty string after -i
            sed -i '' 's/^apply from: "\.\.\/capacitor-cordova-android-plugins\/cordova\.variables\.gradle"/\/\/ Plugin development project - no Capacitor integration files needed\n\/\/ &/' "$CAPACITOR_BUILD_GRADLE"
        else
            # Linux sed
            sed -i 's/^apply from: "\.\.\/capacitor-cordova-android-plugins\/cordova\.variables\.gradle"/\/\/ Plugin development project - no Capacitor integration files needed\n\/\/ &/' "$CAPACITOR_BUILD_GRADLE"
        fi
        
        echo "✅ Fix applied successfully!"
        echo "💡 The problematic line has been commented out with an explanation"
        echo "⚠️  Note: This fix will be lost if you run Capacitor CLI commands again"
        echo "🔄 To restore the fix later, run this script again or use the build script"
    else
        echo "ℹ️  capacitor.build.gradle already has the fix applied or doesn't need fixing"
        echo "   (The problematic line is either commented out or doesn't exist)"
    fi
else
    echo "⚠️  capacitor.build.gradle not found at: $CAPACITOR_BUILD_GRADLE"
    echo "   This may indicate:"
    echo "   - You're not in the correct directory"
    echo "   - The Android project structure is different"
    echo "   - The file hasn't been generated yet"
fi

# =============================================================================
# FIX 2: capacitor.settings.gradle (Test App Plugin Path)
# =============================================================================
if [ -f "$CAPACITOR_SETTINGS_GRADLE" ]; then
    echo ""
    echo "📁 Checking capacitor.settings.gradle at: $CAPACITOR_SETTINGS_GRADLE"
    
    # Check if the path points to android instead of android/plugin
    # Look for the line without the /plugin suffix
    if grep -q "project(':timesafari-daily-notification-plugin').projectDir = new File('../node_modules/@timesafari/daily-notification-plugin/android')$" "$CAPACITOR_SETTINGS_GRADLE"; then
        echo "🔧 Applying fix to capacitor.settings.gradle..."
        echo "   Problem: Path points to 'android' but plugin module is in 'android/plugin'"
        echo "   Solution: Updating path to 'android/plugin'"
        
        # Apply the fix by updating the path - simpler approach
        # Handle macOS vs Linux sed differences
        if [[ "$OSTYPE" == "darwin"* ]]; then
            # macOS sed - replace android')$ with android/plugin')
            sed -i '' "s|/android')$|/android/plugin')|" "$CAPACITOR_SETTINGS_GRADLE"
            # Add comment before the line if it doesn't already exist
            if ! grep -q "NOTE: Plugin module is in android/plugin" "$CAPACITOR_SETTINGS_GRADLE"; then
                sed -i '' "/^include ':timesafari-daily-notification-plugin'/a\\
// NOTE: Plugin module is in android/plugin/ subdirectory, not android root\\
// This file is auto-generated by Capacitor, but must be manually corrected for this plugin structure\\
" "$CAPACITOR_SETTINGS_GRADLE"
            fi
        else
            # Linux sed - replace android')$ with android/plugin')
            sed -i "s|/android')$|/android/plugin')|" "$CAPACITOR_SETTINGS_GRADLE"
            # Add comment before the line if it doesn't already exist
            if ! grep -q "NOTE: Plugin module is in android/plugin" "$CAPACITOR_SETTINGS_GRADLE"; then
                sed -i "/^include ':timesafari-daily-notification-plugin'/a\\// NOTE: Plugin module is in android/plugin/ subdirectory, not android root\\n// This file is auto-generated by Capacitor, but must be manually corrected for this plugin structure" "$CAPACITOR_SETTINGS_GRADLE"
            fi
        fi
        
        echo "✅ Fix applied successfully!"
        echo "💡 The path has been updated to point to android/plugin/"
        echo "⚠️  Note: This fix will be lost if you run Capacitor CLI commands again"
    elif grep -q "android/plugin" "$CAPACITOR_SETTINGS_GRADLE"; then
        echo "ℹ️  capacitor.settings.gradle already has the correct path (android/plugin)"
    else
        echo "ℹ️  capacitor.settings.gradle doesn't reference the plugin or uses a different structure"
    fi
else
    echo "ℹ️  capacitor.settings.gradle not found (may not be a test-app)"
fi

echo ""
echo "📚 For more information, see:"
echo "   - BUILDING.md (troubleshooting section)"
echo "   - scripts/build-native.sh (automatic fix documentation)"
echo "========================================================"
