/**
 * 研究分析 API 模块
 * 封装研究计划生成、研究执行、章节重跑等接口的请求体构建与数据标准化。
 * 前后端字段命名风格不同（前端 camelCase / 后端 snake_case），此处负责转换。
 */
import request from './request'
import type { ResearchPlan, ResearchSectionResult, ResearchTaskDraft } from '@/types/research'

/** 去重并过滤空字符串 */
function uniqueStrings(values: string[]): string[] {
  return [...new Set(values.map((item) => item.trim()).filter(Boolean))]
}

/** 将前端 ResearchTaskDraft 转换为后端 API 所需的 snake_case 格式 */
function mapTaskToApi(
  task: ResearchTaskDraft,
  seedMatterIds: string[] = [],
): Record<string, unknown> {
  return {
    mode: task.mode,
    topic: task.topic,
    question: task.question,
    goal: task.goal || undefined,
    time_range: task.timeRange || undefined,
    region_scope: task.regionScope || undefined,
    org_scope: task.orgScope || undefined,
    output_template: task.outputTemplate,
    depth_level: task.depthLevel,
    required_doc_ids: uniqueStrings(task.requiredDocIds),
    required_matter_ids: uniqueStrings([...task.requiredMatterIds, ...seedMatterIds]),
  }
}

/** 将前端 ResearchPlan 转换为后端 API 所需的 snake_case 格式 */
function mapPlanToApi(plan: ResearchPlan): Record<string, unknown> {
  return {
    summary: plan.summary,
    objectives: plan.objectives,
    sub_questions: plan.subQuestions,
    retrieval_focus: plan.retrievalFocus,
    section_outline: plan.sectionOutline,
    expected_deliverables: plan.expectedDeliverables,
    notes: plan.notes,
    included_doc_ids: plan.includedDocIds,
    included_matter_ids: plan.includedMatterIds,
  }
}

/**
 * 将后端返回的研究计划数据标准化为前端 ResearchPlan 结构。
 * 兼容 snake_case 和 camelCase 两种字段命名，保证容错性。
 */
/** 后端返回的研究计划原始数据（snake_case 或 camelCase 混合） */
interface ResearchPlanPayload {
  summary?: string
  objectives?: string[]
  sub_questions?: string[]
  subQuestions?: string[]
  retrieval_focus?: string[]
  retrievalFocus?: string[]
  section_outline?: string[]
  sectionOutline?: string[]
  expected_deliverables?: string[]
  expectedDeliverables?: string[]
  notes?: string[]
  included_doc_ids?: string[]
  includedDocIds?: string[]
  included_matter_ids?: string[]
  includedMatterIds?: string[]
}

export function normalizeResearchPlan(payload: ResearchPlanPayload | null | undefined): ResearchPlan {
  return {
    summary: payload?.summary || '',
    objectives: Array.isArray(payload?.objectives) ? payload.objectives : [],
    subQuestions: Array.isArray(payload?.sub_questions)
      ? payload.sub_questions
      : Array.isArray(payload?.subQuestions)
        ? payload.subQuestions
        : [],
    retrievalFocus: Array.isArray(payload?.retrieval_focus)
      ? payload.retrieval_focus
      : Array.isArray(payload?.retrievalFocus)
        ? payload.retrievalFocus
        : [],
    sectionOutline: Array.isArray(payload?.section_outline)
      ? payload.section_outline
      : Array.isArray(payload?.sectionOutline)
        ? payload.sectionOutline
        : [],
    expectedDeliverables: Array.isArray(payload?.expected_deliverables)
      ? payload.expected_deliverables
      : Array.isArray(payload?.expectedDeliverables)
        ? payload.expectedDeliverables
        : [],
    notes: Array.isArray(payload?.notes) ? payload.notes : [],
    includedDocIds: Array.isArray(payload?.included_doc_ids)
      ? payload.included_doc_ids
      : Array.isArray(payload?.includedDocIds)
        ? payload.includedDocIds
        : [],
    includedMatterIds: Array.isArray(payload?.included_matter_ids)
      ? payload.included_matter_ids
      : Array.isArray(payload?.includedMatterIds)
        ? payload.includedMatterIds
        : [],
  }
}

/** 调用后端生成研究计划，返回标准化后的 ResearchPlan */
export async function createResearchPlan(
  task: ResearchTaskDraft,
  sessionId?: string,
  seedDocIds: string[] = [],
  seedMatterIds: string[] = [],
): Promise<ResearchPlan> {
  const res = await request.post('/api/ai/v1/research/plan', {
    session_id: sessionId,
    task: mapTaskToApi(task, seedMatterIds),
    seed_doc_ids: uniqueStrings(seedDocIds),
  })
  return normalizeResearchPlan(res.data?.plan)
}

/** 构建研究执行 SSE 请求体（整体执行） */
export function buildResearchRunBody(
  task: ResearchTaskDraft,
  plan: ResearchPlan,
  sessionId?: string,
  seedMatterIds: string[] = [],
): Record<string, unknown> {
  return {
    session_id: sessionId,
    task: mapTaskToApi(task, seedMatterIds),
    plan: mapPlanToApi(plan),
  }
}

/** 构建章节局部重跑 SSE 请求体 */
export function buildResearchSectionRerunBody(
  task: ResearchTaskDraft,
  plan: ResearchPlan,
  section: ResearchSectionResult,
  sessionId?: string,
  seedMatterIds: string[] = [],
): Record<string, unknown> {
  return {
    session_id: sessionId,
    task: mapTaskToApi(task, seedMatterIds),
    plan: mapPlanToApi(plan),
    section_title: section.title,
    section_summary: section.summary || undefined,
    source_doc_ids: uniqueStrings(section.sourceDocIds),
  }
}
