import path from 'node:path'

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueDevTools from 'vite-plugin-vue-devtools'
import packageJson from './package.json' assert { type: 'json' }

// https://vite.dev/config/
export default defineConfig(() => {
  const localRpcProxyTarget = process.env.VITE_LOCAL_RPC_PROXY_TARGET
  const localGraphqlProxyTarget = process.env.VITE_LOCAL_GRAPHQL_PROXY_TARGET ?? 'http://127.0.0.1:42069'
  const localTxnProxyTarget = process.env.VITE_LOCAL_TXN_PROXY_TARGET ?? 'http://127.0.0.1:43069'
  const appVersion = (packageJson as { version?: string }).version ?? 'dev'
  // When served behind a proxy at /app/, set VITE_BASE_PATH=/app/ to ensure assets load correctly
  const basePath = process.env.VITE_BASE_PATH ?? '/'
  // Disable Vue devtools in CI to avoid path resolution issues with the /app/ base path
  const isCI = process.env.CI === 'true' || process.env.CI === 'woodpecker'

  return {
    base: basePath,
    plugins: [
      vue(),
      // Vue devtools causes 500 errors in CI due to path resolution issues
      // when working directory (/app/web-app) doesn't match base path (/app/)
      ...(isCI ? [] : [vueDevTools()]),
    ],
    define: {
      __APP_VERSION__: JSON.stringify(appVersion),
    },
    resolve: {
      alias: {
        '@': path.resolve(process.cwd(), 'src'),
        'kraiken-lib': path.resolve(process.cwd(), '../kraiken-lib/src'),
      },
    },
    server: {
      // Allow Vite to serve files from parent directory (onchain/, kraiken-lib/)
      // Without this, server.fs.strict (default: true) blocks imports like
      // ../../onchain/deployments-local.json when workspace root is web-app/
      fs: {
        allow: ['..'],
      },
      // Allow health checks from CI containers and proxy
      allowedHosts: ['webapp', 'caddy', 'localhost', '127.0.0.1'],
      proxy:
        localRpcProxyTarget || localGraphqlProxyTarget || localTxnProxyTarget
          ? {
              ...(localRpcProxyTarget
                ? {
                    '/api/rpc': {
                      target: localRpcProxyTarget,
                      changeOrigin: true,
                      secure: false,
                      rewrite: (path: string) => {
                        const rewritten = path.replace(/^\/api\/rpc/, '')
                        return rewritten.length === 0 ? '/' : rewritten
                      },
                    },
                  }
                : {}),
              ...(localGraphqlProxyTarget
                ? {
                    '/api/graphql': {
                      target: localGraphqlProxyTarget,
                      changeOrigin: true,
                      secure: false,
                      rewrite: (path: string) => path.replace(/^\/api\/graphql/, '/graphql'),
                    },
                  }
                : {}),
              ...(localTxnProxyTarget
                ? {
                    '/api/txn': {
                      target: localTxnProxyTarget,
                      changeOrigin: true,
                      secure: false,
                      rewrite: (path: string) => {
                        const rewritten = path.replace(/^\/api\/txn/, '')
                        return rewritten.length === 0 ? '/' : rewritten
                      },
                    },
                  }
                : {}),
            }
          : undefined,
    },
  }
})
