import { homedir } from 'node:os'
import path from 'node:path'

export const CONFIG_DIR_NAME = '.dimcode'
export const APP_DIR_NAME = 'dimcode'
export const STATE_DIR_NAME = 'state'

export function normalizeStoragePath(value: unknown): string | undefined {
  const next = String(value ?? '').trim()
  return next ? path.resolve(next) : undefined
}

export function resolveConfigHomeFromEnv(
  env?: Record<string, string | undefined>,
): string | undefined {
  const dimcodeHome = normalizeStoragePath(env?.DIMCODE_HOME)
  if (dimcodeHome)
    return dimcodeHome
  if (env && Object.prototype.hasOwnProperty.call(env, 'HOME')) {
    const userHome = normalizeStoragePath(env.HOME)
    return userHome ? path.resolve(userHome, CONFIG_DIR_NAME) : undefined
  }
  return undefined
}

export function resolveDimcodeConfigDir(
  env?: Record<string, string | undefined>,
): string {
  return (
    resolveConfigHomeFromEnv(env)
    ?? path.resolve(homedir(), CONFIG_DIR_NAME)
  )
}

export function resolveDimcodeUserDir(
  env?: Record<string, string | undefined>,
): string {
  return path.resolve(resolveDimcodeConfigDir(env), APP_DIR_NAME)
}

export function resolveDimcodeStateDir(
  env?: Record<string, string | undefined>,
): string {
  const explicitStateDir = normalizeStoragePath(env?.DIMCODE_STATE_DIR)
  if (explicitStateDir)
    return explicitStateDir
  return path.resolve(resolveDimcodeConfigDir(env), STATE_DIR_NAME)
}
