/**
 * Environment Configuration
 * Centralized environment variable handling for Chrome Extension
 */

// Get environment variables with fallbacks
const REMOTE_SERVER_HOST = import.meta.env.VITE_REMOTE_SERVER_HOST || '127.0.0.1';
const REMOTE_SERVER_PORT = import.meta.env.VITE_REMOTE_SERVER_PORT || '3001';

// Debug logging for environment variables
console.log('Environment Config Loaded:', {
  VITE_REMOTE_SERVER_HOST: import.meta.env.VITE_REMOTE_SERVER_HOST,
  VITE_REMOTE_SERVER_PORT: import.meta.env.VITE_REMOTE_SERVER_PORT,
  REMOTE_SERVER_HOST,
  REMOTE_SERVER_PORT,
});

// Helper function to determine if we should include port in URL
const shouldIncludePort = (host: string, port: string): boolean => {
  // For localhost/127.0.0.1, always include port
  if (host === '127.0.0.1' || host === 'localhost') {
    return true;
  }

  // For HTTPS domains using standard port 443, don't include port
  if (port === '443') {
    return false;
  }

  // For HTTP domains using standard port 80, don't include port
  if (port === '80') {
    return false;
  }

  // For all other cases, include the port
  return true;
};

// Helper function to determine protocol
const getProtocol = (port: string): { ws: string; http: string } => {
  if (port === '443') {
    return { ws: 'wss', http: 'https' };
  }
  return { ws: 'ws', http: 'http' };
};

// Build URLs based on whether port should be included
const includePort = shouldIncludePort(REMOTE_SERVER_HOST, REMOTE_SERVER_PORT);
const protocols = getProtocol(REMOTE_SERVER_PORT);

const baseUrl = includePort ? `${REMOTE_SERVER_HOST}:${REMOTE_SERVER_PORT}` : REMOTE_SERVER_HOST;

// Remote Server Configuration
export const REMOTE_SERVER_CONFIG = {
  HOST: REMOTE_SERVER_HOST,
  PORT: REMOTE_SERVER_PORT,
  WS_URL: `${protocols.ws}://${baseUrl}/chrome`,
  HTTP_URL: `${protocols.http}://${baseUrl}/mcp`,
} as const;

// Default connection settings
export const DEFAULT_CONNECTION_CONFIG = {
  serverUrl: REMOTE_SERVER_CONFIG.WS_URL,
  reconnectInterval: 3000, // Reduced from 5000ms to 3000ms for faster reconnection
  maxReconnectAttempts: 999999, // Effectively unlimited for persistent connections
} as const;

// Export individual values for backward compatibility
export const DEFAULT_SERVER_URL = REMOTE_SERVER_CONFIG.WS_URL;
export const DEFAULT_HTTP_URL = REMOTE_SERVER_CONFIG.HTTP_URL;
