import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import fs from 'fs'
import path from 'path'
import { fileURLToPath } from 'url'

const __dirname = path.dirname(fileURLToPath(import.meta.url))

// https://vite.dev/config/
export default defineConfig({
  plugins: [
    vue(),
    // 让 Vite 开发服务器正确提供 .py 文件的静态服务
    {
      name: 'serve-py-files',
      configureServer(server) {
        server.middlewares.use((req, res, next) => {
          const url = req.url
          // 只处理 .py 文件请求，且排除 API 路径
          if (url.endsWith('.py') && !url.startsWith('/api/')) {
            const filePath = path.join(__dirname, 'public', url.replace(/^\//, ''))
            if (fs.existsSync(filePath)) {
              const content = fs.readFileSync(filePath, 'utf-8')
              res.setHeader('Content-Type', 'text/plain; charset=utf-8')
              res.statusCode = 200
              res.end(content)
              return
            }
          }
          next()
        })
      }
    }
  ],
  server: {
    port: 1025,
    proxy: {
      '/api': {
        target: 'http://localhost:3002',
        changeOrigin: true,
      },
    },
  },
  test: {
    environment: 'jsdom',
    globals: true,
  },
})
