import {
  ASSISTANT_SCOPE_SESSION_APPLICATION,
  ASSISTANT_SCOPE_SESSION_EXPENSE,
  ASSISTANT_SCOPE_SESSION_KNOWLEDGE,
  ASSISTANT_SCOPE_SESSION_STEWARD,
  hasAmbiguousTravelFlowIntent,
  hasExpenseApplicationIntentSignal,
  hasReimbursementIntentSignal,
  inferAssistantScopeTarget
} from './assistantSessionScope.js'

const ASSISTANT_SCOPE_SESSION_BUDGET = 'budget'

function normalizeText(rawText) {
  return String(rawText || '')
    .replace(/\s+/g, '')
    .toLowerCase()
}

function hasEntity(ontology, type, normalizedValue = '') {
  const expectedType = String(type || '').trim()
  const expectedValue = String(normalizedValue || '').trim()
  return Array.isArray(ontology?.entities) && ontology.entities.some((item) => {
    if (String(item?.type || '').trim() !== expectedType) {
      return false
    }
    if (!expectedValue) {
      return true
    }
    return String(item?.normalized_value || item?.value || '').trim() === expectedValue
  })
}

function hasTravelExpenseType(ontology) {
  return hasEntity(ontology, 'expense_type', 'travel')
}

function hasApplicationDocumentEntity(ontology) {
  return hasEntity(ontology, 'document_type', 'expense_application')
    || hasEntity(ontology, 'workflow_stage', 'pre_approval')
}

export function buildWorkbenchIntentOntologyContext({ currentUser = {}, files = [] } = {}) {
  return {
    entry_source: 'workbench',
    session_type: '',
    attachment_count: Array.isArray(files) ? files.length : 0,
    role_codes: Array.isArray(currentUser.roleCodes) ? currentUser.roleCodes : [],
    name: currentUser.name || currentUser.username || '',
    username: currentUser.username || '',
    department: currentUser.department || currentUser.departmentName || '',
    grade: currentUser.grade || ''
  }
}

export function resolveWorkbenchSessionTypeFromOntology(ontology, rawText, fallbackSessionType = '') {
  const text = normalizeText(rawText)
  const fallback = String(fallbackSessionType || '').trim()
  const scenario = String(ontology?.scenario || '').trim()
  const intent = String(ontology?.intent || '').trim()
  const reimbursementSignal = hasReimbursementIntentSignal(text)
  const applicationSignal = hasExpenseApplicationIntentSignal(text)

  if (!text) {
    return fallback
  }

  if (hasAmbiguousTravelFlowIntent(text)) {
    return ASSISTANT_SCOPE_SESSION_STEWARD
  }

  if (applicationSignal && reimbursementSignal) {
    return ASSISTANT_SCOPE_SESSION_STEWARD
  }

  if (hasApplicationDocumentEntity(ontology)) {
    return ASSISTANT_SCOPE_SESSION_APPLICATION
  }

  if (
    !reimbursementSignal
    && (
      applicationSignal
      || (
        scenario === 'expense'
        && intent === 'draft'
        && hasTravelExpenseType(ontology)
        && applicationSignal
      )
      || (scenario === 'budget' && hasTravelExpenseType(ontology) && applicationSignal)
    )
  ) {
    return ASSISTANT_SCOPE_SESSION_APPLICATION
  }

  if (reimbursementSignal && scenario === 'expense' && intent === 'draft') {
    return ASSISTANT_SCOPE_SESSION_EXPENSE
  }

  if (scenario === 'knowledge') {
    return ASSISTANT_SCOPE_SESSION_KNOWLEDGE
  }
  if (scenario === 'budget') {
    return ASSISTANT_SCOPE_SESSION_BUDGET
  }
  if (scenario === 'expense' && intent === 'draft') {
    return ASSISTANT_SCOPE_SESSION_EXPENSE
  }

  return fallback || inferAssistantScopeTarget(rawText)
}

export function resolveWorkbenchSessionTypeFallback(rawText, options = {}) {
  return inferAssistantScopeTarget(rawText, options)
}
