import { writeFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { all } from 'country-codes-list';

const __dirname = dirname(fileURLToPath(import.meta.url));
const outPath = join(__dirname, '../src/phone-dial-codes.json');

/** 平台开放注册/短信的国家（ISO 3166-1 alpha-2） */
const ALLOWED_PHONE_ISO = ['MY', 'SG', 'IN', 'AU', 'TH', 'VN', 'BD', 'TW'];

/** 平台常用市场置顶（须为 ALLOWED_PHONE_ISO 子集） */
const PINNED_ISO = ['MY', 'SG', 'IN', 'AU', 'TH', 'VN', 'BD', 'TW'];

const entries = all()
  .filter((c) => c.countryCallingCode && c.countryCode && ALLOWED_PHONE_ISO.includes(c.countryCode))
  .map((c) => ({
    iso: c.countryCode,
    dial: c.countryCallingCode,
    nameEn: c.countryNameEn,
    nameLocal: c.countryNameLocal || c.countryNameEn,
    flag: c.flag || '',
    region: c.region || '',
  }))
  .sort((a, b) => {
    const pa = PINNED_ISO.indexOf(a.iso);
    const pb = PINNED_ISO.indexOf(b.iso);
    if (pa !== -1 || pb !== -1) {
      if (pa === -1) return 1;
      if (pb === -1) return -1;
      return pa - pb;
    }
    return a.nameEn.localeCompare(b.nameEn, 'en');
  });

writeFileSync(outPath, `${JSON.stringify(entries, null, 2)}\n`, 'utf8');
console.log(`Wrote ${entries.length} countries to ${outPath}`);
