#!/usr/bin/env node
/**
 * 热修补已构建 main/index.js 中主题/贴图路径对非字符串 .trim() / .replace() 崩溃的问题。
 * Cocos Creator 重新构建后可由 deploy-to-001code.sh 自动调用。
 */
const fs = require('fs');
const path = require('path');

const REPLACEMENTS = [
  [
    'function D(e){if(null==e||!e.trim())return"silu";var t=e.trim();',
    'function D(e){var t=String(null==e?"":e).trim();if(!t)return"silu";',
  ],
  [
    'getThemeTilePath:function(e,t){var r=D(e),n=J(r);if(!n)return;var l="string"==typeof t?t.trim():null==t?"":String(t);if(!l)return;',
    'getThemeTilePath:function(e,t){var r=D(e),n=J(r);if(!n)return;var l=String(null==t?"":t).trim();if(!l)return;',
  ],
  [
    'function M(e){var t,r=I(e);return(null==r||null==(t=r.borderDecorKey)?void 0:t.trim())||void 0}',
    'function M(e){var r,n=I(D(e)),o=null==n?void 0:n.borderDecorKey,t="string"==typeof o?o.trim():null==o?"":String(o);return t||void 0}',
  ],
  [
    'var l=null==t?void 0:t.trim();if(!l)return;',
    'var l="string"==typeof t?t.trim():null==t?"":String(t);if(!l)return;',
  ],
  [
    'pathCacheKey=function(e){return e.replace(/\\\\/g,"/")}',
    'pathCacheKey=function(e){var t="string"==typeof e?e:null==e?"":String(e);return t.replace(/\\\\/g,"/")}',
  ],
  [
    'getThemeBackground:function(e){var t,r=I(e);return(null==r||null==(t=r.background)?void 0:t.trim())||void 0}',
    'getThemeBackground:function(e){var t,r=I(e),n=null==r?void 0:r.background,o="string"==typeof n?n.trim():null==n?"":String(n);return o||void 0}',
  ],
  [
    'function(e){if(e){var n=e.trim();return"redArmy"===n?"redarmy":n}}',
    'function(e){if(null==e)return;var n="string"==typeof e?e.trim():String(e);if(!n)return;return"redArmy"===n?"redarmy":n}',
  ],
  [
    'function g(e,t){var r,n=null==(r=Y(e)[t])?void 0:r.trim();return n||y.silu[t]}',
    'function g(e,t){var r,n=Y(e)[t],o="string"==typeof n?n.trim():null==n?"":String(n);return o||y.silu[t]}',
  ],
  [
    'o=null==u||null==(r=u.portrait)?void 0:r.trim()',
    'o=null==u?void 0:(r=u.portrait,r="string"==typeof r?r.trim():null==r?"":String(r),r||void 0)',
  ],
  [
    'ull==u||null==(n=u.playerFront)?void 0:n.trim()',
    'ull==u?void 0:(n=u.playerFront,n="string"==typeof n?n.trim():null==n?"":String(n),n||void 0)',
  ],
  [
    'null==(t=r.cocosPrefab)?void 0:t.trim()',
    '(t=r.cocosPrefab,t="string"==typeof t?t.trim():null==t?"":String(t),t||void 0)',
  ],
];

function patchFile(file) {
  if (!fs.existsSync(file)) {
    console.log('  skip (missing):', file);
    return false;
  }
  let src = fs.readFileSync(file, 'utf8');
  let changed = false;
  for (const [from, to] of REPLACEMENTS) {
    if (src.includes(from)) {
      src = src.replace(from, to);
      changed = true;
    }
  }
  const before = src;
  src = src.replace(
    /"string"==typeof ([a-zA-Z_$][\w$]*)\?\1\.trim\(\):null==\1\?"":String\(\1\)/g,
    'String(null==$1?"":$1).trim()',
  );
  src = src.replace(
    /function D\(e\)\{var t="string"==typeof e\?e\.trim\(\):null==e\?"":String\(e\);/g,
    'function D(e){var t=String(null==e?"":e).trim();',
  );
  if (src !== before) changed = true;
  if (!changed) {
    if (src.includes('String(null==t?"":t).trim()') && src.includes('pathCacheKey=function(e){var t="string"==typeof e')) {
      console.log('  already patched:', file);
      return true;
    }
    console.warn('  no match:', file);
    return false;
  }
  fs.writeFileSync(file, src, 'utf8');
  console.log('  patched:', file);
  return true;
}

const targets = process.argv.slice(2);
if (!targets.length) {
  console.error('Usage: node patch-theme-trim-hotfix.js <main/index.js> [...]');
  process.exit(1);
}

let ok = true;
for (const t of targets) {
  if (!patchFile(path.resolve(t))) ok = false;
}
process.exit(ok ? 0 : 1);
