#!/usr/bin/env node
'use strict';

/**
 * Após cada `cordova prepare`, aplica FLAG_SECURE na MainActivity conforme preferência
 * salva pelo plugin ScreenCapture (libera print/gravação para cargos permitidos no JS).
 */

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

const ROOT = path.join(__dirname, '..');
const MAIN_ACTIVITY = path.join(
  ROOT,
  'platforms',
  'android',
  'app',
  'src',
  'main',
  'java',
  'br',
  'com',
  'FBRegistroPro',
  'MainActivity.java'
);

const POLICY_CALL = 'ScreenCapturePlugin.applySavedPolicy(this);';

const OLD_SECURE_BLOCK =
  '\n\n        getWindow().setFlags(\n                WindowManager.LayoutParams.FLAG_SECURE,\n                WindowManager.LayoutParams.FLAG_SECURE);';

function main() {
  if (!fs.existsSync(MAIN_ACTIVITY)) {
    console.warn('[flag-secure] MainActivity não encontrado (rode com plataforma android); ignorando.');
    return;
  }

  let src = fs.readFileSync(MAIN_ACTIVITY, 'utf8');
  let changed = false;

  if (src.includes(OLD_SECURE_BLOCK)) {
    src = src.replace(OLD_SECURE_BLOCK, '\n\n        ' + POLICY_CALL);
    changed = true;
  }

  const needle = 'super.onCreate(savedInstanceState);';
  if (!src.includes(POLICY_CALL) && src.includes(needle)) {
    src = src.replace(needle, needle + '\n\n        ' + POLICY_CALL);
    changed = true;
  }

  if (!src.includes('protected void onResume()')) {
    const classNeedle = 'public class MainActivity extends CordovaActivity';
    const onResumeBlock =
      '\n    @Override\n    protected void onResume() {\n        super.onResume();\n        ' +
      POLICY_CALL +
      '\n    }\n';
    if (src.includes(classNeedle)) {
      const loadUrlIdx = src.indexOf('loadUrl(launchUrl);');
      if (loadUrlIdx >= 0) {
        const lineEnd = src.indexOf('\n', loadUrlIdx);
        const insertAt = lineEnd >= 0 ? lineEnd + 1 : src.length;
        src = src.slice(0, insertAt) + onResumeBlock + src.slice(insertAt);
        changed = true;
      }
    }
  } else if (!src.includes(POLICY_CALL) || !src.match(/onResume[\s\S]*applySavedPolicy/)) {
    src = src.replace(
      /protected void onResume\(\) \{\s*\n\s*super\.onResume\(\);/,
      'protected void onResume() {\n        super.onResume();\n        ' + POLICY_CALL
    );
    changed = true;
  }

  if (src.includes('WindowManager.LayoutParams.FLAG_SECURE') && !src.includes(POLICY_CALL)) {
    console.warn('[flag-secure] MainActivity com FLAG_SECURE legado; revise manualmente.');
  }

  if (changed) {
    fs.writeFileSync(MAIN_ACTIVITY, src, 'utf8');
    console.log('[flag-secure] MainActivity usa ScreenCapturePlugin.applySavedPolicy.');
  }
}

main();
