/**
 * Module resolution hook for tsx runtime.
 *
 * Handles:
 *   1. bun:bundle → shim (feature() returns custom flags)
 *   2. .md files → export as string
 *   3. .napi/.node files → empty export
 */
import { readFileSync } from 'fs'
import { dirname, join } from 'path'
import { fileURLToPath, pathToFileURL } from 'url'

const __dirname = dirname(fileURLToPath(import.meta.url))
const shimUrl = pathToFileURL(join(__dirname, 'bun_bundle.js')).href



export function resolve(specifier, context, nextResolve) {
  if (specifier === 'bun:bundle') {
    return { url: shimUrl, shortCircuit: true }
  }
  return nextResolve(specifier, context)
}
export function load(url, context, nextLoad) {
  // Handle .md files — export content as a string
  if (url.endsWith('.md')) {
    const filePath = fileURLToPath(url)
    let content;
    try {
      content = readFileSync(filePath, 'utf-8')
    } catch {
      content = ''
    }
    return {
      format: 'module',
      source: `export default ${JSON.stringify(content)};`,
      shortCircuit: true,
    }
  }

  // Handle native addons — return empty export
  if (url.endsWith('.node') || url.endsWith('.napi')) {
    return {
      format: 'module',
      source: 'export default {};',
      shortCircuit: true,
    }
  }

  return nextLoad(url, context)
}
