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

// https://vitejs.dev/config/
export default defineConfig(({ mode }) => {
  // Load env files
  const env = loadEnv(mode, process.cwd(), '');
  
  // Explicitly check for ENVIRONMENT in all possible places
  // 1. Check env loaded by Vite
  // 2. Check process.env (for Node.js environment)
  // 3. Try to read from .env file directly as fallback
  let environment = env.ENVIRONMENT;
  
  if (!environment && process.env.ENVIRONMENT) {
    environment = process.env.ENVIRONMENT;
  }
  
  if (!environment) {
    try {
      const envContent = fs.readFileSync('.env', 'utf8');
      const envMatch = envContent.match(/ENVIRONMENT\s*=\s*(\w+)/);
      if (envMatch && envMatch[1]) {
        environment = envMatch[1];
      }
    } catch (error) {
      // Fallback if file can't be read
      console.warn('Could not read .env file directly:', error.message);
    }
  }
  
  // Default to 'beta' if still not found
  if (!environment) {
    environment = 'beta';
  }
  
  console.log(`Vite environment detected: ${environment}`);
  
  const isProduction = environment === 'prod';
  
  // Configure HMR based on environment
  let hmrConfig;
  
  if (isProduction) {
    // Production: use the domain name without clientPort
    hmrConfig = { 
      host: 'rocks.2many.ca',
      protocol: 'https'
    };
  } else {
    // Development: use localhost with explicit port
    hmrConfig = { 
      host: 'localhost',
      clientPort: 3000
    };
  }
  
  return {
    plugins: [react()],
    resolve: {
      alias: {
        '@': path.resolve(__dirname, 'src'),
        '@components': path.resolve(__dirname, 'src/components'),
        '@features': path.resolve(__dirname, 'src/features'),
        '@hooks': path.resolve(__dirname, 'src/hooks'),
        '@layouts': path.resolve(__dirname, 'src/layouts'),
        '@pages': path.resolve(__dirname, 'src/pages'),
        '@services': path.resolve(__dirname, 'src/services'),
        '@store': path.resolve(__dirname, 'src/store'),
        '@theme': path.resolve(__dirname, 'src/theme'),
        '@utils': path.resolve(__dirname, 'src/utils'),
        '@assets': path.resolve(__dirname, 'src/assets')
      }
    },
    server: {
      allowedHosts: ['localhost', 'rocks.2many.ca'],
      host: '0.0.0.0', 
      port: 3000,
      watch: {
        usePolling: true,
      },
      hmr: hmrConfig
    },
    build: {
      outDir: 'dist',
      assetsDir: 'assets',
      emptyOutDir: true,
      sourcemap: process.env.NODE_ENV !== 'production'
    },
    // Make environment variables available to the client code
    define: {
      'import.meta.env.ENVIRONMENT': JSON.stringify(environment)
    }
  };
});