import prisma from './prisma'

// Environment variable fallbacks for system config keys
const ENV_FALLBACKS: Record<string, string> = {
  AI_PROVIDER_TAGS: process.env.AI_PROVIDER_TAGS || '',
  AI_MODEL_TAGS: process.env.AI_MODEL_TAGS || '',
  AI_PROVIDER_EMBEDDING: process.env.AI_PROVIDER_EMBEDDING || '',
  AI_MODEL_EMBEDDING: process.env.AI_MODEL_EMBEDDING || '',
  AI_PROVIDER_CHAT: process.env.AI_PROVIDER_CHAT || '',
  AI_MODEL_CHAT: process.env.AI_MODEL_CHAT || '',
  OLLAMA_BASE_URL: process.env.OLLAMA_BASE_URL || '',
  OPENAI_API_KEY: process.env.OPENAI_API_KEY || '',
  CUSTOM_OPENAI_API_KEY: process.env.CUSTOM_OPENAI_API_KEY || '',
  CUSTOM_OPENAI_BASE_URL: process.env.CUSTOM_OPENAI_BASE_URL || '',
  ALLOW_REGISTRATION: process.env.ALLOW_REGISTRATION || '',
  NEXTAUTH_URL: process.env.NEXTAUTH_URL || '',
}

export async function getSystemConfig() {
  let dbConfig: Record<string, string> = {}
  try {
    const configs = await prisma.systemConfig.findMany()
    dbConfig = configs.reduce((acc, conf) => {
      acc[conf.key] = conf.value
      return acc
    }, {} as Record<string, string>)
  } catch (e) {
    console.error('Failed to load system config from DB:', e)
  }

  // Merge: DB values take precedence, env vars as fallback
  const merged = { ...ENV_FALLBACKS, ...dbConfig }
  return merged
}

/**
 * Get a config value with a default fallback
 */
export async function getConfigValue(key: string, defaultValue: string = ''): Promise<string> {
  const config = await getSystemConfig()
  return config[key] || defaultValue
}

/**
 * Get a numeric config value with a default fallback
 */
export async function getConfigNumber(key: string, defaultValue: number): Promise<number> {
  const value = await getConfigValue(key, String(defaultValue))
  const num = parseFloat(value)
  return isNaN(num) ? defaultValue : num
}

/**
 * Get a boolean config value with a default fallback
 */
export async function getConfigBoolean(key: string, defaultValue: boolean): Promise<boolean> {
  const value = await getConfigValue(key, String(defaultValue))
  return value === 'true'
}

/**
 * Search configuration defaults
 */
export const SEARCH_DEFAULTS = {
  SEMANTIC_THRESHOLD: 0.65,
  RRF_K_BASE: 20,
  RRF_K_ADAPTIVE: true,
  KEYWORD_BOOST_EXACT: 2.0,
  KEYWORD_BOOST_CONCEPTUAL: 0.7,
  SEMANTIC_BOOST_EXACT: 0.7,
  SEMANTIC_BOOST_CONCEPTUAL: 1.5,
  QUERY_EXPANSION_ENABLED: false,
  QUERY_EXPANSION_MAX_SYNONYMS: 3,
  DEBUG_MODE: false,
} as const
