import {
  resolveRiskActionability,
  resolveRiskDomain,
  resolveRiskVisibilityScope
} from '../../utils/riskVisibility.js'
import {
  normalizeBusinessStage,
  resolveFlagBusinessStage
} from './travelRequestDetailBusinessStage.js'

function normalizeText(value) {
  return String(value || '').trim()
}

function normalizeTone(value) {
  const tone = normalizeText(value).toLowerCase()
  if (['pass', 'success', 'ok', 'normal', 'none', 'compliant', 'approved'].includes(tone)) return 'pass'
  if (tone === 'high') return 'high'
  if (tone === 'medium') return 'medium'
  if (tone === 'low') return 'low'
  return 'medium'
}

export function resolveRiskTagTone(tag) {
  const normalized = normalizeText(tag).toLowerCase()
  if (normalized === '#high_risk') return 'high'
  if (normalized === '#middle_risk') return 'medium'
  if (normalized === '#low_risk') return 'low'
  if (normalized === '#hotel') return 'hotel'
  if (normalized === '#traffic') return 'traffic'
  return 'neutral'
}

export function extractRiskTagsFromText(text) {
  const matches = normalizeText(text).match(/#[A-Za-z_]+/g) || []
  return [...new Set(matches.map((tag) => tag.toLowerCase()))]
}

export function resolveRiskTags(card = {}) {
  const tags = []
  const tone = normalizeTone(card.tone || card.severity)
  if (tone === 'high') {
    tags.push('#high_risk')
  } else if (tone === 'medium') {
    tags.push('#middle_risk')
  } else if (tone === 'low') {
    tags.push('#low_risk')
  }

  const text = [
    card.label,
    card.title,
    card.risk,
    card.summary,
    card.suggestion,
    card.itemType,
    card.documentType
  ].map((item) => normalizeText(item).toLowerCase()).join(' ')
  if (/住宿|酒店|宾馆|hotel/.test(text)) {
    tags.push('#hotel')
  }
  if (/交通|火车|高铁|机票|航班|出租车|网约车|乘车|车票|train|flight|taxi|traffic|transport/.test(text)) {
    tags.push('#traffic')
  }

  return [...new Set(tags)]
}

export function withRiskTags(card) {
  const businessStage = normalizeBusinessStage(
    card.businessStage
    || card.business_stage
    || card.controlStage
    || card.control_stage
  )
  const riskDomain = resolveRiskDomain(card)
  const actionability = resolveRiskActionability(card, { businessStage, riskDomain })
  const visibilityScope = resolveRiskVisibilityScope(card, { businessStage, riskDomain, actionability })
  return {
    ...card,
    ...(businessStage ? { businessStage } : {}),
    riskDomain,
    risk_domain: riskDomain,
    actionability,
    visibilityScope,
    visibility_scope: visibilityScope,
    tags: resolveRiskTags(card)
  }
}

export function filterRiskCardsByBusinessStage(cards = [], businessStage = 'reimbursement') {
  const targetStage = normalizeBusinessStage(businessStage) || 'reimbursement'
  return (Array.isArray(cards) ? cards : []).filter(
    (card) => resolveFlagBusinessStage(card, targetStage) === targetStage
  )
}
