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

function toNumber(value, fallback = 0) {
  const number = Number(value)
  return Number.isFinite(number) ? number : fallback
}

function toArray(value) {
  return Array.isArray(value) ? value : []
}

export function normalizeApprovalWorkbenchItem(item = {}) {
  const evidence = item.evidence && typeof item.evidence === 'object' ? item.evidence : {}
  const suggestion = item.suggestion && typeof item.suggestion === 'object' ? item.suggestion : {}
  return {
    taskKey: String(item.task_key || item.taskKey || '').trim(),
    claim: item.claim && typeof item.claim === 'object' ? item.claim : {},
    priorityScore: Math.max(0, Math.min(toNumber(item.priority_score ?? item.priorityScore), 100)),
    priorityTier: String(item.priority_tier || item.priorityTier || 'normal').trim(),
    priorityReasons: toArray(item.priority_reasons || item.priorityReasons).map((reason) => ({
      code: String(reason?.code || '').trim(),
      label: String(reason?.label || '').trim(),
      weight: toNumber(reason?.weight),
      tone: String(reason?.tone || 'normal').trim()
    })).filter((reason) => reason.label),
    riskLevel: String(item.risk_level || item.riskLevel || 'low').trim(),
    openRiskCount: Math.max(0, toNumber(item.open_risk_count ?? item.openRiskCount)),
    budgetUsageRate: item.budget_usage_rate == null && item.budgetUsageRate == null
      ? null
      : toNumber(item.budget_usage_rate ?? item.budgetUsageRate),
    waitingHours: Math.max(0, toNumber(item.waiting_hours ?? item.waitingHours)),
    slaDueAt: String(item.sla_due_at || item.slaDueAt || '').trim(),
    slaOverdue: Boolean(item.sla_overdue ?? item.slaOverdue),
    evidence: {
      completeness: Math.max(0, Math.min(toNumber(evidence.completeness), 1)),
      presentCount: Math.max(0, toNumber(evidence.present_count ?? evidence.presentCount)),
      requiredCount: Math.max(0, toNumber(evidence.required_count ?? evidence.requiredCount)),
      missingLabels: toArray(evidence.missing_labels || evidence.missingLabels)
        .map((value) => String(value || '').trim())
        .filter(Boolean),
      historicalLabels: toArray(evidence.historical_labels || evidence.historicalLabels)
        .map((value) => String(value || '').trim())
        .filter(Boolean)
    },
    suggestion: {
      action: String(suggestion.action || 'manual_review').trim(),
      label: String(suggestion.label || '人工复核').trim(),
      reason: String(suggestion.reason || '').trim(),
      advisoryOnly: suggestion.advisory_only !== false && suggestion.advisoryOnly !== false
    }
  }
}

export async function fetchApprovalWorkbenchItems(options = {}) {
  const limit = Math.max(1, Math.min(toNumber(options.limit || 100), 200))
  const payload = await apiRequest(`/approval-workbench/items?limit=${limit}`, {
    timeoutMs: toNumber(options.timeoutMs || 5000),
    timeoutMessage: '审批优先队列加载超时，请稍后重试。'
  })
  return {
    items: toArray(payload?.items).map(normalizeApprovalWorkbenchItem),
    total: Math.max(0, toNumber(payload?.total)),
    generatedAt: String(payload?.generated_at || payload?.generatedAt || '').trim(),
    scoringVersion: String(payload?.scoring_version || payload?.scoringVersion || '').trim()
  }
}
