import { computed, ref } from 'vue'
import type { KbxAiAnswer, KbxAiScreenContext, KbxScreenDefinition, KbxSuggestionRequest } from '@kbx/contracts'
import { helpRegistry } from '../help/helpRegistry'
import { submitKbxSuggestion } from './suggestionApi'
import { askKbxAssistant } from './aiAssistantApi'
import { kbxAiCapabilities } from '../permissions/authorizationPolicy'

export interface KbxRuntimeContext {
  route: string
  appVersion: string
  userRole: string
  filters?: Record<string, unknown>
  selectedIds?: string[]
  entityId?: string
  grantedPermissions?: string[]
}

export function useKbxScreenUtility(screen: KbxScreenDefinition, runtime: KbxRuntimeContext) {
  const aiLoading = ref(false)
  const aiAnswer = ref<KbxAiAnswer | null>(null)
  const aiError = ref('')
  const suggestionSubmitting = ref(false)

  const help = computed(() => screen.helpKey ? helpRegistry[screen.helpKey] : undefined)
  const aiContext = computed<KbxAiScreenContext>(() => ({
    screenId: screen.id,
    screenVersion: screen.version,
    entityId: runtime.entityId,
    selectedIds: runtime.selectedIds,
    filters: runtime.filters,
    allowedCapabilities: kbxAiCapabilities(runtime.grantedPermissions ?? [], ['explain', 'suggest', 'draft']),
  }))
  const suggestionContext = computed(() => ({
    screenId: screen.id,
    screenVersion: screen.version,
    route: runtime.route,
    appVersion: runtime.appVersion,
    userRole: runtime.userRole,
    activeFilters: runtime.filters ? Object.keys(runtime.filters).filter(k => runtime.filters?.[k] != null) : [],
  }))

  async function askAi(question: string) {
    aiLoading.value = true
    aiError.value = ''
    try {
      aiAnswer.value = await askKbxAssistant({ question, context: aiContext.value })
    } catch {
      aiError.value = '네트워크 상태를 확인한 후 다시 질문하세요.'
    } finally {
      aiLoading.value = false
    }
  }

  async function submitSuggestion(request: KbxSuggestionRequest) {
    suggestionSubmitting.value = true
    try {
      return await submitKbxSuggestion(request)
    } finally {
      suggestionSubmitting.value = false
    }
  }

  return { help, aiContext, aiAnswer, aiLoading, aiError, suggestionContext, suggestionSubmitting, askAi, submitSuggestion }
}
