/** 数字员工设置：面向管理员的简明任务列表（频率固定，仅可调执行时间） */
export const HERMES_SIMPLE_TASKS = [
  {
    id: 'global_risk_scan',
    label: '财务风险图谱巡检',
    hint: '扫描单据、票据、审批链和画像异常',
    frequency: 'daily',
    frequencyLabel: '每天'
  },
  {
    id: 'weekly_expense_report',
    label: '费控洞察周报',
    hint: '聚合生成财务总结简报',
    frequency: 'weekly',
    frequencyLabel: '每周一',
    weekday: 1
  },
  {
    id: 'employee_behavior_profile_scan',
    label: '员工画像巡检',
    hint: '沉淀费用、流程质量与 AI 协作画像快照',
    frequency: 'weekly',
    frequencyLabel: '每周一',
    weekday: 1
  }
]

function buildDefaultSchedules() {
  const defaults = {
    global_risk_scan: { enabled: true, frequency: 'daily', time: '09:00', weekday: 1, monthDay: 1, month: 1 },
    weekly_expense_report: { enabled: false, frequency: 'weekly', time: '10:30', weekday: 1, monthDay: 1, month: 1 },
    employee_behavior_profile_scan: { enabled: false, frequency: 'weekly', time: '08:30', weekday: 1, monthDay: 1, month: 1 }
  }

  for (const task of HERMES_SIMPLE_TASKS) {
    const schedule = defaults[task.id]
    if (!schedule) {
      continue
    }
    schedule.frequency = task.frequency
    if (task.weekday != null) {
      schedule.weekday = task.weekday
    }
    if (task.monthDay != null) {
      schedule.monthDay = task.monthDay
    }
    if (task.month != null) {
      schedule.month = task.month
    }
  }

  return defaults
}

export function buildDefaultHermesEmployeeForm() {
  return {
    masterEnabled: true,
    notifyOnFailure: true,
    capabilities: {
      global_risk_scan: true,
      weekly_expense_report: false,
      employee_behavior_profile_scan: false
    },
    schedules: buildDefaultSchedules()
  }
}

export function mergeHermesEmployeeForm(override = {}) {
  const defaults = buildDefaultHermesEmployeeForm()
  const schedules = { ...defaults.schedules }

  for (const [key, value] of Object.entries(override?.schedules || {})) {
    schedules[key] = { ...defaults.schedules[key], ...value }
  }

  for (const task of HERMES_SIMPLE_TASKS) {
    if (schedules[task.id]) {
      schedules[task.id].frequency = task.frequency
      if (task.weekday != null) {
        schedules[task.id].weekday = task.weekday
      }
      if (task.monthDay != null) {
        schedules[task.id].monthDay = task.monthDay
      }
      if (task.month != null) {
        schedules[task.id].month = task.month
      }
    }
  }

  return {
    ...defaults,
    ...override,
    capabilities: {
      ...defaults.capabilities,
      ...(override?.capabilities || {})
    },
    schedules
  }
}

export function isHermesTaskEnabled(form, taskId) {
  return Boolean(form?.masterEnabled && form?.capabilities?.[taskId] && form?.schedules?.[taskId]?.enabled)
}

export function countEnabledHermesTasks(form) {
  return HERMES_SIMPLE_TASKS.filter((task) => isHermesTaskEnabled(form, task.id)).length
}

export function isHermesEmployeeSettingsReady(form) {
  return Boolean(!form?.masterEnabled || countEnabledHermesTasks(form) > 0)
}
