import fs from 'fs'
import path from 'path'
import axios from 'axios'

const outDir = path.join(process.cwd(), 'public', 'logos')
const proxy = (url) => `https://images.weserv.nl/?url=${encodeURIComponent(url)}`
const logos = {
  // Banks
  'bca.svg': 'https://upload.wikimedia.org/wikipedia/commons/3/3f/Bank_Central_Asia.svg',
  'bni.svg': 'https://upload.wikimedia.org/wikipedia/commons/2/23/Bank_Negara_Indonesia_logo.svg',
  'bri.svg': 'https://upload.wikimedia.org/wikipedia/commons/4/42/BRI_2020.svg',
  'cimb.svg': 'https://upload.wikimedia.org/wikipedia/commons/2/2d/CIMB_Niaga_logo.svg',
  'mandiri.svg': 'https://upload.wikimedia.org/wikipedia/commons/d/df/Bank_Mandiri_logo_2016.svg',
  'permata.svg': 'https://upload.wikimedia.org/wikipedia/commons/4/42/PermataBank_logo.svg',
  // Cards
  'visa.svg': 'https://upload.wikimedia.org/wikipedia/commons/0/04/Visa.svg',
  'mastercard.svg': 'https://upload.wikimedia.org/wikipedia/commons/2/2a/Mastercard-logo.svg',
  'jcb.svg': 'https://upload.wikimedia.org/wikipedia/commons/3/3a/JCB_logo.svg',
  'amex.svg': 'https://upload.wikimedia.org/wikipedia/commons/3/30/American_Express_logo_%282018%29.svg',
  // Wallets
  'gopay.svg': 'https://upload.wikimedia.org/wikipedia/commons/1/1e/Logo_GoPay.svg',
  'qris.svg': 'https://upload.wikimedia.org/wikipedia/commons/0/0a/QRIS_Logo.svg',
}

async function download(name, url) {
  const dst = path.join(outDir, name)
  try {
    if (fs.existsSync(dst)) {
      console.log(`[skip] ${name} already exists`)
      return
    }
    const res = await axios.get(proxy(url), { responseType: 'arraybuffer' })
    fs.writeFileSync(dst, Buffer.from(res.data))
    console.log(`[ok] ${name}`)
  } catch (err) {
    console.error(`[err] ${name}:`, err?.message || err)
  }
}

async function main() {
  fs.mkdirSync(outDir, { recursive: true })
  const entries = Object.entries(logos)
  for (const [name, url] of entries) {
    await download(name, url)
  }
  console.log(`Done. Saved ${entries.length} logos to ${outDir}`)
}

main()