import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const root = path.join(__dirname, '../src/i18n');
const am = fs.readFileSync(path.join(root, 'admin-messages.ts'), 'utf8');
const ap = fs.readFileSync(path.join(root, 'admin-pages.ts'), 'utf8');

const zhStart = am.indexOf('const zh:');
const enStart = am.indexOf('const en:');
const msStart = am.indexOf('const ms:');
const exportStart = am.indexOf('export const adminMessages');
const header = am.slice(0, zhStart);
const zhBody = am.slice(zhStart, enStart).replace(/^const zh/, 'const messages');
const enBody = am.slice(enStart, msStart).replace(/^const en/, 'const messages');
const msBody = am.slice(msStart, exportStart).replace(/^const ms/, 'const messages');

const apZhEnd = ap.indexOf('export const adminPagesEn');
function toDefaultExport(block, constName) {
  const body = block
    .replace(`export const ${constName}`, 'const adminPages')
    .trimEnd();
  return `${body}\n\nexport default adminPages;\n`;
}
const apZh = toDefaultExport(ap.slice(0, apZhEnd), 'adminPagesZh');
const apEn = toDefaultExport(ap.slice(apZhEnd), 'adminPagesEn');

fs.mkdirSync(path.join(root, 'bundles'), { recursive: true });
fs.mkdirSync(path.join(root, 'pages'), { recursive: true });
fs.writeFileSync(path.join(root, 'pages/zh.ts'), `${apZh.trim()}\n`);
fs.writeFileSync(path.join(root, 'pages/en.ts'), `${apEn.trim()}\n`);

const bundles = [
  ['zh-CN', zhBody, "import adminPages from '../pages/zh';"],
  ['en-US', enBody, "import adminPages from '../pages/en';"],
  ['ms-MY', msBody, "import adminPages from '../admin-pages-ms';"],
];

for (const [loc, body, pagesImport] of bundles) {
  const content = `${pagesImport}\n${body.replace(/\.\.\.adminPages\w+/g, '...adminPages')}\nexport default { ...messages, ...adminPages };\n`;
  fs.writeFileSync(path.join(root, 'bundles', `${loc}.ts`), content);
}

const typesOnly = header
  .replace(/import \{ adminPagesEn, adminPagesZh \} from '\.\/admin-pages';\r?\n/, '')
  .replace(/import \{ adminPagesMs \} from '\.\/admin-pages-ms';\r?\n/, '')
  + `export const adminMessages: Record<AdminLocale, Record<string, string>> = {\n  'zh-CN': {},\n  'en-US': {},\n  'ms-MY': {},\n};\n`;

fs.writeFileSync(path.join(root, 'admin-messages.ts'), typesOnly);
console.log('split i18n ok');
