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

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

/** 与 ruoyi-ui vue.config.js publicPath 一致：生产 /screen，开发 / */
function resolvePublicPath(mode, env) {
  if (mode !== 'production') {
    return '/'
  }
  const raw = String(env.VITE_APP_PUBLIC_PATH || '/screen').trim()
  if (!raw || raw === '/') {
    return '/'
  }
  return `/${raw.replace(/^\/+|\/+$/g, '')}/`
}

// https://vite.dev/config/
export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, process.cwd(), '')
  const base = resolvePublicPath(mode, env)

  const baseApi = env.VITE_APP_BASE_API || '/dev-api'
  const proxyTarget = (env.VITE_PROXY_TARGET || 'http://192.168.1.6:8010').replace(/\/$/, '')

  const proxy = {
    [baseApi]: {
      target: proxyTarget,
      changeOrigin: true,
      rewrite: (path) => path.replace(new RegExp(`^${baseApi}`), '')
    },
    '^/v3/api-docs/(.*)': {
      target: proxyTarget,
      changeOrigin: true
    }
  }

  const llmTarget = env.LLM_PROXY_TARGET
  if (llmTarget) {
    proxy['^/llm-dev-proxy'] = {
      target: llmTarget.replace(/\/$/, ''),
      changeOrigin: true,
      rewrite: (path) => path.replace(/^\/llm-dev-proxy/, '')
    }
  }

  const gisTarget = env.VITE_GIS_PROXY_TARGET
  if (gisTarget) {
    proxy['^/gis-dev-proxy'] = {
      target: gisTarget.replace(/\/$/, ''),
      changeOrigin: true,
      rewrite: (path) => path.replace(/^\/gis-dev-proxy/, '')
    }
  }

  return {
    base,
    plugins: [vue()],
    resolve: {
      alias: {
        '@': path.resolve(__dirname, 'src')
      }
    },
    server: {
      host: true,
      port: 5188,
      strictPort: false,
      proxy
    }
  }
})

