/* eslint-disable @typescript-eslint/no-var-requires */
/**
 * Fix für SDK-54 + prebuilt React Native + react-native-webrtc:
 *   "include of non-modular header inside framework module"
 *   (als Fehler, weil Xcode `-Werror=non-modular-include-in-framework-module`
 *    auf Framework-Module setzt).
 *
 * Ab RN 0.81 / Expo SDK 54 wird React Native als prebuilt XCFramework
 * (React.framework, modular) ausgeliefert. Native Module wie react-native-webrtc
 * importieren React-Core-Header non-modular (`#import "React/..."`) → das ist bei
 * modularen Frameworks ein -Werror → Build bricht ab.
 *
 * Lösung (dokumentiert): auf den Pod-Targets non-modular Includes erlauben
 * (CLANG_ALLOW_NON_MODULAR_INCLUDES_IN_FRAMEWORK_MODULES=YES) + das -Werror
 * neutralisieren (-Wno-error=non-modular-include-in-framework-module).
 *
 * Injiziert in den bestehenden `post_install do |installer|`-Block (ein zweiter
 * würde den ersten ersetzen). Idempotent via Marker. Läuft als
 * withDangerousMod('ios') während `expo prebuild`, vor `pod install`.
 */
const { withDangerousMod } = require('@expo/config-plugins');
const fs = require('fs');
const path = require('path');

const MARKER = '# REBREAK_ALLOW_NONMODULAR_INCLUDES';

const FIX = `
    ${MARKER}
    # SDK 54 prebuilt React Native: react-native-webrtc & Co. importieren
    # React-Header non-modular -> -Werror bricht den Build ab. Auf allen
    # Pod-Targets erlauben + -Werror entschärfen.
    installer.pods_project.targets.each do |t|
      t.build_configurations.each do |config|
        config.build_settings['CLANG_ALLOW_NON_MODULAR_INCLUDES_IN_FRAMEWORK_MODULES'] = 'YES'
        cflags = config.build_settings['OTHER_CFLAGS'] || ['$(inherited)']
        cflags = [cflags] unless cflags.is_a?(Array)
        unless cflags.include?('-Wno-error=non-modular-include-in-framework-module')
          cflags << '-Wno-error=non-modular-include-in-framework-module'
        end
        config.build_settings['OTHER_CFLAGS'] = cflags
      end
    end
    Pod::UI.puts "  -> Allowed non-modular includes on #{installer.pods_project.targets.count} pod targets".green
    ${MARKER}
`;

module.exports = function withAllowNonModularIncludes(config) {
  return withDangerousMod(config, [
    'ios',
    async (cfg) => {
      const podfilePath = path.join(cfg.modRequest.platformProjectRoot, 'Podfile');
      if (!fs.existsSync(podfilePath)) {
        console.warn('[with-allow-nonmodular-includes] Podfile not found at', podfilePath);
        return cfg;
      }
      let podfile = fs.readFileSync(podfilePath, 'utf-8');
      if (podfile.includes(MARKER)) {
        return cfg; // schon gepatcht
      }
      const anchorRe = /(post_install do \|installer\|[^\n]*\n)/;
      if (!anchorRe.test(podfile)) {
        console.warn('[with-allow-nonmodular-includes] no `post_install do |installer|` block — skipping');
        return cfg;
      }
      podfile = podfile.replace(anchorRe, `$1${FIX}`);
      fs.writeFileSync(podfilePath, podfile);
      console.log('[with-allow-nonmodular-includes] patched Podfile post_install');
      return cfg;
    },
  ]);
};
