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

export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, __dirname, '')

  function parseDotenvFile(filePath: string) {
    try {
      if (!fs.existsSync(filePath)) return {}
      const text = fs.readFileSync(filePath, 'utf-8')
      const result: Record<string, string> = {}
      for (const rawLine of text.split(/\r?\n/)) {
        const line = rawLine.trim()
        if (!line || line.startsWith('#')) continue
        const eq = line.indexOf('=')
        if (eq <= 0) continue
        const key = line.slice(0, eq).trim()
        let value = line.slice(eq + 1).trim()
        if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) {
          value = value.slice(1, -1)
        }
        result[key] = value
      }
      return result
    } catch {
      return {}
    }
  }

  // Vite only loads env files under `frontend/` by default.
  // Many Jarvis setups keep HOST/PORT in repo root `.env`, so we read it explicitly as a fallback.
  const rootEnvPath = path.resolve(__dirname, '../.env')
  const rootEnv = parseDotenvFile(rootEnvPath)
  const rootHost = (rootEnv.HOST || '127.0.0.1').trim()
  const rootPort = (rootEnv.PORT || '').trim()
  const rootApi = (rootEnv.VITE_API_URL || (rootPort ? `http://${rootHost}:${rootPort}` : '')).trim()

  const apiTarget = env.VITE_API_URL || rootApi || 'http://localhost:8000'

  return {
  plugins: [vue()],
  resolve: {
    alias: {
      '@': path.resolve(__dirname, './src'),
    },
  },
  server: {
    proxy: {
      '/api': {
        target: apiTarget,
        changeOrigin: true,
      },
    },
  },
}
})
