/**
 * Feature flag system
 *
 * Flags can be configured via environment variables or runtime overrides.
 * Environment variables take precedence over defaults.
 * Runtime overrides take precedence over environment variables.
 */

export interface FeatureFlags {
  IMAGE_UPLOADS_ENABLED: boolean
  DIFF_TOOL_ENABLED: boolean
}

/**
 * Default values for all feature flags
 */
export const FLAG_DEFAULTS: FeatureFlags = {
  IMAGE_UPLOADS_ENABLED: true,
  DIFF_TOOL_ENABLED: true,
}

/**
 * Global cache key for runtime flags
 */
const CACHE_KEY = '__MULTI_AGENT_CHAT_FLAGS__'

/**
 * Parse boolean from string environment variable
 */
export function parseBool(value: string | undefined, defaultValue: boolean): boolean {
  if (value === undefined || value === '') {
    return defaultValue
  }

  const normalized = value.toLowerCase().trim()

  if (normalized === 'true' || normalized === '1' || normalized === 'yes') {
    return true
  }

  if (normalized === 'false' || normalized === '0' || normalized === 'no') {
    return false
  }

  return defaultValue
}

/**
 * Get feature flags from environment variables with caching
 */
export function getFlags({ refresh = false }: { refresh?: boolean } = {}): FeatureFlags {
  // Check for cached runtime overrides
  const cached = (globalThis as any)[CACHE_KEY]
  if (cached && !refresh) {
    return cached
  }

  // Build flags from environment variables
  const flags: FeatureFlags = {
    IMAGE_UPLOADS_ENABLED: parseBool(
      process.env.IMAGE_UPLOADS_ENABLED,
      FLAG_DEFAULTS.IMAGE_UPLOADS_ENABLED
    ),
    DIFF_TOOL_ENABLED: parseBool(
      process.env.DIFF_TOOL_ENABLED,
      FLAG_DEFAULTS.DIFF_TOOL_ENABLED
    ),
  }

  // Cache the flags
  ;(globalThis as any)[CACHE_KEY] = flags

  return flags
}

/**
 * Register runtime flag overrides (useful for testing)
 */
export function registerRuntimeFlags(overrides: Partial<FeatureFlags>): void {
  const currentFlags = getFlags({ refresh: true })
  const newFlags = { ...currentFlags, ...overrides }
  ;(globalThis as any)[CACHE_KEY] = newFlags
}

/**
 * Clear the flag cache (useful for testing)
 */
export function resetFlagsCache(): void {
  delete (globalThis as any)[CACHE_KEY]
}

/**
 * Proxy object for convenient flag access
 * Usage: Flags.IMAGE_UPLOADS_ENABLED
 */
export const Flags = new Proxy({} as FeatureFlags, {
  get(_target, prop: string) {
    const flags = getFlags()
    return flags[prop as keyof FeatureFlags]
  },
})
