/**
 * 为 public/60sapi 下 HTML 注入 sixty-runtime.js，并将硬编码的 60s 域名改为 window.__SIXTY_API_BASE__
 */
const fs = require('fs');
const path = require('path');
const root = path.join(__dirname, '../public/60sapi');

function walk(dir) {
  for (const f of fs.readdirSync(dir)) {
    const p = path.join(dir, f);
    const st = fs.statSync(p);
    if (st.isDirectory()) walk(p);
    else if (f.endsWith('.html')) {
      let s = fs.readFileSync(p, 'utf8');
      if (!s.includes('sixty-runtime.js')) {
        if (s.includes('ig-embed.js')) {
          s = s.replace(
            '<script src="/60sapi/ig-embed.js"></script>',
            '<script src="/60sapi/ig-embed.js"></script>\n<script src="/60sapi/sixty-runtime.js"></script>'
          );
        } else {
          s = s.replace('</head>', '<script src="/60sapi/sixty-runtime.js"></script>\n</head>');
        }
      }
      s = s.replace(/fetch\('https:\/\/60s\.api\.shumengya\.top(\/[^']+)'/g, "fetch(window.__SIXTY_API_BASE__+'$1'");
      s = s.replace(/fetch\(`https:\/\/60s\.api\.shumengya\.top/g, 'fetch(`${window.__SIXTY_API_BASE__}');
      s = s.replace(/const API='https:\/\/60s\.api\.shumengya\.top([^']+)'/g, "const API=window.__SIXTY_API_BASE__+'$1'");
      s = s.replace(/const BASE='https:\/\/60s\.api\.shumengya\.top'/g, 'const BASE=window.__SIXTY_API_BASE__');
      fs.writeFileSync(p, s);
    }
  }
}
walk(root);
console.log('patched 60sapi html');
