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

const STATUS_FILTERS = [
  { label: '草稿', keys: ['draft'], pattern: /草稿|未提交/ },
  { label: '审批中', keys: ['submitted', 'pending'], pattern: /审批中|审核中|待审批|待审核|待审|已提交/ },
  { label: '已审批', keys: ['approved'], pattern: /已审批|审批通过|已通过|已批准/ },
  { label: '已完成', keys: ['completed'], pattern: /已完成|完成/ },
  { label: '已归档', keys: ['archived'], pattern: /已归档|归档/ },
  { label: '已退回', keys: ['returned'], pattern: /已退回|退回|待补充/ },
  { label: '已驳回', keys: ['rejected'], pattern: /已驳回|驳回|拒绝/ },
  { label: '待付款', keys: ['pending_payment'], pattern: /待付款|待支付/ },
  { label: '已付款', keys: ['paid'], pattern: /已付款|已支付/ }
]

const EXPENSE_TYPE_FILTERS = [
  { label: '差旅费', codes: ['travel', 'travel_application'], pattern: /差旅|出差|差旅费|差旅费用/ },
  { label: '交通费', codes: ['transport'], pattern: /交通|火车|机票|打车|出租|网约车/ },
  { label: '住宿费', codes: ['hotel'], pattern: /住宿|酒店|宾馆/ },
  { label: '业务招待费', codes: ['meal', 'entertainment'], pattern: /招待|餐饮|宴请|客户餐/ },
  { label: '办公用品费', codes: ['office'], pattern: /办公|办公用品|采购/ },
  { label: '会务费', codes: ['meeting'], pattern: /会务|会议/ },
  { label: '培训费', codes: ['training'], pattern: /培训/ },
  { label: '软件服务费', codes: ['software'], pattern: /软件|服务费|订阅/ }
]

const RISK_FILTERS = [
  { label: '无风险', level: 'none', pattern: /无风险|没有风险|暂无风险|无异常|合规/ },
  { label: '高风险', level: 'high', pattern: /高风险/ },
  { label: '中风险', level: 'medium', pattern: /中风险/ },
  { label: '低风险', level: 'low', pattern: /低风险/ },
  { label: '有风险', level: 'has', pattern: /风险|异常|超标/ }
]

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

function lastDayOfMonth(year, month) {
  return new Date(Date.UTC(year, month, 0)).getUTCDate()
}

function buildMonthRange(year, month) {
  const normalizedMonth = String(month).padStart(2, '0')
  return {
    start: `${year}-${normalizedMonth}-01`,
    end: `${year}-${normalizedMonth}-${String(lastDayOfMonth(year, month)).padStart(2, '0')}`,
    label: `${year}年${month}月`
  }
}

function resolveTimeRange(prompt, options = {}) {
  const text = compactText(prompt)
  const today = resolveToday(options)
  const todayText = formatDate(today)

  const explicitMonth = text.match(/(?:(?<year>20\d{2})年?)?(?<month>\d{1,2})月(?!\d{1,2})/)
  if (explicitMonth?.groups) {
    const year = Number(explicitMonth.groups.year || today.getUTCFullYear())
    const month = Number(explicitMonth.groups.month)
    if (month >= 1 && month <= 12) {
      return buildMonthRange(year, month)
    }
  }

  const explicitRange = text.match(/(?:(?<year>20\d{2})年?)?(?<startMonth>\d{1,2})月(?<startDay>\d{1,2})日?(?:至|到|~|-|—|–)(?:(?<endMonth>\d{1,2})月)?(?<endDay>\d{1,2})日?/)
  if (explicitRange?.groups) {
    const year = Number(explicitRange.groups.year || today.getUTCFullYear())
    const startMonth = Number(explicitRange.groups.startMonth)
    const endMonth = Number(explicitRange.groups.endMonth || startMonth)
    const start = `${year}-${String(startMonth).padStart(2, '0')}-${String(explicitRange.groups.startDay).padStart(2, '0')}`
    const end = `${year}-${String(endMonth).padStart(2, '0')}-${String(explicitRange.groups.endDay).padStart(2, '0')}`
    return { start, end, label: `${start} 至 ${end}` }
  }

  const explicitDay = text.match(/(?:(?<year>20\d{2})年?)?(?<month>\d{1,2})月(?<day>\d{1,2})日?/)
  if (explicitDay?.groups) {
    const year = Number(explicitDay.groups.year || today.getUTCFullYear())
    const value = `${year}-${String(explicitDay.groups.month).padStart(2, '0')}-${String(explicitDay.groups.day).padStart(2, '0')}`
    return { start: value, end: value, label: value }
  }

  if (/今天|今日/.test(text)) {
    return { start: todayText, end: todayText, label: '今天' }
  }

  if (/昨天/.test(text)) {
    const date = new Date(today.getTime())
    date.setUTCDate(date.getUTCDate() - 1)
    const value = formatDate(date)
    return { start: value, end: value, label: '昨天' }
  }

  const daysAgo = text.match(/(?<days>\d{1,3})天前/)
  if (daysAgo?.groups?.days) {
    const days = Math.max(0, Number(daysAgo.groups.days))
    const date = new Date(today.getTime())
    date.setUTCDate(date.getUTCDate() - days)
    const value = formatDate(date)
    return { start: value, end: value, label: `${days}天前` }
  }

  if (/本月|这个月|当月/.test(text)) {
    return buildMonthRange(today.getUTCFullYear(), today.getUTCMonth() + 1)
  }

  if (/上月|上个月/.test(text)) {
    const date = new Date(today.getTime())
    date.setUTCMonth(date.getUTCMonth() - 1)
    return buildMonthRange(date.getUTCFullYear(), date.getUTCMonth() + 1)
  }

  if (/今年|本年/.test(text)) {
    const year = today.getUTCFullYear()
    return { start: `${year}-01-01`, end: `${year}-12-31`, label: `${year}年` }
  }

  const recent = text.match(/近(?<days>\d{1,3})天/)
  if (recent?.groups?.days) {
    const days = Math.max(1, Number(recent.groups.days))
    const start = new Date(today.getTime())
    start.setUTCDate(start.getUTCDate() - days + 1)
    return { start: formatDate(start), end: todayText, label: `近${days}天` }
  }

  return null
}

function resolveDocumentType(prompt) {
  const text = compactText(prompt)
  if (/申请单|申请类单据|申请类/.test(text)) {
    return 'application'
  }
  if (/报销单|报销类单据|报销类/.test(text)) {
    return 'reimbursement'
  }
  return 'all'
}

function resolveStatusFilter(prompt) {
  const text = compactText(prompt)
  return STATUS_FILTERS.find((item) => item.pattern.test(text)) || null
}

function resolveExpenseTypeFilter(prompt) {
  const text = compactText(prompt)
  return EXPENSE_TYPE_FILTERS.find((item) => item.pattern.test(text)) || null
}

function resolveRiskFilter(prompt) {
  const text = compactText(prompt)
  return RISK_FILTERS.find((item) => item.pattern.test(text)) || null
}

function normalizeAmountText(value = '') {
  const matched = compactText(value).replace(/,/g, '').match(/-?\d+(?:\.\d+)?/)
  if (!matched) {
    return null
  }
  const amount = Number(matched[0])
  return Number.isFinite(amount) ? amount : null
}

function resolveAmountFilter(prompt) {
  const text = compactText(prompt)
  const range = text.match(/金额(?:在|为)?(?<min>\d+(?:\.\d+)?)(?:元)?(?:到|至|~|-|—|–)(?<max>\d+(?:\.\d+)?)(?:元)?/)
  if (range?.groups) {
    const min = normalizeAmountText(range.groups.min)
    const max = normalizeAmountText(range.groups.max)
    if (min !== null && max !== null) {
      return {
        min: Math.min(min, max),
        max: Math.max(min, max),
        label: `${Math.min(min, max)}-${Math.max(min, max)}元`
      }
    }
  }

  const minMatch = text.match(/(?:金额)?(?:大于|超过|高于|不少于|不低于|>=|以上)(?<amount>\d+(?:\.\d+)?)(?:元)?/)
    || text.match(/(?<amount>\d+(?:\.\d+)?)(?:元)?以上/)
  if (minMatch?.groups?.amount) {
    const min = normalizeAmountText(minMatch.groups.amount)
    return min === null ? null : { min, max: null, label: `不少于${min}元` }
  }

  const maxMatch = text.match(/(?:金额)?(?:小于|低于|少于|不超过|<=|以下)(?<amount>\d+(?:\.\d+)?)(?:元)?/)
    || text.match(/(?<amount>\d+(?:\.\d+)?)(?:元)?以下/)
  if (maxMatch?.groups?.amount) {
    const max = normalizeAmountText(maxMatch.groups.amount)
    return max === null ? null : { min: null, max, label: `不超过${max}元` }
  }
  return null
}

function normalizeKeywordCandidate(value = '') {
  return normalizeText(value)
    .replace(/^(的|是|为|包含|含有)+/u, '')
    .replace(/(相关的?|有关的?|单据|单子|申请单|报销单|审核单|审批单|有哪些|有吗|查询|查看)$/u, '')
    .replace(/的$/u, '')
    .trim()
}

function resolveKeywordFilter(prompt) {
  const text = normalizeText(prompt)
  const compact = compactText(prompt)
  const explicitMatch = text.match(/(?:关于|有关|包含|含有|关键词|关键字|事由(?:是|为|包含|含有)?)[：:\s]*(?<keyword>[\u4e00-\u9fa5A-Za-z0-9_-]{2,32})/u)
  const relatedMatch = compact.match(/(?<keyword>[\u4e00-\u9fa5A-Za-z0-9_-]{2,32})相关(?:的)?(?:单据|单子|申请单|报销单|审核单|审批单)/u)
  const keyword = normalizeKeywordCandidate(explicitMatch?.groups?.keyword || relatedMatch?.groups?.keyword || '')
  if (!keyword || /^(现在|当前|哪些|审核|审批|申请|报销|单据|单子)$/u.test(keyword)) {
    return null
  }
  return { keyword, label: keyword }
}

function resolveSource(prompt) {
  const text = compactText(prompt)
  if (/审核单|审批单|待办|待审|待审核|待审批|我审批|我审核|我要审批|我要审核|去审批|去审核|处理审批|处理审核/.test(text)) {
    return {
      source: 'approval',
      sourceLabel: '待我审核的单据'
    }
  }
  if (/我名下|我发起|我提交|我创建|我的/.test(text)) {
    return {
      source: 'mine',
      sourceLabel: '我的单据'
    }
  }
  return {
    source: 'accessible',
    sourceLabel: '我可见的单据'
  }
}

export function resolveAiDocumentQueryIntent(prompt, options = {}) {
  const text = compactText(prompt)
  if (!text || !/(单据|单子|申请单|报销单|审核单|审批单|待办|待审|待审批|待审核|我要审核|我要审批|去审核|去审批|处理审核|处理审批|草稿)/.test(text)) {
    return null
  }
  if (
    /(标准|制度|规则|政策|口径|怎么|如何|能不能|可以吗)/.test(text) &&
    !/(单据|单子|申请单|报销单|审核单|审批单|待办|待审|待审批|待审核)/.test(text)
  ) {
    return null
  }
  if (/(发起|创建|新增|填写|生成|申请出差|我要报销|提交).*(单据|申请单|报销单)?/.test(text)) {
    return null
  }
  const source = resolveSource(text)
  const documentType = resolveDocumentType(text)
  const statusFilter = resolveStatusFilter(text)
  const expenseTypeFilter = resolveExpenseTypeFilter(text)
  const keywordFilter = resolveKeywordFilter(prompt)
  const amountFilter = resolveAmountFilter(text)
  const riskFilter = resolveRiskFilter(text)
  return {
    ...source,
    documentType,
    documentTypeLabel: documentType === 'application'
      ? '申请单'
      : documentType === 'reimbursement'
        ? '报销单'
        : '全部单据',
    timeRange: resolveTimeRange(text, options),
    statusFilter,
    expenseTypeFilter,
    keywordFilter,
    amountFilter,
    riskFilter
  }
}
