#!/usr/bin/env node
/**
 * Restore Local Capacitor Plugins
 * 
 * This script ensures that local custom plugins (SafeArea and SharedImage)
 * are present in capacitor.plugins.json after `npx cap sync` runs.
 * 
 * The capacitor.plugins.json file is auto-generated by Capacitor and gets
 * overwritten during sync, so we need to restore our local plugins.
 * 
 * Usage:
 *   node scripts/restore-local-plugins.js
 * 
 * This should be run after `npx cap sync android` or `npx cap sync ios`
 */

const fs = require('fs');
const path = require('path');

const PLUGINS_FILE = path.join(__dirname, '../android/app/src/main/assets/capacitor.plugins.json');

// Local plugins that need to be added
const LOCAL_PLUGINS = [
  {
    pkg: 'SafeArea',
    classpath: 'app.timesafari.safearea.SafeAreaPlugin'
  },
  {
    pkg: 'SharedImage',
    classpath: 'app.timesafari.sharedimage.SharedImagePlugin'
  }
];

function restoreLocalPlugins() {
  try {
    // Read the current plugins file
    if (!fs.existsSync(PLUGINS_FILE)) {
      console.error(`❌ Plugins file not found: ${PLUGINS_FILE}`);
      console.error('   Run "npx cap sync android" first to generate the file.');
      process.exit(1);
    }

    const content = fs.readFileSync(PLUGINS_FILE, 'utf8');
    let plugins = JSON.parse(content);

    if (!Array.isArray(plugins)) {
      console.error(`❌ Invalid plugins file format: expected array, got ${typeof plugins}`);
      process.exit(1);
    }

    // Check which local plugins are missing
    const existingPackages = new Set(plugins.map(p => p.pkg));
    const missingPlugins = LOCAL_PLUGINS.filter(p => !existingPackages.has(p.pkg));

    if (missingPlugins.length === 0) {
      console.log('✅ All local plugins are already present in capacitor.plugins.json');
      return;
    }

    // Add missing plugins
    plugins.push(...missingPlugins);

    // Write back to file with proper formatting (matching existing style)
    const formatted = JSON.stringify(plugins, null, '\t');
    fs.writeFileSync(PLUGINS_FILE, formatted + '\n', 'utf8');

    console.log('✅ Restored local plugins to capacitor.plugins.json:');
    missingPlugins.forEach(p => {
      console.log(`   - ${p.pkg} (${p.classpath})`);
    });
  } catch (error) {
    console.error('❌ Error restoring local plugins:', error.message);
    process.exit(1);
  }
}

// Run the script
restoreLocalPlugins();
