/* eslint-disable @typescript-eslint/no-var-requires */
/**
 * Expo Config-Plugin — kopiert das Rive-Asset (lyra-avatar.riv) bei prebuild
 * nach android/app/src/main/res/raw/lyra_avatar.riv damit Rive-Native auf
 * Android es als raw-resource laden kann.
 *
 * Hintergrund: rive-react-native auf Android akzeptiert NUR
 *   - resourceName="lyra_avatar"  (raw-resource-Name, lowercase+underscores)
 *   - url="https://..."  (remote)
 *
 * Mit `source={{ uri: 'file:///...' }}` (was iOS via expo-asset gut findet)
 * crasht Android: "File resource not found. You must provide correct url
 * or resourceName!"
 *
 * Fix: bei jedem prebuild .riv aus assets/ in res/raw/ kopieren.
 *
 * Usage in app.config.ts: plugins: ['./plugins/with-rive-asset-android']
 */

const fs = require('fs');
const path = require('path');
const { withDangerousMod } = require('@expo/config-plugins');

const SOURCE = path.join(__dirname, '..', 'assets', 'lyra-avatar.riv');
// Android raw-resource convention: lowercase + underscores (NICHT hyphens).
const TARGET_FILENAME = 'lyra_avatar.riv';

function withRiveAssetAndroid(config) {
  return withDangerousMod(config, [
    'android',
    async (cfg) => {
      const platformProjectRoot = cfg.modRequest.platformProjectRoot;
      const targetDir = path.join(platformProjectRoot, 'app', 'src', 'main', 'res', 'raw');
      const target = path.join(targetDir, TARGET_FILENAME);

      if (!fs.existsSync(SOURCE)) {
        throw new Error(`[with-rive-asset-android] Quelle fehlt: ${SOURCE}`);
      }

      if (!fs.existsSync(targetDir)) {
        fs.mkdirSync(targetDir, { recursive: true });
      }

      fs.copyFileSync(SOURCE, target);
      return cfg;
    },
  ]);
}

module.exports = withRiveAssetAndroid;
