import {
  AI_APPLICATION_ACTION_SAVE_DRAFT,
  AI_APPLICATION_ACTION_SUBMIT
} from '../../services/aiApplicationPreviewActions.js'

export function isReimbursementCreationIntent(prompt = '') {
  const compact = String(prompt || '').replace(/\s+/g, '')
  if (!compact || !/报销|报账/.test(compact)) {
    return false
  }
  if (/标准|制度|规则|政策|口径|怎么|如何|能不能|可以吗|查一下|查询|状态|进度|多少钱|多少/.test(compact)) {
    return false
  }
  return (
    /^(我要|我想|我需要|帮我|请帮我|需要|发起|新建|创建|提交|办理|走).{0,16}(报销|报账)/.test(compact) ||
    /^(报销|报账)(一下|一笔|单|流程)?$/.test(compact)
  )
}

export function resolveInlineTravelApplicationRequest(prompt = '') {
  const sourceText = String(prompt || '').trim()
  const compact = sourceText.replace(/\s+/g, '')
  if (!compact) {
    return null
  }
  if (/标准|制度|规则|政策|口径|怎么|如何|能不能|可以吗|查一下|查询|状态|进度|多少钱|多少/.test(compact)) {
    return null
  }

  const hasTravelIntent = /出差|差旅|差旅费|交通/.test(compact)
  const hasTravelDetail = (
    /去[\u4e00-\u9fa5A-Za-z0-9]{2,24}/.test(compact) ||
    /[\u4e00-\u9fa5A-Za-z0-9]{2,24}出差/.test(compact) ||
    /地点[:：]?[\u4e00-\u9fa5A-Za-z0-9]{2,24}/.test(compact) ||
    /交通(?:方式)?[:：]?(火车|高铁|动车|飞机|航班|轮船|轮渡|汽车|网约车|自驾)/.test(compact) ||
    /(火车|高铁|动车|飞机|航班|轮船|轮渡|汽车|网约车|自驾)/.test(compact)
  )
  if (!hasTravelIntent || !hasTravelDetail) {
    return null
  }

  return {
    expenseType: 'travel',
    expenseTypeLabel: '差旅费',
    sourceText,
    autoSubmit: false,
    requestedSubmit: /直接提交|提交申请|确认提交|提交审批/.test(compact)
  }
}

export function resolveInlineApplicationPreviewTextAction(text = '') {
  const normalized = String(text || '').replace(/\s+/g, '').trim()
  if (!normalized) {
    return ''
  }
  if (/^(保存草稿|保存|存草稿|先保存|保存这个单据|保存这个申请|保存这个申请单|保存这张单据|保存这张申请单|保存当前单据|保存当前申请|保存上面的单据|保存刚才的草稿)$/.test(normalized)) {
    return AI_APPLICATION_ACTION_SAVE_DRAFT
  }
  if (/^(提交|提交申请|确认提交|提交审批|直接提交|提交这个单据|提交这个申请|提交这个申请单|提交这张单据|提交这张申请单|提交当前单据|提交当前申请|提交上面的单据|提交刚才保存的草稿|提交刚才的草稿|把这个单据提交|把这个申请单提交|提交到领导审批|提交给领导审核)$/.test(normalized)) {
    return AI_APPLICATION_ACTION_SUBMIT
  }
  return ''
}

export function resolveLatestApplicationPreviewMessage(messages = []) {
  return [...(Array.isArray(messages) ? messages : [])]
    .reverse()
    .find((message) => message?.role === 'assistant' && message.applicationPreview) || null
}

export function isOrphanInlineApplicationPreviewMessage(message = {}) {
  if (message?.applicationPreview || message?.role !== 'assistant') {
    return false
  }
  return /下方表格|申请核对表|点击对应行即可直接编辑/.test(String(message.content || message.text || ''))
}

export function resolveLatestOrphanApplicationPreviewMessage(messages = []) {
  return [...(Array.isArray(messages) ? messages : [])]
    .reverse()
    .find((message) => isOrphanInlineApplicationPreviewMessage(message)) || null
}
