import fs from 'node:fs'
import path from 'node:path'

const assetPattern = /\.(png|jpe?g|gif|webp|svg|bmp)(\?.*)?$/i

function toPublicUrl(source) {
  if (source.startsWith('../images/')) {
    return `/images/${source.slice('../images/'.length)}`
  }
  if (source.startsWith('../assets/')) {
    return `/assets/${source.slice('../assets/'.length)}`
  }
  if (source.startsWith('images/')) {
    return `/images/${source.slice('images/'.length)}`
  }
  if (source.startsWith('assets/')) {
    return `/assets/${source.slice('assets/'.length)}`
  }
  return `/${source.replace(/^\.\//, '')}`
}

export function missingAssetsPlugin() {
  return {
    name: 'vitepress-missing-assets',
    enforce: 'pre',
    resolveId(source, importer) {
      if (!importer?.endsWith('.md') || !assetPattern.test(source)) {
        return null
      }
      if (/^https?:\/\//.test(source)) {
        return null
      }

      const resolved = path.resolve(path.dirname(importer), source)
      if (fs.existsSync(resolved)) {
        return null
      }

      return `\0missing-asset:${toPublicUrl(source)}`
    },
    load(id) {
      if (!id.startsWith('\0missing-asset:')) {
        return null
      }
      const url = id.slice('\0missing-asset:'.length)
      return `export default ${JSON.stringify(url)}`
    },
  }
}
