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

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

// 启动后端服务器
let backendProcess = null

function startBackend() {
  if (backendProcess) return
  
  console.log('🚀 Starting Loco backend server...')
  backendProcess = spawn('cargo', ['loco', 'start'], {
    cwd: path.join(__dirname, 'src-loco'),
    stdio: 'inherit',
    shell: true
  })
  
  backendProcess.on('error', (err) => {
    console.error('Failed to start backend:', err)
  })
  
  backendProcess.on('exit', (code) => {
    console.log(`Backend server exited with code ${code}`)
    backendProcess = null
  })
}

export default defineConfig({
  plugins: [
    vue(), 
    tailwindcss(),
    {
      name: 'start-backend',
      configureServer() {
        startBackend()
      }
    }
  ],
  resolve: {
    alias: {
      '@': path.resolve(__dirname, './src')
    }
  },
  server: {
    port: 5173,
    proxy: {
      '/api': {
        target: 'http://localhost:5150',
        changeOrigin: true
      }
    }
  },
  build: {
    outDir: 'dist'
  }
})
