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

const root = path.join(__dirname, '..');
const sourcePath = path.join(root, 'electron-builder.json5');
const outputPath = path.join(root, 'tools', 'oem-batch-builder', 'electron-builder.oem.generated.json');

function isLargeBundledResource(entry) {
  const from = String(entry && entry.from || '').replace(/\\/g, '/');
  const to = String(entry && entry.to || '').replace(/\\/g, '/');
  return to.startsWith('resources-bundles/')
    || from === 'ziti'
    || from === 'bgm'
    || from.includes('/common/playwright')
    || from.includes('/common/python')
    || from.includes('/common/models')
    || from.includes('/common/fonts');
}

const config = JSON5.parse(fs.readFileSync(sourcePath, 'utf8'));
const oemCoverTemplateFiles = [
  'common/cover-templates/huangbai-shishi.jpg',
  'common/cover-templates/landi-baizi.jpg',
  'common/cover-templates/dasi-baobao.jpg',
  'common/cover-templates/xiehanghuangbai.jpg',
  'common/cover-templates/fenghong-xubai.jpg',
  'common/cover-templates/renyixujzhong.jpg',
  'common/cover-templates/qinglan-xushi.png',
  'common/cover-templates/honghang-xushi.png',
  'common/cover-templates/baihang-xushi.png',
];
for (const templateId of ['11', '22', '33', '44', '55', '66', '77', '88']) {
  oemCoverTemplateFiles.push(`common/cover-templates/subtitle-preview-template_system_${templateId}.png`);
  oemCoverTemplateFiles.push(`common/cover-templates/subtitle-preview-template_system_classic_${templateId}.png`);
}
const oemAsarExcludes = [
  '!node_modules/date-fns{,/**/*}',
  '!node_modules/fluent-ffmpeg{,/**/*}',
  '!node_modules/ttf2woff2{,/**/*}',
  '!node_modules/vue-timeago3{,/**/*}',
  '!node_modules/pdfkit{,/**/*}',
  '!node_modules/fontkit{,/**/*}',
  '!node_modules/@resvg{,/**/*}',
  '!node_modules/moment{,/**/*}',
  '!node_modules/tldts{,/**/*}',
  '!node_modules/polished{,/**/*}',
  '!node_modules/caniuse-lite{,/**/*}',
  '!node_modules/csso{,/**/*}',
  '!node_modules/cheerio{,/**/*}',
  '!node_modules/svgo{,/**/*}',
  '!node_modules/@jimp{,/**/*}',
  '!node_modules/jimp{,/**/*}',
  '!node_modules/lit{,/**/*}',
  '!node_modules/emoji-mart{,/**/*}',
  '!node_modules/@mswjs{,/**/*}',
  '!node_modules/graphql{,/**/*}',
  '!node_modules/mermaid{,/**/*}',
  '!node_modules/@lobehub{,/**/*}',
  '!node_modules/@emoji-mart{,/**/*}',
  '!node_modules/@arco-design{,/**/*}',
  '!node_modules/lucide-react{,/**/*}',
  '!node_modules/typescript{,/**/*}',
  '!node_modules/@shikijs{,/**/*}',
  '!node_modules/@vue{,/**/*}',
  '!node_modules/@babel{,/**/*}',
  '!node_modules/@mermaid-js{,/**/*}',
  '!node_modules/@splinetool{,/**/*}',
  '!node_modules/concurrently{,/**/*}',
  '!node_modules/tailwindcss{,/**/*}',
  '!node_modules/msw{,/**/*}',
  '!node_modules/cytoscape{,/**/*}',
  '!node_modules/cytoscape-fcose{,/**/*}',
  '!node_modules/framer-motion{,/**/*}',
  '!node_modules/katex{,/**/*}',
  '!node_modules/rxjs{,/**/*}',
  '!node_modules/langium{,/**/*}',
  '!node_modules/openai{,/**/*}',
  '!node_modules/@emotion{,/**/*}',
  '!node_modules/d3{,/**/*}',
  '!node_modules/vue{,/**/*}',
  '!node_modules/vue-router{,/**/*}',
  '!node_modules/vue-i18n{,/**/*}',
  '!node_modules/pinia{,/**/*}',
  '!node_modules/xgplayer{,/**/*}',
  '!node_modules/wavesurfer.js{,/**/*}',
  '!node_modules/showdown{,/**/*}',
  '!node_modules/dompurify{,/**/*}',
  '!node_modules/file-saver{,/**/*}',
  '!node_modules/qrcode{,/**/*}',
  '!node_modules/canvg{,/**/*}',
  '!node_modules/svg2img{,/**/*}',
  '!node_modules/svgtofont{,/**/*}',
  '!node_modules/mddir{,/**/*}',
  '!node_modules/@types{,/**/*}',
  '!node_modules/vite{,/**/*}',
  '!node_modules/vite-plugin-electron{,/**/*}',
  '!node_modules/vite-plugin-electron-renderer{,/**/*}',
  '!node_modules/@vitejs{,/**/*}',
  '!node_modules/vue-tsc{,/**/*}',
  '!node_modules/less{,/**/*}',
  '!node_modules/postcss{,/**/*}',
  '!node_modules/autoprefixer{,/**/*}',
  '!node_modules/sass-embedded{,/**/*}',
  '!node_modules/sass-embedded-win32-x64{,/**/*}',
  '!node_modules/electron-builder{,/**/*}',
  '!node_modules/app-builder-bin{,/**/*}',
  '!node_modules/7zip-bin{,/**/*}',
  '!node_modules/wait-on{,/**/*}',
];

if (config.win && Array.isArray(config.win.extraResources)) {
  config.win.extraResources = config.win.extraResources
    .filter(entry => !isLargeBundledResource(entry))
    .map(entry => {
      const from = String(entry && entry.from || '').replace(/\\/g, '/');
      if (from.endsWith('electron/resources/extra') && Array.isArray(entry.filter)) {
        return {
          ...entry,
          filter: entry.filter
            .filter(pattern => String(pattern).replace(/\\/g, '/') !== 'common/config/**/*')
            .filter(pattern => String(pattern).replace(/\\/g, '/') !== 'common/cover-templates/**/*')
            .filter(pattern => !String(pattern).replace(/\\/g, '/').startsWith('win-x86'))
            .concat([
              'common/config/default-templates.json',
              'common/config/default-subtitle-templates.json',
              'common/config/preset_templates.json',
              'common/config/default-ipagent-config.json',
              'common/config/system-templates.json',
              'common/python-scripts/**/*',
              'common/soundEffects/**/*',
              'stickers/**/*',
            ])
            .concat(oemCoverTemplateFiles)
        };
      }
      if (from.endsWith('electron/resources/build') && Array.isArray(entry.filter)) {
        return {
          ...entry,
          filter: entry.filter.filter(pattern => String(pattern).replace(/\\/g, '/') !== 'vc_redist.x64.exe'),
        };
      }
      return entry;
    });
}

if (Array.isArray(config.files)) {
  config.files = config.files
    .filter(entry => !(typeof entry === 'string' && entry.replace(/\\/g, '/') === 'node_modules'))
    .concat(oemAsarExcludes);
}

if (config.win) {
  config.win.target = [
    {
      target: 'dir',
      arch: ['x64'],
    },
  ];
}

if (config.nsis) {
  config.nsis.differentialPackage = false;
}

fs.mkdirSync(path.dirname(outputPath), { recursive: true });
fs.writeFileSync(outputPath, JSON.stringify(config, null, 2), 'utf8');
console.log(`[oem-builder-config] wrote ${outputPath}`);
