/**
 * 研究分析相关类型定义
 * 涵盖研究任务草稿、研究计划、执行产物（发现/冲突/章节/报告）、
 * 会话状态管理以及模板与深度级别的配置选项。
 */
import type { BasketItem } from '@/types/basket'
import type { ResearchReference } from '@/types/document'

/** 研究模式：快速 / 深入 */
export type ResearchMode = 'quick' | 'deep'
/** 输出模板类型：综合报告 / 政策简报 / 时间演进 / 对比分析 / 执行研判 / 汇报提纲 / 讲话稿 */
export type ResearchOutputTemplate = 'comprehensive' | 'policy_brief' | 'timeline' | 'comparison' | 'implementation' | 'briefing_outline' | 'speech_draft'
/** 研究深度级别 */
export type ResearchDepthLevel = 'standard' | 'deep' | 'comprehensive'
/** 研究会话生命周期状态 */
export type ResearchSessionStatus = 'idle' | 'planned' | 'running' | 'completed' | 'error'
/** 证据强度等级 */
export type ResearchEvidenceStrength = 'high' | 'medium' | 'low'
/** 冲突严重等级 */
export type ResearchConflictSeverity = 'high' | 'medium' | 'low'

/** 研究任务草稿：用户在前端表单中填写的研究参数 */
export interface ResearchTaskDraft {
  mode: ResearchMode
  topic: string
  question: string
  goal: string
  timeRange: string
  regionScope: string
  orgScope: string
  outputTemplate: ResearchOutputTemplate
  depthLevel: ResearchDepthLevel
  requiredDocIds: string[]
  requiredMatterIds: string[]
}

/** 研究计划：由 AI 根据任务参数生成，包含目标、子问题、章节大纲等 */
export interface ResearchPlan {
  summary: string
  objectives: string[]
  subQuestions: string[]
  retrievalFocus: string[]
  sectionOutline: string[]
  expectedDeliverables: string[]
  notes: string[]
  includedDocIds: string[]
  includedMatterIds: string[]
}

/** 关键发现：研究执行过程中提取的重要结论 */
export interface ResearchFinding {
  title: string
  content: string
  strength: ResearchEvidenceStrength
  sourceDocIds: string[]
}

/** 冲突或缺口：文档间矛盾信息或证据不足之处 */
export interface ResearchConflict {
  title: string
  content: string
  severity: ResearchConflictSeverity
  sourceDocIds: string[]
}

export interface ResearchOpenQuestion {
  question: string
  reason: string
}

export interface ResearchSectionResult {
  title: string
  summary: string
  content: string
  sourceDocIds: string[]
}

export interface ResearchProgressItem {
  stage: string
  content: string
  status: 'running' | 'completed' | 'error'
  timestamp: number
}

/** 研究报告：研究执行完成后的最终产出 */
export interface ResearchReport {
  executiveSummary: string
  findings: ResearchFinding[]
  conflicts: ResearchConflict[]
  openQuestions: ResearchOpenQuestion[]
  sections: ResearchSectionResult[]
  onePageSummary: string
  recommendedNextSteps: string[]
  /** 交付物文档（完整 Markdown），由 LLM 在研究完成后独立生成 */
  finalDocumentMd: string
}

/** 研究会话：一次完整研究流程的全量状态快照，用于持久化和恢复 */
export interface ResearchSession {
  id: string
  title: string
  createdAt: number
  updatedAt: number
  status: ResearchSessionStatus
  task: ResearchTaskDraft
  plan?: ResearchPlan
  planTaskSignature: string
  importedItems: BasketItem[]
  references: ResearchReference[]
  progress: ResearchProgressItem[]
  report: ResearchReport
  notes: string
  lastError: string
}

export interface ResearchTemplateOption {
  value: ResearchOutputTemplate
  label: string
  description: string
}

export interface ResearchDepthOption {
  value: ResearchDepthLevel
  label: string
  description: string
}

export const RESEARCH_TEMPLATE_OPTIONS: ResearchTemplateOption[] = [
  { value: 'comprehensive', label: '综合研究报告', description: '适合专题梳理、领导汇报和全面研究。' },
  { value: 'policy_brief', label: '政策简报', description: '突出结论、依据链和执行建议。' },
  { value: 'timeline', label: '时间演进', description: '强调阶段节点、政策演化和趋势判断。' },
  { value: 'comparison', label: '对比分析', description: '适合地区、部门或政策方案比较。' },
  { value: 'implementation', label: '执行研判', description: '强调落地任务、风险和推进路径。' },
  { value: 'briefing_outline', label: '汇报提纲', description: '适合领导汇报前整理提纲和会议材料。' },
  { value: 'speech_draft', label: '讲话稿', description: '适合会议讲话和政策宣贯发言稿准备。' },
]

export const RESEARCH_DEPTH_OPTIONS: ResearchDepthOption[] = [
  { value: 'standard', label: '标准', description: '适合快速形成结构化研究报告。' },
  { value: 'deep', label: '深入', description: '增加证据覆盖与问题拆解深度。' },
  { value: 'comprehensive', label: '全面', description: '尽可能扩大材料覆盖与风险提示。' },
]

/** 创建默认研究任务草稿，可选填入初始主题 */
export function createDefaultResearchTask(seed = ''): ResearchTaskDraft {
  return {
    mode: 'deep',
    topic: seed,
    question: seed,
    goal: '',
    timeRange: '',
    regionScope: '',
    orgScope: '',
    outputTemplate: 'comprehensive',
    depthLevel: 'deep',
    requiredDocIds: [],
    requiredMatterIds: [],
  }
}

export function createEmptyResearchReport(): ResearchReport {
  return {
    executiveSummary: '',
    findings: [],
    conflicts: [],
    openQuestions: [],
    sections: [],
    onePageSummary: '',
    recommendedNextSteps: [],
    finalDocumentMd: '',
  }
}

// ---------------------------------------------------------------------------
// Research Record types (backend-aligned)
// ---------------------------------------------------------------------------

/** 研究记录状态（与后端枚举对齐） */
export type ResearchRecordStatus =
  | 'draft' | 'clarifying' | 'planned'
  | 'running' | 'cancelled' | 'completed' | 'failed'

/** 列表页摘要 */
export interface ResearchRecordSummary {
  id: string
  title: string
  mode: ResearchMode
  status: ResearchRecordStatus
  outputTemplate: ResearchOutputTemplate
  summary: string | null
  archived: boolean
  versionNo: number
  createdAt: string
  updatedAt: string
}

/** 详情页记录（不含完整 report） */
export interface ResearchRecordDetail {
  id: string
  title: string
  mode: ResearchMode
  status: ResearchRecordStatus
  outputTemplate: ResearchOutputTemplate
  summary: string | null
  archived: boolean
  sessionId: string | null
  task: ResearchTaskDraft | null
  plan: ResearchPlan | null
  references: ResearchReference[] | null
  importedItems: BasketItem[] | null
  notes: string | null
  parentRecordId: string | null
  rootRecordId: string | null
  versionNo: number
  lastError: string | null
  createdAt: string
  updatedAt: string
  completedAt: string | null
  // Latest run metadata (C7)
  latestRunId: string | null
  latestRunStatus: string | null
  latestRunType: string | null
  latestRunStartedAt: string | null
  clarificationMessages: Record<string, unknown>[] | null
  chatMessages: Record<string, unknown>[] | null
}

/** Run 响应 */
export interface ResearchRecordRunInfo {
  runId: string
  recordId: string
  status: string
}