import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { fileURLToPath, URL } from 'node:url'

// 豆包 ASR 鉴权信息（与 src/config/index.js 保持一致）
const DOUBAO_APP_ID = '2542859186'
const DOUBAO_ACCESS_TOKEN = 'a4h5fT3cVlBi82u93iEQlqT3c4MP6_8V'
const DOUBAO_ASR_RESOURCE_ID = 'volc.bigasr.sauc.duration'

// https://vite.dev/config/
export default defineConfig({
  plugins: [vue()],
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url))
    }
  },
  server: {
    host: '0.0.0.0',
    proxy: {
      // 后端 API 代理
      '/api': {
        target: 'http://localhost:3001',
        changeOrigin: true,
      },
      '/tts-api': {
        target: 'https://openspeech.bytedance.com',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/tts-api/, '')
      },
      '/ark-api': {
        target: 'https://ark.cn-beijing.volces.com',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/ark-api/, '')
      },
      '/dashscope-api': {
        target: 'https://dashscope.aliyuncs.com',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/dashscope-api/, '')
      },
      // ASR WebSocket 代理：在代理层注入鉴权 Header（浏览器 WS 不支持自定义 Header）
      '/asr-ws': {
        target: 'wss://openspeech.bytedance.com',
        changeOrigin: true,
        ws: true,
        rewrite: (path) => path.replace(/^\/asr-ws/, ''),
        configure: (proxy) => {
          proxy.on('proxyReqWs', (proxyReq) => {
            proxyReq.setHeader('X-Api-App-Key', DOUBAO_APP_ID)
            proxyReq.setHeader('X-Api-Access-Key', DOUBAO_ACCESS_TOKEN)
            proxyReq.setHeader('X-Api-Resource-Id', DOUBAO_ASR_RESOURCE_ID)
            proxyReq.setHeader('X-Api-Connect-Id', crypto.randomUUID())
          })
        }
      },
      // 阿里云OSS音频代理：解决COEP策略问题（支持多个OSS域名）
      '/oss-audio': {
        target: 'https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/oss-audio/, ''),
        configure: (proxy) => {
          proxy.on('proxyRes', (proxyRes) => {
            // 添加CORS头以符合COEP要求
            proxyRes.headers['access-control-allow-origin'] = '*'
          })
        }
      },
      // 阿里云OSS图片代理（支持多个OSS域名）
      '/oss-image': {
        target: 'https://dashscope-7c2c.oss-accelerate.aliyuncs.com',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/oss-image/, ''),
        configure: (proxy) => {
          proxy.on('proxyRes', (proxyRes) => {
            proxyRes.headers['access-control-allow-origin'] = '*'
          })
        }
      }
    }
  }
})
