import { defineConfig, type Plugin } from 'vite'
import react from '@vitejs/plugin-react'
import tailwindcss from '@tailwindcss/vite'
import path from 'node:path'
import fs from 'node:fs'

const AUDIO_DIR = path.resolve(__dirname, '../tide-table/punkachien')

/**
 * Dev-only: serve /audio/* from the punkachien dir with HTTP Range support,
 * so wavesurfer can stream + seek the big FLACs without copying them into the
 * bundle. In production, `serve.py --dir dist` with a `dist/audio` symlink does
 * the same job (created post-build), keeping /audio a stable base everywhere.
 */
function audioDevServer(): Plugin {
  return {
    name: 'armada-audio-dev',
    apply: 'serve',
    configureServer(server) {
      server.middlewares.use('/audio', (req, res, next) => {
        const rel = decodeURIComponent((req.url || '').split('?')[0])
        const file = path.join(AUDIO_DIR, rel)
        if (!file.startsWith(AUDIO_DIR) || !fs.existsSync(file) || !fs.statSync(file).isFile())
          return next()
        const size = fs.statSync(file).size
        const range = req.headers.range
        res.setHeader('Accept-Ranges', 'bytes')
        res.setHeader('Content-Type', 'audio/flac')
        if (range) {
          const m = /bytes=(\d*)-(\d*)/.exec(range)
          const start = m && m[1] ? parseInt(m[1], 10) : 0
          const end = m && m[2] ? parseInt(m[2], 10) : size - 1
          res.statusCode = 206
          res.setHeader('Content-Range', `bytes ${start}-${end}/${size}`)
          res.setHeader('Content-Length', String(end - start + 1))
          fs.createReadStream(file, { start, end }).pipe(res)
        } else {
          res.setHeader('Content-Length', String(size))
          fs.createReadStream(file).pipe(res)
        }
      })
    },
  }
}

// https://vite.dev/config/
export default defineConfig({
  plugins: [react(), tailwindcss(), audioDevServer()],
  resolve: { alias: { '@': path.resolve(__dirname, './src') } },
  server: { host: true }, // expose on LAN for phone audition (same wifi)
  build: {
    rollupOptions: {
      input: {
        // Multi-page: the take-judge (index) + the distribution simulator (sextant).
        main: path.resolve(__dirname, 'index.html'),
        sextant: path.resolve(__dirname, 'sextant.html'),
      },
    },
  },
})
