import { formatDate, parseDate } from '../../utils/aiDocumentQueryText.js'

const CONFIRM_REQUIRED_ACTIONS = new Set(['delete', 'approve', 'reject'])

function compactText(value = '') {
  return String(value || '').replace(/\s+/g, '').trim()
}

function resolveToday(options = {}) {
  return parseDate(options.today) || new Date()
}

function shiftDay(today, offset) {
  const date = new Date(today.getTime())
  date.setUTCDate(date.getUTCDate() + offset)
  return formatDate(date)
}

function resolveAction(text = '') {
  if (/(标准|制度|规则|政策|口径|怎么|如何|能不能|可以吗)/.test(text)) {
    return 'ask_policy'
  }
  if (/删除|删掉|删了|移除|作废|撤销/.test(text)) {
    return 'delete'
  }
  if (/驳回|退回|拒绝/.test(text)) {
    return 'reject'
  }
  if (/审核|审批|通过|处理待办|去审批|去审核/.test(text)) {
    return 'approve'
  }
  if (/查|看|列出|有哪些|找一下/.test(text)) {
    return 'query'
  }
  if (/新建|发起|创建|我要报销|申请/.test(text)) {
    return 'create'
  }
  if (/补充|修改|改成|填入/.test(text)) {
    return 'update'
  }
  return null
}

function resolveObjectType(text = '') {
  if (/草稿|未提交/.test(text)) {
    return 'draft'
  }
  if (/待办|待审|待审核|待审批|审核单|审批单/.test(text)) {
    return 'approval_task'
  }
  if (/申请单|申请/.test(text)) {
    return 'application'
  }
  if (/报销单|报销/.test(text)) {
    return 'reimbursement'
  }
  if (/票据|发票|附件|图片|文件/.test(text)) {
    return 'receipt'
  }
  if (/单据|单子/.test(text)) {
    return 'document'
  }
  return 'document'
}

function resolveTimeFilter(text = '', options = {}) {
  const today = resolveToday(options)
  const daysAgo = text.match(/(?<days>\d{1,3})天前/)
  if (daysAgo?.groups?.days) {
    const days = Math.max(0, Number(daysAgo.groups.days))
    const value = shiftDay(today, -days)
    return { start: value, end: value, label: `${days}天前` }
  }
  if (/昨天/.test(text)) {
    const value = shiftDay(today, -1)
    return { start: value, end: value, label: '昨天' }
  }
  if (/今天|今日/.test(text)) {
    const value = shiftDay(today, 0)
    return { start: value, end: value, label: '今天' }
  }
  return null
}

function resolveRiskFilter(text = '') {
  if (/无风险|没有风险|暂无风险|无异常|合规/.test(text)) {
    return { level: 'none', label: '无风险' }
  }
  if (/高风险/.test(text)) {
    return { level: 'high', label: '高风险' }
  }
  if (/中风险/.test(text)) {
    return { level: 'medium', label: '中风险' }
  }
  if (/低风险/.test(text)) {
    return { level: 'low', label: '低风险' }
  }
  if (/风险|异常|超标/.test(text)) {
    return { level: 'has', label: '有风险' }
  }
  return null
}

function resolveStatusFilter(text = '', objectType = '') {
  if (objectType === 'draft' || /草稿|未提交/.test(text)) {
    return { keys: ['draft'], label: '草稿' }
  }
  if (/待审|待审核|待审批|审批中|审核中/.test(text)) {
    return { keys: ['submitted', 'pending'], label: '审批中' }
  }
  return null
}

function resolveDocumentType(text = '', objectType = '') {
  if (objectType === 'application' || /申请单|申请/.test(text)) {
    return 'application'
  }
  if (objectType === 'reimbursement' || /报销单|报销/.test(text)) {
    return 'reimbursement'
  }
  return null
}

function hasContextReference(text = '') {
  return /刚才|当前|这个|这张|上面|最近/.test(text)
}

function hasExplicitFilter(filters = {}) {
  return Boolean(filters.timeRange || filters.risk || filters.amount || filters.keyword)
}

function resolveTargetMode(action = '', text = '', filters = {}) {
  if (!CONFIRM_REQUIRED_ACTIONS.has(action)) {
    return 'filtered_candidates'
  }
  if (hasContextReference(text) && !hasExplicitFilter(filters)) {
    return 'current_context'
  }
  return 'filtered_candidates'
}

function resolveSafetyLevel(action = '') {
  if (CONFIRM_REQUIRED_ACTIONS.has(action)) {
    return 'confirm_required'
  }
  return 'read_only'
}

function resolveRiskLevel(action = '') {
  if (CONFIRM_REQUIRED_ACTIONS.has(action)) {
    return 'high'
  }
  if (['create', 'update'].includes(action)) {
    return 'low'
  }
  return 'read_only'
}

function resolveExecutionPolicy({ action, targetMode, riskLevel }) {
  if (action === 'ask_policy') {
    return {
      requiresCandidateSearch: false,
      requiresSelection: false,
      requiresConfirmation: false,
      executionMode: 'answer_only',
      policyDecision: 'answer_only'
    }
  }

  const highRisk = riskLevel === 'high'
  const requiresCandidateSearch = targetMode === 'filtered_candidates'
  const requiresSelection = highRisk && requiresCandidateSearch
  const requiresConfirmation = highRisk

  if (requiresCandidateSearch) {
    return {
      requiresCandidateSearch,
      requiresSelection,
      requiresConfirmation,
      executionMode: 'query_candidates',
      policyDecision: 'query_candidates'
    }
  }
  if (requiresConfirmation) {
    return {
      requiresCandidateSearch,
      requiresSelection,
      requiresConfirmation,
      executionMode: 'need_confirmation',
      policyDecision: 'need_confirmation'
    }
  }
  return {
    requiresCandidateSearch,
    requiresSelection,
    requiresConfirmation,
    executionMode: 'pass_through',
    policyDecision: 'pass_through'
  }
}

function buildNormalizedQuery({ action, objectType, filters }) {
  if ((objectType === 'draft' || action === 'delete') && !filters.timeRange?.label && !filters.risk?.label && !filters.documentType) {
    return '我的草稿单据'
  }
  const parts = []
  if (action === 'approve' || objectType === 'approval_task') {
    parts.push('待我审核')
  } else if (objectType === 'draft' || action === 'delete') {
    parts.push('我的')
  }
  if (filters.timeRange?.label) {
    parts.push(filters.timeRange.label)
  }
  if (filters.risk?.label) {
    parts.push(filters.risk.label)
  }
  if (filters.status?.label && (filters.documentType || objectType !== 'draft')) {
    parts.push(filters.status.label)
  }
  if (filters.documentType === 'application') {
    parts.push('申请单')
  } else if (filters.documentType === 'reimbursement') {
    parts.push('报销单')
  } else if (objectType === 'draft') {
    parts.push('草稿单据')
  } else {
    parts.push('单据')
  }
  return parts.join(' ').trim()
}

export function resolveWorkbenchIntentFrame(prompt = '', options = {}) {
  const text = compactText(prompt)
  if (!text) {
    return null
  }
  const action = resolveAction(text)
  if (!action) {
    return null
  }
  const objectType = resolveObjectType(text)
  const filters = {
    timeRange: resolveTimeFilter(text, options),
    status: resolveStatusFilter(text, objectType),
    risk: resolveRiskFilter(text),
    documentType: resolveDocumentType(text, objectType),
    amount: null,
    keyword: null
  }
  const safetyLevel = resolveSafetyLevel(action)
  const targetMode = action === 'ask_policy'
    ? 'ambiguous'
    : resolveTargetMode(action, text, filters)
  const riskLevel = resolveRiskLevel(action)
  const policy = resolveExecutionPolicy({ action, targetMode, riskLevel })
  return {
    action,
    objectType,
    filters,
    targetMode,
    safetyLevel,
    riskLevel,
    ...policy,
    confidence: 0.86,
    normalizedQuery: action === 'ask_policy' ? String(prompt || '').trim() : buildNormalizedQuery({ action, objectType, filters })
  }
}
