import {
  getAgentProduct,
  getCourseProduct,
  getDataProduct,
  getEventProduct,
  getExpert,
  getAccountAiPermissions,
  getAccountMembership,
  listAccountConsultingRequests,
  listAccountCourseRegistrations,
  listAccountDataServiceRequests,
  listAccountEventRegistrations,
  listAccountExpertBookings,
  listAccountInvoiceApplications,
  listAccountNotifications,
  listAccountOrders,
  listAccountTasks,
  recordAiAssistAudit,
  listAgentCatalog,
  listCourseCatalog,
  listDataCatalog,
  listEventCatalog,
  listExperts,
  requireUser,
} from '../business-pg.mjs'

const consultingService = {
  id: 'consulting-digital-plan',
  slug: 'consulting-digital-plan',
  type: 'consulting',
  title: '规划咨询服务',
  summary: '提交数字化规划、数据治理、产业服务或专项咨询需求，顾问会根据场景评估并跟进方案。',
  category: '规划咨询',
  priceAmount: 0,
  tags: ['需求评估', '方案规划'],
}

const sourceLabels = {
  consulting: '规划咨询',
  course: '课程学习',
  event: '活动报名',
  data: '数据服务',
  agent: '智能体服务',
  expert: '专家预约',
}

const leadRequiredFields = {
  consulting: ['company', 'contactName', 'contactPhone', 'direction', 'currentSituation', 'requirement'],
  data_service: ['company', 'contactName', 'contactPhone', 'dataTopic', 'serviceType', 'requirement', 'expectedResult'],
}

const accountIntentSet = new Set(['getAccountSummary', 'getAccountProgress', 'getTodoItems'])

const accountDomainScopes = {
  overview: 'account_overview',
  orders: 'account_orders',
  membership: 'account_membership',
  services: 'account_services',
  learning: 'account_learning',
  expertBookings: 'account_expert_bookings',
  invoices: 'account_invoices',
  notifications: 'account_notifications',
}

const accountDomainLabels = {
  overview: '我的概览',
  orders: '我的订单',
  membership: '会员权益',
  services: '服务进度',
  learning: '课程活动',
  expertBookings: '专家预约',
  invoices: '发票状态',
  notifications: '通知摘要',
}

const riskyIntentRules = [
  { code: 'payment_blocked', label: '支付', pattern: /(支付|付款|继续支付|微信支付|requestPayment)/i },
  { code: 'order_blocked', label: '下单', pattern: /(下单|创建订单|直接购买|帮我买|加入购物车)/i },
  { code: 'checkin_blocked', label: '核销', pattern: /(核销|签到|验票|checkin|扫码核验)/i },
  { code: 'auth_blocked', label: '登录确认', pattern: /(验证码|短信码|电脑登录|pc登录|确认登录|扫码登录)/i },
  { code: 'account_blocked', label: '账号资料变更', pattern: /(注销|关闭账号|删除账号|修改手机号|改密码)/i },
  { code: 'invoice_blocked', label: '发票', pattern: /(发票|开票|税号)/i },
  { code: 'settlement_blocked', label: '专家结算', pattern: /(提现|结算|确认完成|发起争议|退款)/i },
]

function textOf(value) {
  if (value === null || value === undefined) return ''
  if (typeof value === 'string') return value
  if (typeof value === 'number' || typeof value === 'boolean') return String(value)
  if (Array.isArray(value)) return value.map(textOf).join(' ')
  if (typeof value === 'object') return Object.values(value).map(textOf).join(' ')
  return ''
}

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

function itemsOf(result) {
  if (Array.isArray(result)) return result
  if (Array.isArray(result?.items)) return result.items
  return []
}

function compactObject(value) {
  return Object.fromEntries(Object.entries(value).filter(([, item]) => item !== undefined && item !== null && item !== ''))
}

function yuan(amount) {
  const cents = Number(amount || 0)
  if (!Number.isFinite(cents) || cents <= 0) return ''
  return `¥${Math.round(cents / 100).toLocaleString('zh-CN')}`
}

function shortDate(value) {
  if (!value) return ''
  const date = new Date(value)
  if (Number.isNaN(date.getTime())) return ''
  return `${date.getMonth() + 1}月${date.getDate()}日`
}

function shortDateTime(value) {
  if (!value) return ''
  const date = new Date(value)
  if (Number.isNaN(date.getTime())) return ''
  return `${date.getMonth() + 1}月${date.getDate()}日 ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
}

function orderStatusLabel(status = '') {
  if (status === 'pending_payment') return '待支付'
  if (status === 'paid') return '已支付'
  if (status === 'completed') return '已完成'
  if (status === 'closed') return '已关闭'
  return status || '订单'
}

function consultingStatusLabel(status = '') {
  if (status === 'proposal_ready') return '报价待确认'
  if (status === 'pending_payment') return '待支付'
  if (status === 'in_service') return '服务中'
  if (status === 'completed') return '已完成'
  if (status === 'cancelled') return '已取消'
  if (status === 'communicating') return '沟通中'
  if (status === 'planning') return '方案中'
  if (status === 'assigned') return '已接单'
  return '待受理'
}

function dataStatusLabel(status = '') {
  if (status === 'quoted') return '报价待确认'
  if (status === 'pending_payment') return '待支付'
  if (status === 'in_service') return '服务中'
  if (status === 'completed') return '已完成'
  if (status === 'cancelled') return '已取消'
  if (status === 'contacting') return '沟通中'
  return '等待联系'
}

function taskStatusLabel(status = '') {
  if (status === 'completed') return '已完成'
  if (status === 'pending_confirm') return '待确认'
  if (status === 'in_progress') return '配置中'
  if (status === 'assigned') return '资料审核中'
  if (status === 'cancelled') return '已取消'
  return '待提交资料'
}

function bookingStatusLabel(status = '') {
  if (status === 'pending_payment') return '待支付'
  if (status === 'pending_expert') return '待专家确认'
  if (status === 'confirmed') return '预约中'
  if (status === 'pending_user_confirm') return '待确认完成'
  if (status === 'disputed') return '争议处理中'
  if (status === 'completed') return '已完成'
  if (status === 'rejected') return '已拒绝'
  return '已取消'
}

function registrationStatusLabel(status = '') {
  if (status === 'pending_payment') return '待支付'
  if (status === 'waitlisted') return '候补中'
  if (status === 'checked_in') return '已核销'
  if (status === 'registered') return '待参加'
  if (status === 'cancel_requested') return '取消处理中'
  if (status === 'cancelled') return '已取消'
  if (status === 'no_show') return '未到场'
  return '已关闭'
}

function invoiceStatusLabel(status = '') {
  if (status === 'pending') return '待处理'
  if (status === 'processing') return '开票中'
  if (status === 'issued') return '已开票'
  if (status === 'rejected') return '已驳回'
  if (status === 'failed') return '开票失败'
  return status || '发票'
}

function membershipLevelLabel(level = '') {
  if (level === 'senior') return '高级会员'
  if (level === 'junior') return '初级会员'
  return '注册用户'
}

function normalizeAccountDomain(value = '', intent = '') {
  const raw = clean(value || intent).toLowerCase()
  if (['order', 'orders', '订单'].includes(raw) || /订单|待支付|付款/.test(raw)) return 'orders'
  if (['member', 'membership', '会员', '权益'].includes(raw) || /会员|权益|到期/.test(raw)) return 'membership'
  if (['service', 'services', 'progress', '服务', '进度'].includes(raw) || /咨询|数据服务|智能体|进度|交付|报价/.test(raw)) return 'services'
  if (['learning', 'course', 'event', '课程', '活动'].includes(raw) || /课程|活动|报名|参加/.test(raw)) return 'learning'
  if (['expert', 'expertbooking', 'expertbookings', '专家', '预约'].includes(raw) || /专家|预约/.test(raw)) return 'expertBookings'
  if (['invoice', 'invoices', '发票', '开票'].includes(raw) || /发票|开票/.test(raw)) return 'invoices'
  if (['notification', 'notifications', 'notice', '通知', '消息'].includes(raw) || /通知|消息|未读/.test(raw)) return 'notifications'
  return 'overview'
}

function accountCard({
  sourceType,
  sourceLabel,
  id,
  title,
  summary,
  statusLabel,
  meta,
  amountLabel,
  timeLabel,
  nextStep,
  url,
}) {
  return compactObject({
    type: 'account',
    sourceType,
    sourceLabel,
    id,
    title,
    summary,
    statusLabel,
    meta,
    amountLabel,
    timeLabel,
    nextStep,
    action: url ? { type: 'navigate', label: '打开查看', url } : undefined,
  })
}

function orderCard(order = {}) {
  const firstTitle = order.items?.[0]?.titleSnapshot || '订单'
  return accountCard({
    sourceType: 'order',
    sourceLabel: '订单',
    id: order.orderNo || order.id,
    title: `${firstTitle}${order.items?.length > 1 ? ` 等 ${order.items.length} 项` : ''}`,
    summary: order.orderNo ? `订单 ${order.orderNo}` : '订单记录',
    statusLabel: orderStatusLabel(order.status),
    amountLabel: yuan(order.totalAmount || order.paidAmount),
    timeLabel: shortDateTime(order.createdAt),
    nextStep: order.status === 'pending_payment' ? '请手动打开订单页完成支付。' : '可打开订单页查看明细。',
    url: order.orderNo ? `/pages/account/orders/detail/index?id=${encodeURIComponent(order.orderNo)}` : '/pages/account/orders/index',
  })
}

function consultingCard(item = {}) {
  return accountCard({
    sourceType: 'consulting',
    sourceLabel: '规划咨询',
    id: item.requestNo || item.id,
    title: item.direction || item.company || '规划咨询',
    summary: item.requestNo ? `咨询单 ${item.requestNo}` : '咨询需求',
    statusLabel: consultingStatusLabel(item.status),
    amountLabel: yuan(item.quotedAmount),
    timeLabel: shortDateTime(item.updatedAt || item.createdAt),
    nextStep: ['proposal_ready', 'pending_payment'].includes(item.status) ? '请手动打开咨询详情确认报价或付款。' : '可打开页面查看沟通进度。',
    url: item.id ? `/pages/account/consulting/detail/index?id=${encodeURIComponent(item.id)}` : '/pages/account/consulting/index',
  })
}

function dataRequestCard(item = {}) {
  return accountCard({
    sourceType: 'data_service',
    sourceLabel: '数据服务',
    id: item.requestNo || item.id,
    title: item.dataTopic || item.quotedTitle || '数据服务申请',
    summary: item.requestNo ? `需求单 ${item.requestNo}` : '数据服务需求',
    statusLabel: dataStatusLabel(item.status),
    amountLabel: yuan(item.quotedAmount),
    timeLabel: shortDateTime(item.updatedAt || item.createdAt),
    nextStep: ['quoted', 'pending_payment'].includes(item.status) ? '请手动打开数据服务详情确认报价或付款。' : '可打开页面查看服务进度。',
    url: item.id ? `/pages/account/reports/detail/index?id=${encodeURIComponent(item.id)}` : '/pages/account/reports/index',
  })
}

function taskCard(item = {}) {
  return accountCard({
    sourceType: 'agent_task',
    sourceLabel: '智能体交付',
    id: item.taskNo || item.id,
    title: item.productTitle || item.title || '智能体交付',
    summary: item.taskNo ? `任务 ${item.taskNo}` : '交付任务',
    statusLabel: taskStatusLabel(item.status),
    timeLabel: shortDateTime(item.updatedAt || item.createdAt),
    nextStep: item.status === 'pending_material' ? '请手动打开任务页补充材料。' : '可打开页面查看交付进度。',
    url: item.taskNo || item.id ? `/pages/account/agents/detail/index?id=${encodeURIComponent(item.taskNo || item.id)}` : '/pages/account/agents/index',
  })
}

function courseCard(item = {}) {
  const course = item.course || {}
  return accountCard({
    sourceType: 'course_registration',
    sourceLabel: '课程',
    id: item.registrationNo || item.id,
    title: course.title || '课程报名',
    summary: item.registrationNo ? `报名 ${item.registrationNo}` : '课程报名',
    statusLabel: registrationStatusLabel(item.status),
    meta: course.location || course.courseFormat || '',
    timeLabel: shortDateTime(course.startsAt),
    nextStep: item.status === 'pending_payment' ? '请手动打开课程详情处理待支付。' : '可打开页面查看课程安排。',
    url: item.id ? `/pages/account/courses/detail/index?id=${encodeURIComponent(item.id)}` : '/pages/account/courses/index',
  })
}

function eventCard(item = {}) {
  const event = item.event || {}
  return accountCard({
    sourceType: 'event_registration',
    sourceLabel: '活动',
    id: item.registrationNo || item.id,
    title: event.title || '活动报名',
    summary: item.registrationNo ? `报名 ${item.registrationNo}` : '活动报名',
    statusLabel: registrationStatusLabel(item.status),
    meta: event.location || event.eventFormat || '',
    timeLabel: shortDateTime(event.startsAt),
    nextStep: item.status === 'pending_payment' ? '请手动打开活动详情处理待支付。' : '可打开页面查看活动安排。',
    url: item.id ? `/pages/account/events/detail/index?id=${encodeURIComponent(item.id)}` : '/pages/account/events/index',
  })
}

function expertBookingCard(item = {}) {
  return accountCard({
    sourceType: 'expert_booking',
    sourceLabel: '专家预约',
    id: item.bookingNo || item.id,
    title: `${item.expert?.name || '专家'}咨询`,
    summary: item.bookingNo ? `预约 ${item.bookingNo}` : '专家预约',
    statusLabel: bookingStatusLabel(item.status),
    timeLabel: shortDateTime(item.startsAt),
    nextStep: item.status === 'pending_user_confirm' ? '请手动打开预约页确认或处理异议。' : '可打开页面查看预约状态。',
    url: item.id ? `/pages/account/expert-bookings/detail/index?id=${encodeURIComponent(item.id)}` : '/pages/account/expert-bookings/index',
  })
}

function invoiceCard(item = {}) {
  return accountCard({
    sourceType: 'invoice',
    sourceLabel: '发票',
    id: item.invoiceNo || item.id,
    title: item.invoiceNo ? `发票 ${item.invoiceNo}` : '发票申请',
    summary: item.orderNo ? `关联订单 ${item.orderNo}` : '发票状态',
    statusLabel: invoiceStatusLabel(item.status),
    amountLabel: yuan(item.amount),
    timeLabel: shortDateTime(item.updatedAt || item.createdAt),
    nextStep: '可打开发票页查看处理进度，文件下载需你手动操作。',
    url: '/pages/account/invoices/index',
  })
}

function notificationCard(item = {}) {
  return accountCard({
    sourceType: 'notification',
    sourceLabel: '通知',
    id: item.id,
    title: item.title || '站内通知',
    summary: item.body || '',
    statusLabel: item.readAt ? '已读' : '未读',
    timeLabel: shortDateTime(item.createdAt || item.scheduledAt),
    nextStep: '可打开我的页面查看通知，不会自动标记已读。',
    url: '/pages/account/index',
  })
}

function membershipCard(membership = {}) {
  const level = membership.level || membership.membership?.level || 'registered'
  const daysLeft = membership.daysLeft
  const expiresAt = membership.expiresAt
  return accountCard({
    sourceType: 'membership',
    sourceLabel: '会员',
    id: membership.subscription?.id || level,
    title: membershipLevelLabel(level),
    summary: membership.status === 'active'
      ? (expiresAt ? `有效至 ${shortDate(expiresAt)}` : '会员有效')
      : membership.status === 'expiring'
        ? `即将到期${daysLeft !== null && daysLeft !== undefined ? `，剩余 ${daysLeft} 天` : ''}`
        : membership.status === 'expired'
          ? '会员已到期'
          : '暂未开通会员',
    statusLabel: membership.status === 'active' ? '有效' : membership.status === 'expiring' ? '即将到期' : membership.status === 'expired' ? '已到期' : '未开通',
    meta: Array.isArray(membership.quotas) && membership.quotas.length ? `权益额度 ${membership.quotas.length} 项` : '',
    timeLabel: expiresAt ? shortDate(expiresAt) : '',
    nextStep: membership.canRenew || membership.canUpgrade ? '可手动打开会员页查看续费或升级方案。' : '可打开会员页查看权益明细。',
    url: '/pages/account/membership/index',
  })
}

function activeServiceItem(item = {}) {
  return !['completed', 'cancelled'].includes(item.status)
}

function activeExpertBooking(item = {}) {
  return ['pending_payment', 'pending_expert', 'confirmed', 'pending_user_confirm', 'disputed'].includes(item.status)
}

function pendingRegistration(item = {}) {
  return ['pending_payment', 'registered', 'waitlisted'].includes(item.status)
}

function cardsReply(domain, cards = [], extra = '') {
  if (!cards.length) return `${accountDomainLabels[domain] || '账户信息'}暂无需要提醒的记录。${extra}`.trim()
  return `已读取${accountDomainLabels[domain] || '账户信息'}摘要，只展示脱敏状态；具体处理需要你手动打开页面确认。${extra}`.trim()
}

export function detectWechatAiRisk(payload = {}) {
  const text = textOf([payload.intent, payload.message, payload.keyword, payload.scenario, payload.action, payload.payload])
  return riskyIntentRules.find((rule) => rule.pattern.test(text)) || null
}

export function normalizeWechatAiLeadType(value = '') {
  const raw = clean(value).toLowerCase()
  if (['data', 'data_service', 'data-service', '数据', '数据服务'].includes(raw)) return 'data_service'
  if (['consulting', 'consult', '规划咨询', '咨询'].includes(raw)) return 'consulting'
  return raw.includes('data') ? 'data_service' : 'consulting'
}

function userDraftDefaults(user = {}) {
  return compactObject({
    company: user.organization,
    contactName: user.displayName || user.name,
    contactPhone: user.contactPhone || user.phone,
    email: user.email,
    city: user.city,
    industry: user.industry,
  })
}

export function buildWechatAiLeadDraft(input = {}, user = null) {
  const leadType = normalizeWechatAiLeadType(input.leadType || input.type || input.sourceType)
  const payload = {
    ...userDraftDefaults(user || {}),
    ...(input.payload || {}),
  }

  if (leadType === 'data_service') {
    payload.dataTopic = clean(payload.dataTopic || input.dataTopic || input.title || input.serviceTitle || input.keyword)
    payload.serviceType = clean(payload.serviceType || input.serviceType || input.category || '数据定制')
    payload.requirement = clean(payload.requirement || input.requirement || input.message)
    payload.expectedResult = clean(payload.expectedResult || input.expectedResult)
    payload.organizationType = clean(payload.organizationType || '其他组织')
  } else {
    payload.direction = clean(payload.direction || input.direction || input.title || input.serviceTitle)
    payload.currentSituation = clean(payload.currentSituation || input.currentSituation)
    payload.requirement = clean(payload.requirement || input.requirement || input.message)
    payload.organizationType = clean(payload.organizationType || '其他组织')
    payload.expectedStart = clean(payload.expectedStart || '仅先咨询评估')
  }

  const required = leadRequiredFields[leadType] || leadRequiredFields.consulting
  const missingFields = required.filter((field) => !clean(payload[field]))
  const submitEndpoint = leadType === 'data_service' ? '/api/data-service-requests' : '/api/consulting-requests'
  const pagePath = leadType === 'data_service' ? '/pages/data-service/apply/index' : '/pages/consulting/apply/index'

  return {
    type: leadType,
    payload: compactObject(payload),
    missingFields,
    submitEndpoint,
    pagePath,
  }
}

function priceLabel(item = {}) {
  const amount = Number(item.priceAmount ?? item.registeredPriceAmount ?? item.monthlyPriceAmount ?? 0)
  if (!Number.isFinite(amount) || amount <= 0) return item.status || '提交需求'
  return `¥${Math.round(amount / 100).toLocaleString('zh-CN')}`
}

function serviceUrl(sourceType, item = {}) {
  if (sourceType === 'consulting') return '/pages/consulting/index'
  if (sourceType === 'expert') return `/pages/services/detail/index?id=expert-${encodeURIComponent(item.slug || item.id || '')}`
  const id = item.id || item.productId || item.slug || ''
  return `/pages/services/detail/index?id=${encodeURIComponent(id)}`
}

function cardFromService(sourceType, item = {}) {
  const id = item.id || item.productId || item.slug || ''
  const title = item.title || item.name || ''
  const summary = item.summary || item.description || item.detailDescription || item.title || ''
  const tags = Array.isArray(item.tags) ? item.tags : Array.isArray(item.scenarioTags) ? item.scenarioTags : Array.isArray(item.directions) ? item.directions : []
  return compactObject({
    type: 'service',
    sourceType,
    sourceLabel: sourceLabels[sourceType] || sourceType,
    id,
    slug: item.slug,
    title,
    summary,
    category: item.category || item.direction || item.title,
    priceLabel: priceLabel(item),
    tags: tags.slice(0, 4),
    action: {
      type: 'navigate',
      label: sourceType === 'consulting' ? '提交咨询需求' : '查看详情',
      url: serviceUrl(sourceType, item),
    },
  })
}

function serviceSearchText(card = {}) {
  return textOf([card.title, card.summary, card.category, card.sourceLabel, card.tags]).toLowerCase()
}

export function filterWechatAiCards(cards = [], keyword = '') {
  const normalized = clean(keyword).toLowerCase()
  if (!normalized) return cards
  return cards.filter((card) => serviceSearchText(card).includes(normalized))
}

function scenarioTypes(payload = {}) {
  const raw = clean([payload.scenario, payload.serviceType, payload.sourceType, payload.leadType, payload.keyword, payload.message].map(textOf).join(' ')).toLowerCase()
  if (/数据|data/.test(raw)) return ['data', 'consulting']
  if (/智能体|agent/.test(raw)) return ['agent', 'consulting']
  if (/专家|expert|预约/.test(raw)) return ['expert', 'consulting']
  if (/课程|培训|学习|course/.test(raw)) return ['course']
  if (/活动|报名|会议|event/.test(raw)) return ['event']
  if (/咨询|规划|方案|consult/.test(raw)) return ['consulting', 'expert']
  return ['consulting', 'data', 'agent', 'expert', 'course', 'event']
}

async function loadCatalogCards(providers, payload = {}) {
  const [courses, events, data, agents, experts] = await Promise.all([
    providers.listCourseCatalog(),
    providers.listEventCatalog(),
    providers.listDataCatalog(),
    providers.listAgentCatalog(),
    providers.listExperts({ available: true }),
  ])
  const cards = [
    cardFromService('consulting', consultingService),
    ...itemsOf(data).map((item) => cardFromService('data', item)),
    ...itemsOf(agents).map((item) => cardFromService('agent', item)),
    ...itemsOf(experts).map((item) => cardFromService('expert', item)),
    ...itemsOf(courses).map((item) => cardFromService('course', item)),
    ...itemsOf(events).map((item) => cardFromService('event', item)),
  ]
  const allowed = new Set(scenarioTypes(payload))
  return cards.filter((card) => allowed.has(card.sourceType))
}

async function loadDetailCard(providers, payload = {}) {
  const sourceType = clean(payload.sourceType || payload.type)
  const id = clean(payload.id || payload.productId || payload.slug)
  if (!sourceType || !id) return null
  if (sourceType === 'consulting') return cardFromService('consulting', consultingService)
  const loaders = {
    course: providers.getCourseProduct,
    event: providers.getEventProduct,
    data: providers.getDataProduct,
    agent: providers.getAgentProduct,
    expert: providers.getExpert,
  }
  const loader = loaders[sourceType]
  if (!loader) return null
  const item = await loader(id)
  return item ? cardFromService(sourceType, item) : null
}

async function optionalUser(token, providers) {
  if (!clean(token)) return { user: null, authStatus: 'anonymous' }
  try {
    const { user } = await providers.requireUser(token)
    return { user, authStatus: 'authenticated' }
  } catch (error) {
    if (error?.statusCode === 401) return { user: null, authStatus: 'invalid' }
    throw error
  }
}

async function recordAuditSafe(providers, payload) {
  try {
    await providers.recordAiAssistAudit?.(payload)
  } catch {
    // AI answers should not fail just because audit logging is temporarily unavailable.
  }
}

function aiAccessAllowed(accessLevel, required = 'read') {
  if (required === 'operate') return accessLevel === 'operate'
  return accessLevel === 'read' || accessLevel === 'operate'
}

async function resolveAiPermission(providers, token, user, scopeCode, required = 'read') {
  if (!user) {
    return {
      allowed: false,
      code: 'auth_required',
      permission: { scopeCode, accessLevel: 'denied' },
    }
  }
  const permissions = await providers.getAccountAiPermissions(token)
  const item = (permissions.items || []).find((permission) => permission.scopeCode === scopeCode) || { scopeCode, accessLevel: 'denied' }
  return {
    allowed: aiAccessAllowed(item.accessLevel, required),
    code: aiAccessAllowed(item.accessLevel, required) ? 'allowed' : 'ai_permission_denied',
    permission: item,
  }
}

function permissionDeniedResponse({ authStatus, scopeCode, domain, code = 'ai_permission_denied', permission, intent = 'getAccountSummary' }) {
  const needsAuth = code === 'auth_required'
  const label = accountDomainLabels[domain] || permission?.label || '该能力'
  return {
    reply: needsAuth
      ? '需要你先登录后，我才能读取你的账户服务摘要。'
      : `你还没有授权 AI 使用${label}。可以在“我的-账号设置-AI 助手授权”里开启。`,
    requiresAuth: needsAuth,
    authStatus,
    cards: [],
    draft: null,
    actions: [{
      type: 'navigate',
      label: needsAuth ? '前往登录' : '打开 AI 助手授权',
      url: needsAuth ? '/pages/account/index' : '/pages/account/ai-settings/index',
    }],
    permission: permission || { scopeCode, accessLevel: 'denied' },
    intent,
  }
}

async function loadOrdersSummary(providers, token) {
  const orders = itemsOf(await providers.listAccountOrders(token))
  const pending = orders.filter((item) => item.status === 'pending_payment')
  const cards = (pending.length ? pending : orders).slice(0, 6).map(orderCard)
  return {
    cards,
    summary: {
      total: orders.length,
      pendingPayment: pending.length,
    },
    reply: cardsReply('orders', cards, pending.length ? `共有 ${pending.length} 个待支付订单。` : ''),
    actions: [{ type: 'navigate', label: '打开我的订单', url: '/pages/account/orders/index' }],
  }
}

async function loadMembershipSummary(providers, token) {
  const membership = await providers.getAccountMembership(token)
  const card = membershipCard(membership || {})
  return {
    cards: [card],
    summary: {
      level: membership?.level || 'registered',
      status: membership?.status || 'registered',
      daysLeft: membership?.daysLeft ?? null,
      quotas: Array.isArray(membership?.quotas) ? membership.quotas.length : 0,
    },
    reply: cardsReply('membership', [card]),
    actions: [{ type: 'navigate', label: '打开会员权益', url: '/pages/account/membership/index' }],
  }
}

async function loadServicesSummary(providers, token) {
  const [consultingResult, dataResult, taskResult] = await Promise.allSettled([
    providers.listAccountConsultingRequests(token),
    providers.listAccountDataServiceRequests(token),
    providers.listAccountTasks(token),
  ])
  const consulting = consultingResult.status === 'fulfilled' ? itemsOf(consultingResult.value) : []
  const data = dataResult.status === 'fulfilled' ? itemsOf(dataResult.value) : []
  const tasks = taskResult.status === 'fulfilled' ? itemsOf(taskResult.value) : []
  const activeConsulting = consulting.filter(activeServiceItem)
  const activeData = data.filter(activeServiceItem)
  const activeTasks = tasks.filter(activeServiceItem)
  const cards = [
    ...activeData.slice(0, 3).map(dataRequestCard),
    ...activeConsulting.slice(0, 3).map(consultingCard),
    ...activeTasks.slice(0, 3).map(taskCard),
  ].slice(0, 8)
  return {
    cards,
    summary: {
      consulting: consulting.length,
      data: data.length,
      tasks: tasks.length,
      active: activeConsulting.length + activeData.length + activeTasks.length,
    },
    reply: cardsReply('services', cards),
    actions: [
      { type: 'navigate', label: '打开数据服务', url: '/pages/account/reports/index' },
      { type: 'navigate', label: '打开我的咨询', url: '/pages/account/consulting/index' },
      { type: 'navigate', label: '打开我的智能体', url: '/pages/account/agents/index' },
    ],
  }
}

async function loadLearningSummary(providers, token) {
  const [courseResult, eventResult] = await Promise.allSettled([
    providers.listAccountCourseRegistrations(token),
    providers.listAccountEventRegistrations(token),
  ])
  const courses = courseResult.status === 'fulfilled' ? itemsOf(courseResult.value) : []
  const events = eventResult.status === 'fulfilled' ? itemsOf(eventResult.value) : []
  const pendingCourses = courses.filter(pendingRegistration)
  const pendingEvents = events.filter(pendingRegistration)
  const cards = [
    ...pendingCourses.slice(0, 4).map(courseCard),
    ...pendingEvents.slice(0, 4).map(eventCard),
  ].slice(0, 8)
  return {
    cards,
    summary: {
      courses: courses.length,
      events: events.length,
      pending: pendingCourses.length + pendingEvents.length,
    },
    reply: cardsReply('learning', cards),
    actions: [
      { type: 'navigate', label: '打开我的课程', url: '/pages/account/courses/index' },
      { type: 'navigate', label: '打开报名活动', url: '/pages/account/events/index' },
    ],
  }
}

async function loadExpertBookingSummary(providers, token) {
  const bookings = itemsOf(await providers.listAccountExpertBookings(token))
  const active = bookings.filter(activeExpertBooking)
  const cards = (active.length ? active : bookings).slice(0, 6).map(expertBookingCard)
  return {
    cards,
    summary: {
      total: bookings.length,
      active: active.length,
    },
    reply: cardsReply('expertBookings', cards),
    actions: [{ type: 'navigate', label: '打开专家预约', url: '/pages/account/expert-bookings/index' }],
  }
}

async function loadInvoiceSummary(providers, token) {
  const invoices = itemsOf(await providers.listAccountInvoiceApplications(token))
  const active = invoices.filter((item) => !['issued', 'rejected'].includes(item.status))
  const cards = (active.length ? active : invoices).slice(0, 6).map(invoiceCard)
  return {
    cards,
    summary: {
      total: invoices.length,
      active: active.length,
    },
    reply: cardsReply('invoices', cards),
    actions: [{ type: 'navigate', label: '打开我的发票', url: '/pages/account/invoices/index' }],
  }
}

async function loadNotificationSummary(providers, token) {
  const notifications = itemsOf(await providers.listAccountNotifications(token, { unreadOnly: true }))
  const cards = notifications.slice(0, 6).map(notificationCard)
  return {
    cards,
    summary: {
      unread: notifications.length,
    },
    reply: cardsReply('notifications', cards, notifications.length ? `有 ${notifications.length} 条未读通知。` : ''),
    actions: [{ type: 'navigate', label: '打开我的页面', url: '/pages/account/index' }],
  }
}

async function loadOverviewSummary(providers, token) {
  const [orders, membership, services, learning, experts, notifications] = await Promise.allSettled([
    loadOrdersSummary(providers, token),
    loadMembershipSummary(providers, token),
    loadServicesSummary(providers, token),
    loadLearningSummary(providers, token),
    loadExpertBookingSummary(providers, token),
    loadNotificationSummary(providers, token),
  ])
  const resultOf = (result) => result.status === 'fulfilled' ? result.value : { cards: [], summary: {} }
  const orderSummary = resultOf(orders)
  const membershipSummary = resultOf(membership)
  const serviceSummary = resultOf(services)
  const learningSummary = resultOf(learning)
  const expertSummary = resultOf(experts)
  const notificationSummary = resultOf(notifications)
  const cards = [
    ...orderSummary.cards.filter((card) => card.statusLabel === '待支付').slice(0, 2),
    ...serviceSummary.cards.slice(0, 3),
    ...expertSummary.cards.slice(0, 2),
    ...learningSummary.cards.slice(0, 2),
    ...notificationSummary.cards.slice(0, 1),
  ].slice(0, 8)
  return {
    cards,
    summary: {
      pendingOrders: orderSummary.summary.pendingPayment || 0,
      activeServices: serviceSummary.summary.active || 0,
      pendingLearning: learningSummary.summary.pending || 0,
      activeExpertBookings: expertSummary.summary.active || 0,
      unreadNotifications: notificationSummary.summary.unread || 0,
      membership: membershipSummary.summary,
    },
    reply: cards.length
      ? '这是你的账户待办摘要，已脱敏展示。支付、核销、确认完成等动作仍需要你手动打开页面处理。'
      : '你的账户暂时没有明显待办。账户数据已按授权范围脱敏读取。',
    actions: [{ type: 'navigate', label: '打开我的', url: '/pages/account/index' }],
  }
}

async function loadAccountSummary(providers, token, domain) {
  const loaders = {
    overview: loadOverviewSummary,
    orders: loadOrdersSummary,
    membership: loadMembershipSummary,
    services: loadServicesSummary,
    learning: loadLearningSummary,
    expertBookings: loadExpertBookingSummary,
    invoices: loadInvoiceSummary,
    notifications: loadNotificationSummary,
  }
  return (loaders[domain] || loaders.overview)(providers, token)
}

async function createAccountSummaryResponse(providers, payload, { token, user, authStatus, intent }) {
  const domain = intent === 'getTodoItems'
    ? 'overview'
    : normalizeAccountDomain(payload.domain || payload.scope || payload.category || payload.message, intent)
  const scopeCode = accountDomainScopes[domain] || accountDomainScopes.overview
  const permission = await resolveAiPermission(providers, token, user, scopeCode, 'read')
  if (!permission.allowed) {
    await recordAuditSafe(providers, {
      userId: user?.id,
      intent,
      requestedScope: scopeCode,
      decision: permission.code === 'auth_required' ? 'denied' : 'denied',
      actionType: 'account_summary',
      metadata: { domain, permission: permission.permission },
    })
    return permissionDeniedResponse({
      authStatus,
      scopeCode,
      domain,
      code: permission.code,
      permission: permission.permission,
      intent,
    })
  }
  const result = await loadAccountSummary(providers, token, domain)
  await recordAuditSafe(providers, {
    userId: user?.id,
    intent,
    requestedScope: scopeCode,
    decision: 'allowed',
    actionType: 'account_summary',
    metadata: { domain, cardCount: result.cards.length },
  })
  return {
    reply: result.reply,
    requiresAuth: false,
    authStatus,
    cards: result.cards,
    accountSummary: {
      domain,
      label: accountDomainLabels[domain] || '账户摘要',
      scopeCode,
      summary: result.summary,
    },
    draft: null,
    actions: result.actions,
    permission: permission.permission,
    intent,
  }
}

function blockedResponse(risk, payload = {}, cards = [], authStatus = 'anonymous') {
  return {
    reply: `我不能代你执行${risk.label}。可以先帮你查服务、整理草稿或打开需要你手动确认的页面。`,
    requiresAuth: false,
    authStatus,
    risk: { code: risk.code, label: risk.label },
    cards,
    draft: null,
    actions: cards.slice(0, 3).map((card) => ({
      type: 'navigate',
      label: card.action?.label || '查看详情',
      url: card.action?.url || '/pages/services/index',
    })),
    intent: clean(payload.intent || 'blocked'),
  }
}

const defaultProviders = {
  listAgentCatalog,
  listCourseCatalog,
  listDataCatalog,
  listEventCatalog,
  listExperts,
  getAgentProduct,
  getCourseProduct,
  getDataProduct,
  getEventProduct,
  getExpert,
  getAccountAiPermissions,
  getAccountMembership,
  listAccountConsultingRequests,
  listAccountCourseRegistrations,
  listAccountDataServiceRequests,
  listAccountEventRegistrations,
  listAccountExpertBookings,
  listAccountInvoiceApplications,
  listAccountNotifications,
  listAccountOrders,
  listAccountTasks,
  recordAiAssistAudit,
  requireUser,
}

export async function createWechatAiAssist(payload = {}, options = {}) {
  const providers = { ...defaultProviders, ...(options.providers || {}) }
  const token = clean(options.token || '')
  const { user, authStatus } = await optionalUser(token, providers)
  const risk = detectWechatAiRisk(payload)
  const intent = clean(payload.intent || payload.action || 'recommendServices')

  if (risk && risk.code !== 'order_blocked') {
    await recordAuditSafe(providers, {
      userId: user?.id,
      intent,
      requestedScope: 'high_risk',
      decision: 'blocked',
      riskCode: risk.code,
      actionType: 'risk_block',
      metadata: { label: risk.label },
    })
    return blockedResponse(risk, payload, [], authStatus)
  }

  if (accountIntentSet.has(intent)) {
    return createAccountSummaryResponse(providers, payload, { token, user, authStatus, intent })
  }

  if (intent === 'prepareLeadDraft') {
    if (user) {
      const permission = await resolveAiPermission(providers, token, user, 'lead_draft', 'operate')
      if (!permission.allowed) {
        await recordAuditSafe(providers, {
          userId: user.id,
          intent,
          requestedScope: 'lead_draft',
          decision: 'denied',
          actionType: 'lead_draft',
          metadata: { permission: permission.permission },
        })
        return permissionDeniedResponse({
          authStatus,
          scopeCode: 'lead_draft',
          domain: '',
          code: permission.code,
          permission: permission.permission,
          intent,
        })
      }
    }
    const draft = buildWechatAiLeadDraft(payload, user)
    await recordAuditSafe(providers, {
      userId: user?.id,
      intent,
      requestedScope: 'lead_draft',
      decision: 'allowed',
      actionType: 'lead_draft',
      metadata: { type: draft.type, missingFields: draft.missingFields },
    })
    return {
      reply: draft.missingFields.length
        ? '我已整理一份申请草稿，还需要你补充关键字段后再手动提交。'
        : '我已整理好申请草稿，请打开页面核对后手动提交。',
      requiresAuth: !user,
      authStatus,
      cards: [],
      draft,
      actions: [{
        type: 'open_confirm_page',
        label: draft.type === 'data_service' ? '打开数据服务申请' : '打开咨询申请',
        url: draft.pagePath,
      }],
      intent,
    }
  }

  if (user && ['recommendServices', 'searchServices', 'getServiceDetail'].includes(intent)) {
    const permission = await resolveAiPermission(providers, token, user, 'service_discovery', 'read')
    if (!permission.allowed) {
      await recordAuditSafe(providers, {
        userId: user.id,
        intent,
        requestedScope: 'service_discovery',
        decision: 'denied',
        actionType: 'service_discovery',
        metadata: { permission: permission.permission },
      })
      return permissionDeniedResponse({
        authStatus,
        scopeCode: 'service_discovery',
        domain: '',
        code: permission.code,
        permission: permission.permission,
        intent,
      })
    }
  }

  if (intent === 'getServiceDetail') {
    const card = await loadDetailCard(providers, payload)
    await recordAuditSafe(providers, {
      userId: user?.id,
      intent,
      requestedScope: 'service_discovery',
      decision: 'allowed',
      actionType: 'service_detail',
      metadata: { sourceType: payload.sourceType || payload.type, id: payload.id || payload.productId || payload.slug },
    })
    return {
      reply: card ? `这是${card.title}的服务详情，后续操作需要你手动确认。` : '没有找到对应服务，请换个关键词试试。',
      requiresAuth: false,
      authStatus,
      cards: card ? [card] : [],
      draft: null,
      actions: card ? [{ type: 'navigate', label: card.action.label, url: card.action.url }] : [],
      intent,
    }
  }

  const cards = filterWechatAiCards(await loadCatalogCards(providers, payload), payload.keyword || payload.message)
  const selected = cards.slice(0, Number(payload.limit || 6) || 6)
  if (risk?.code === 'order_blocked') {
    await recordAuditSafe(providers, {
      userId: user?.id,
      intent,
      requestedScope: 'high_risk',
      decision: 'blocked',
      riskCode: risk.code,
      actionType: 'risk_block',
      metadata: { label: risk.label, cardCount: selected.length },
    })
    return blockedResponse(risk, payload, selected, authStatus)
  }
  await recordAuditSafe(providers, {
    userId: user?.id,
    intent,
    requestedScope: 'service_discovery',
    decision: 'allowed',
    actionType: intent === 'searchServices' ? 'service_search' : 'service_recommend',
    metadata: { cardCount: selected.length },
  })

  return {
    reply: selected.length
      ? '我根据你的需求找到了这些服务。你可以先查看详情，提交、下单和支付都需要你手动确认。'
      : '暂时没有找到完全匹配的服务，可以换个关键词或先提交咨询需求。',
    requiresAuth: false,
    authStatus,
    cards: selected,
    draft: null,
    actions: selected.slice(0, 3).map((card) => ({
      type: 'navigate',
      label: card.action?.label || '查看详情',
      url: card.action?.url || '/pages/services/index',
    })),
    intent,
  }
}
