import type { TerminalColorCapability } from '@simon_he/vue-tui'
import type { InjectionKey } from 'vue'
import type { UiThemeContext } from './ui-theme'
import { resolveInitialThemeId } from '#cli/core/theme'
import { detectTerminalColorCapability } from '@simon_he/vue-tui'
import { inject } from 'vue'
import { getUiTheme } from './registry'
import { createUiThemeContext } from './ui-theme'

export const DimSdkUiThemeKey: InjectionKey<UiThemeContext> =
  Symbol('DimSdkUiTheme')

function detectFallbackCapability(): TerminalColorCapability {
  const proc: any = (globalThis as any).process
  const env = (proc?.env ?? {}) as Record<string, unknown>
  const isTTY = Boolean(proc?.stdout?.isTTY)
  return detectTerminalColorCapability({
    env,
    isTTY,
    platform: String(proc?.platform ?? ''),
  })
}

export function useUiTheme(): UiThemeContext {
  const injected = inject(DimSdkUiThemeKey, null)
  if (injected) return injected
  const fallback = detectFallbackCapability()
  const id = resolveInitialThemeId((globalThis as any)?.process?.env ?? {})
  const theme = getUiTheme(id)
  return createUiThemeContext(theme, fallback)
}
