import { apiRequest } from './api.js'

const SYSTEM_DASHBOARD_FALLBACK = {
  totals: null,
  agentDailyRatio: null,
  loginWave: null,
  tokenDailyWave: null,
  userTokenUsage: null,
  accuracyComparison: null,
  usageDurationSummary: null,
  feedbackSummary: null,
  toolDetailRows: null,
  hasRealData: false
}

const FINANCE_DASHBOARD_FALLBACK = {
  totals: null,
  metricMeta: null,
  trend: null,
  spendByCategory: null,
  exceptionMix: null,
  departmentRanking: null,
  departmentEmployeeMix: null,
  employeeRanking: null,
  topClaims: null,
  bottlenecks: null,
  budgetSummary: null,
  budgetMetrics: null,
  hasRealData: false
}

const DIGITAL_EMPLOYEE_DASHBOARD_FALLBACK = {
  totals: null,
  dailyWork: [],
  taskDistribution: [],
  categoryDistribution: [],
  recentRuns: [],
  hasRealData: false
}

function normalizeSystemDashboardPayload(payload = {}) {
  return {
    ...SYSTEM_DASHBOARD_FALLBACK,
    windowDays: Number(payload.window_days || payload.windowDays || 7),
    generatedAt: payload.generated_at || payload.generatedAt || '',
    hasRealData: Boolean(payload.has_real_data ?? payload.hasRealData),
    totals: payload.totals || null,
    agentDailyRatio: payload.agent_daily_ratio || payload.agentDailyRatio || null,
    loginWave: payload.login_wave || payload.loginWave || null,
    tokenDailyWave: payload.token_daily_wave || payload.tokenDailyWave || null,
    userTokenUsage: payload.user_token_usage || payload.userTokenUsage || null,
    accuracyComparison: payload.accuracy_comparison || payload.accuracyComparison || null,
    usageDurationSummary: payload.usage_duration_summary || payload.usageDurationSummary || null,
    feedbackSummary: payload.feedback_summary || payload.feedbackSummary || null,
    toolDetailRows: payload.tool_detail_rows || payload.toolDetailRows || null
  }
}

function normalizeFinanceDashboardPayload(payload = {}) {
  return {
    ...FINANCE_DASHBOARD_FALLBACK,
    rangeKey: payload.range_key || payload.rangeKey || '近10日',
    startDate: payload.start_date || payload.startDate || '',
    endDate: payload.end_date || payload.endDate || '',
    generatedAt: payload.generated_at || payload.generatedAt || '',
    hasRealData: Boolean(payload.has_real_data ?? payload.hasRealData),
    totals: payload.totals || null,
    metricMeta: payload.metric_meta || payload.metricMeta || null,
    trend: payload.trend || null,
    spendByCategory: payload.spend_by_category || payload.spendByCategory || null,
    exceptionMix: payload.exception_mix || payload.exceptionMix || null,
    departmentRanking: payload.department_ranking || payload.departmentRanking || null,
    departmentEmployeeMix: payload.department_employee_mix || payload.departmentEmployeeMix || null,
    employeeRanking: payload.employee_ranking || payload.employeeRanking || null,
    topClaims: payload.top_claims || payload.topClaims || null,
    bottlenecks: payload.bottlenecks || null,
    budgetSummary: payload.budget_summary || payload.budgetSummary || null,
    budgetMetrics: payload.budget_metrics || payload.budgetMetrics || null
  }
}

export function normalizeDigitalEmployeeDashboardPayload(payload = {}) {
  return {
    ...DIGITAL_EMPLOYEE_DASHBOARD_FALLBACK,
    windowDays: Number(payload.window_days || payload.windowDays || 7),
    generatedAt: payload.generated_at || payload.generatedAt || '',
    hasRealData: Boolean(payload.has_real_data ?? payload.hasRealData),
    totals: payload.totals || null,
    dailyWork: payload.daily_work || payload.dailyWork || [],
    taskDistribution: payload.task_distribution || payload.taskDistribution || [],
    categoryDistribution: payload.category_distribution || payload.categoryDistribution || [],
    recentRuns: payload.recent_runs || payload.recentRuns || []
  }
}

export async function fetchSystemDashboard(options = {}) {
  const days = Number(options.days || 7)
  const search = new URLSearchParams()
  search.set('days', String(Math.max(1, Math.min(days, 30))))

  const payload = await apiRequest(`/analytics/system-dashboard?${search.toString()}`, {
    timeoutMs: Number(options.timeoutMs || 3500),
    timeoutMessage: '系统看板真实数据加载超时，已保留本地展示数据。'
  })

  return normalizeSystemDashboardPayload(payload)
}

export async function fetchDigitalEmployeeDashboard(options = {}) {
  const days = Number(options.days || 7)
  const limit = Number(options.limit || 300)
  const search = new URLSearchParams()
  search.set('days', String(Math.max(1, Math.min(days, 30))))
  search.set('limit', String(Math.max(1, Math.min(limit, 1000))))

  const payload = await apiRequest(`/analytics/digital-employee-dashboard?${search.toString()}`, {
    timeoutMs: Number(options.timeoutMs || 3500),
    timeoutMessage: '数字员工看板真实数据加载超时，请稍后重试。'
  })

  return normalizeDigitalEmployeeDashboardPayload(payload)
}

export async function fetchFinanceDashboard(options = {}) {
  const search = new URLSearchParams()
  search.set('range_key', String(options.rangeKey || options.range || '近10日'))
  search.set('trend_range', String(options.trendRange || '近12天'))
  search.set('department_range', String(options.departmentRange || '本月'))

  if (options.startDate) search.set('start_date', String(options.startDate))
  if (options.endDate) search.set('end_date', String(options.endDate))

  const payload = await apiRequest(`/analytics/finance-dashboard?${search.toString()}`, {
    timeoutMs: Number(options.timeoutMs || 10000),
    timeoutMessage: '财务看板真实数据加载超时，已保留本地展示数据。'
  })

  return normalizeFinanceDashboardPayload(payload)
}
