import { isEnvDefinedFalsy } from '../../utils/envUtils.js'

type SyntaxTheme = unknown
type ColorDiffLike = unknown
type ColorFileLike = unknown

/* eslint-disable @typescript-eslint/no-require-imports */
const colorDiffModule = (() => {
  try {
    return require('color-diff-napi') as {
      ColorDiff?: ColorDiffLike
      ColorFile?: ColorFileLike
      getSyntaxTheme?: (themeName: string) => SyntaxTheme
    }
  } catch {
    return {}
  }
})()
/* eslint-enable @typescript-eslint/no-require-imports */

const ColorDiff = colorDiffModule.ColorDiff ?? null
const ColorFile = colorDiffModule.ColorFile ?? null
const nativeGetSyntaxTheme = colorDiffModule.getSyntaxTheme ?? (() => null)

export type ColorModuleUnavailableReason = 'env'

/**
 * Returns a static reason why the color-diff module is unavailable, or null if available.
 * 'env' = disabled via CLAUDE_CODE_SYNTAX_HIGHLIGHT
 *
 * The TS port of color-diff works in all build modes, so the only way to
 * disable it is via the env var.
 */
export function getColorModuleUnavailableReason(): ColorModuleUnavailableReason | null {
  if (isEnvDefinedFalsy(process.env.CLAUDE_CODE_SYNTAX_HIGHLIGHT)) {
    return 'env'
  }
  return null
}

export function expectColorDiff(): ColorDiffLike | null {
  return getColorModuleUnavailableReason() === null ? ColorDiff : null
}

export function expectColorFile(): ColorFileLike | null {
  return getColorModuleUnavailableReason() === null ? ColorFile : null
}

export function getSyntaxTheme(themeName: string): SyntaxTheme | null {
  return getColorModuleUnavailableReason() === null
    ? nativeGetSyntaxTheme(themeName)
    : null
}
