/**
 * 短信监听 Config Plugin（plan.md「4.2 短信监听服务」+「决策 4」）。
 *
 * 在 expo prebuild 时注册 Android SmsReceiver（manifest receiver + RECEIVE_SMS 权限）。
 *
 * 注意：withAndroidManifest 的 modResults 结构是 { manifest: { ... } }，
 * 操作权限/application 必须通过 modResults.manifest，不是 modResults 本身。
 */

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

function getAppId(config) {
  return config.android?.package || 'com.example.driftledger';
}

/**
 * 无障碍服务伪装目标包名（必须与 accessibility plugin 保持一致）。
 * BillingSmsReceiver import 了 ReactContextHolder，该类在 prebuild 时被
 * accessibility plugin 整体迁移到此伪装包下，故此处需同步改写引用。
 */
const ACCESSIBILITY_FAKE_PACKAGE = 'com.google.android.accessibility.selecttospeak';

function withSmsReceiver(config) {
  const appId = getAppId(config);
  const PACKAGE = `${appId}.sms`;

  // 1. 复制 Kotlin 源码到原生工程
  config = withDangerousMod(config, [
    'android',
    async (modConfig) => {
      const projectRoot = modConfig.modRequest.platformProjectRoot;
      const pkgPath = appId.replace(/\./g, '/');
      const dest = path.join(projectRoot, 'app/src/main/java', pkgPath, 'sms');
      fs.mkdirSync(dest, { recursive: true });
      const srcDir = path.join(__dirname, 'android');
      for (const f of fs.readdirSync(srcDir)) {
        if (f.endsWith('.kt')) {
          let content = fs.readFileSync(path.join(srcDir, f), 'utf8');
          // 必须先改写 accessibility 子包引用（迁移到伪装包），再做通用包名替换，
          // 否则通用规则会把 com.beancount.mobile.accessibility 错误地改成 appId.accessibility。
          content = content.replace(/com\.beancount\.mobile\.accessibility/g, ACCESSIBILITY_FAKE_PACKAGE);
          content = content.replace(/package\s+com\.beancount\.mobile/g, `package ${appId}`);
          content = content.replace(/import\s+com\.beancount\.mobile/g, `import ${appId}`);
          fs.writeFileSync(path.join(dest, f), content, 'utf8');
        }
      }
      return modConfig;
    },
  ]);

  // 2. 注册 receiver + 权限到 AndroidManifest
  config = withAndroidManifest(config, (modConfig) => {
    const manifest = modConfig.modResults.manifest;

    // 1. 添加 RECEIVE_SMS 权限
    if (!manifest['uses-permission']) {
      manifest['uses-permission'] = [];
    }
    const perms = ['android.permission.RECEIVE_SMS'];
    for (const perm of perms) {
      const exists = manifest['uses-permission'].some(p => p.$['android:name'] === perm);
      if (!exists) {
        manifest['uses-permission'].push({ $: { 'android:name': perm } });
      }
    }

    // 2. 添加短信 Receiver
    const receiverNode = {
      $: {
        'android:name': `${PACKAGE}.BillingSmsReceiver`,
        'android:exported': 'true',
      },
      'intent-filter': [{
        action: [{ $: { 'android:name': 'android.provider.Telephony.SMS_RECEIVED' } }],
      }],
    };

    // 确保 application[0] 存在
    if (!Array.isArray(manifest.application) || manifest.application.length === 0) {
      manifest.application = [{ $: {} }];
    }
    const app = manifest.application[0];
    if (!app.receiver) {
      app.receiver = [];
    }
    const exists = app.receiver.some(
      r => r.$['android:name'] === `${PACKAGE}.BillingSmsReceiver`
    );
    if (!exists) {
      app.receiver.push(receiverNode);
    }

    return modConfig;
  });

  return config;
}

module.exports = withSmsReceiver;
