import type { DimSdkStore } from '#cli/core/store'
import {
  DEFAULT_SHORTCUTS,
  formatShortcutLabel,
} from '#cli/core/ui-settings'
import { readRuntimeVersion } from '#cli/core/version-env'
import { t } from '#cli/i18n'
import { getDimcodeUserDir } from '../../cli/user-cache'

type StartupToastStore = Pick<
  DimSdkStore,
  'state' | 'setEnvVar' | 'showUpgradeNotification'
>

type NodeLikeProcess = {
  env?: Record<string, string | undefined>
}

type StartupToastGlobals = typeof globalThis & {
  process?: NodeLikeProcess
  __DIMCODE_UPGRADE_TOAST__?: (text: string) => void
}

/**
 * Consume and clear a one-shot startup toast message from environment.
 *
 * Used for things like upgrade notifications where the process relaunches.
 */
export function consumeStartupToast(
  opts: Readonly<{
    store: StartupToastStore
    nodeLike: boolean
    showToast: (text: string) => void
  }>,
): void {
  const env = opts.store.state.context.env
  const globals = globalThis as StartupToastGlobals
  const showUpgradeToast = (text: string) => {
    opts.store.showUpgradeNotification(text)
  }

  const procEnv = globals.process?.env
  const isTest = String(procEnv?.DIMCODE_TEST ?? '').trim() === '1'

  if (opts.nodeLike)
    globals.__DIMCODE_UPGRADE_TOAST__ = showUpgradeToast

  const upgradeToast = String(env.DIMCODE_STARTUP_UPGRADE_TOAST ?? '').trim()
  if (upgradeToast) {
    showUpgradeToast(upgradeToast)

    opts.store.setEnvVar('DIMCODE_STARTUP_UPGRADE_TOAST', undefined)

    if (opts.nodeLike) {
      const proc = globals.process
      if (proc?.env) {
        delete proc.env.DIMCODE_STARTUP_UPGRADE_TOAST
      }
    }
  }

  if (opts.nodeLike) {
    void consumeUpgradeToastFile(env, showUpgradeToast)
  }

  if (!isTest) {
    const version = readRuntimeVersion(env)
    const uiState = opts.store.state.ui
    const seen = String(uiState.onboarding.lastSeenVersion ?? '').trim()
    const upgradeVisible = uiState.upgradeNotification.visible
    if (!upgradeVisible && version && seen !== version) {
      const commandsKey =
        formatShortcutLabel(DEFAULT_SHORTCUTS.commands) || 'Ctrl+P'
      const message = t('help.onboarding', {
        commandsKey,
        sessions: '/sessions',
        timeline: '/tl',
      })
      if (message) showUpgradeToast(message)
      uiState.onboarding = {
        ...uiState.onboarding,
        lastSeenVersion: version,
      }
    }
  }

  const toast = String(env.DIMCODE_STARTUP_TOAST ?? '').trim()
  if (!toast) return

  opts.showToast(toast)
  opts.store.setEnvVar('DIMCODE_STARTUP_TOAST', undefined)

  if (!opts.nodeLike) return

  const proc = globals.process
  if (proc?.env) {
    delete proc.env.DIMCODE_STARTUP_TOAST
  }
}

async function consumeUpgradeToastFile(
  env: Record<string, string | undefined>,
  showUpgradeToast: (text: string) => void,
): Promise<void> {
  try {
    const [{ readFile, unlink }, path] = await Promise.all([
      import('node:fs/promises'),
      import('node:path'),
    ])
    const dir = await getDimcodeUserDir(env)
    const filePath = path.join(dir, 'upgrade-toast.json')
    const raw = await readFile(filePath, 'utf8')
    const parsed = JSON.parse(raw)
    const message = String(parsed?.message ?? '').trim()
    await unlink(filePath)
    if (message) {
      showUpgradeToast(message)
    }
  } catch {
    // ignore
  }
}
