import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import basicSsl from '@vitejs/plugin-basic-ssl'
import wasm from 'vite-plugin-wasm'
import topLevelAwait from 'vite-plugin-top-level-await'
import { execSync } from 'child_process'
import fs from 'fs'

// Read version from package.json
const packageJson = JSON.parse(fs.readFileSync('./package.json', 'utf-8'))
const appVersion = packageJson.version

// Get git commit hash
const gitHash = execSync('git rev-parse --short HEAD').toString().trim()

export default defineConfig({
  plugins: [
    wasm(),
    topLevelAwait(),
    react(),
    // basicSsl() plugin removed - it was causing MIME type issues with raw imports
    // Enable only when specifically needed for HTTPS development
    {
      name: 'html-transform',
      transformIndexHtml(html) {
        return html.replace(/__APP_VERSION__/g, appVersion);
      }
    }
  ],
  server: {
    headers: {
      'Content-Security-Policy': '',  // Empty CSP for dev
    },
  },

  preview: {
    headers: {
      'Content-Security-Policy': '',  // Empty for preview too
    },
  },

  resolve: {
    alias: {
      buffer: 'buffer',
    }
  },
  optimizeDeps: {
    esbuildOptions: {
      define: {
        global: 'globalThis'
      }
    }
  },
  base: process.env.VITE_BASE_PATH || './',  // Use relative paths for offline compatibility
  publicDir: 'public',  // ← Explicitly set (should be default)
  build: {
    outDir: 'dist',
    emptyOutDir: false,
  },
  define: {
    '__APP_VERSION__': JSON.stringify(appVersion),
    '__BUILD_HASH__': JSON.stringify(gitHash),
    '__BUILD_TIMESTAMP__': JSON.stringify(new Date().toISOString()),
    'global': 'globalThis',
  },
  assetsInclude: ['**/*.md', '**/*.txt']  // Enables raw imports for .txt files
})