import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { config, modelProviders, getConfiguredProviders, getDefaultProvider } from '../utils/config.js'
import DeepSeekAPI from '../api/deepseek.js'
import { buildPrompt, createStreamParser, parseGhostwriterOutput } from '../utils/promptBuilder.js'
import { PARADIGMS, getParadigmById, buildParadigmConstraints } from '../config/paradigms.js'

export const useAppStore = defineStore('app', () => {
  // 页面状态
  const currentPage = ref('home') // 默认进入主页

  // 模型服务商选择
  const selectedProviderId = ref(getDefaultProvider().id)

  // 动态获取当前服务商配置
  const currentProvider = computed(() => {
    return modelProviders[selectedProviderId.value] || getDefaultProvider()
  })

  // API 配置（基于选择的服务商）
  const apiUrl = computed(() => currentProvider.value.apiUrl)
  const apiKey = computed(() => currentProvider.value.apiKey)

  // 写作相关
  const inputTask = ref('请帮我写一篇关于"AI 辅助编程如何改变软件开发流程"的博客文章，面向中级程序员。')
  const inputType = ref('text') // 'text' 或 'outline'
  const outlinePoints = ref({
    topic: '',
    audience: '',
    keyPoints: ''
  })
  const references = ref([
    {
      title: '示例：技术博客风格.txt',
      content: '本文深入探讨了...（此处省略2000字，这是为了让AI模仿这种干练的技术风格）...',
      styleTags: ['#技术干货', '#逻辑严密', '#客观中立']
    }
  ])
  const selectedTags = ref(['Markdown格式', '总分总结构'])
  const customConstraint = ref('')

  // 范式相关
  const activeParadigm = ref(null) // 当前激活的范式配置
  const expertGuidelines = ref([]) // 专家指令列表

  // 当前编辑的文稿
  const currentDocument = ref(null)

  // 质检报告（深度模式）
  const qualityReport = ref(null) // { checks: [{key, title, status, message}], overall: 'pass'|'warning'|'fail' }

  // 生成相关
  const isGenerating = ref(false)
  const isDeepMode = ref(false)
  const generationStage = ref('') // 'thinking' | 'draft' | 'critique' | 'refine' | ''
  const generatedContent = ref('')
  const thinkingContent = ref('') // AI 思考过程（风格分析 + 大纲规划）
  const rawStreamBuffer = ref('') // 原始流式输出缓冲

  // 分析相关
  const analysisText = ref('')
  const analysisResult = ref(null)
  const isAnalyzing = ref(false)
  const styleAnalysis = ref('') // 存储具体的风格分析内容

  // 范式写作相关 (Paradigm Writing)
  const paradigmWriterState = ref({
    selectedParadigmId: null,
    sections: [],  // 解析后的章节列表 [{title, placeholder, userInput, generatedContent, isGenerating}]
    currentSectionIndex: 0,
    isGeneratingOverall: false
  })

  // 范式编辑状态 (Paradigm Editing)
  const paradigmEditState = ref({
    isEditing: false,       // 是否正在编辑
    isAddMode: false,       // 是否为新增模式
    editingParadigmId: null, // 正在编辑的范式ID
    editForm: {
      icon: '📝',
      name: '',
      description: '',
      tagsInput: '',
      tagClass: 'bg-blue-900/30 text-blue-300',
      specializedPrompt: ''
    }
  })

  // UI状态
  const showPromptDebug = ref(false)
  const showRefInput = ref(false)
  const newRefTitle = ref('')
  const newRefContent = ref('')

  // 方法
  const addReferenceFromAnalysis = (title, content) => {
    references.value.push({
      title: title || `参考范文_${new Date().toLocaleDateString()}`,
      content: content,
      styleTags: [],
      isAnalyzing: false
    })
    // 自动触发风格分析
    analyzeReferenceStyleAction(references.value.length - 1)
  }

  // 分析参考案例风格动作
  const analyzeReferenceStyleAction = async (index) => {
    const ref = references.value[index]
    if (!ref || !ref.content) return

    if (!apiUrl.value || !apiKey.value || apiKey.value === 'YOUR_KEY') {
      console.warn('Store: Missing API Key for style analysis')
      return
    }

    // 如果已经有标签，跳过（或者强制刷新？这里假设自动触发仅一次）
    if (ref.styleTags && ref.styleTags.length > 0) return

    ref.isAnalyzing = true
    try {
      const api = new DeepSeekAPI({
        url: apiUrl.value,
        key: apiKey.value,
        model: currentProvider.value.model,
        appId: currentProvider.value.appId
      })
      let fullTags = ''

      console.log(`Store: Analyzing style for reference [${index}]...`)
      await api.extractStyle(ref.content, (content) => {
        fullTags += content
      })

      // 提取标签 (假设返回格式为 "#标签1 #标签2")
      const tags = fullTags.match(/#[\w\u4e00-\u9fa5]+/g) || []
      ref.styleTags = tags
      console.log('Store: Style tags extracted:', tags)
    } catch (error) {
      console.error('Store: Style analysis failed', error)
    } finally {
      ref.isAnalyzing = false
    }
  }

  // 生成内容动作
  const generateContentAction = async () => {
    if (!apiUrl.value || !apiKey.value || apiKey.value === 'YOUR_KEY') {
      throw new Error('请先配置 API 地址和 API Key')
    }

    console.log('Store: generateContentAction 启动', { mode: isDeepMode.value ? 'Deep' : 'Standard' })
    isGenerating.value = true
    generatedContent.value = ''
    thinkingContent.value = ''
    rawStreamBuffer.value = ''
    generationStage.value = 'thinking'

    try {
      const api = new DeepSeekAPI({
        url: apiUrl.value,
        key: apiKey.value,
        model: currentProvider.value.model,
        appId: currentProvider.value.appId
      })
      const streamParser = createStreamParser()

      // 构建 Prompt（XML 结构化数据）
      const taskContent = inputType.value === 'outline'
        ? `核心主题：${outlinePoints.value.topic}\n目标受众：${outlinePoints.value.audience}\n关键观点：\n${outlinePoints.value.keyPoints}`
        : inputTask.value

      const userMessage = buildPrompt(
        taskContent,
        [...selectedTags.value, customConstraint.value].filter(Boolean),
        references.value
      )

      console.log('Store: 开始 Ghostwriter Protocol 生成流程...', {
        hasParadigm: !!activeParadigm.value,
        paradigmName: activeParadigm.value?.name
      })

      // 流式接收并实时解析 XML 结构，同时实时显示内容
      // 传入范式配置以使用专用 System Prompt
      await api.generateContent(userMessage, (chunk) => {
        rawStreamBuffer.value += chunk
        const { section, buffer } = streamParser.process(chunk)

        // 根据当前 section 更新 UI 状态
        if (section === 'thinking' && generationStage.value !== 'thinking') {
          generationStage.value = 'thinking'
          console.log('Store: 进入思考阶段 (Style Analysis + Planning)')
        }
        if (section === 'draft' && generationStage.value !== 'draft') {
          generationStage.value = 'draft'
          console.log('Store: 进入草稿生成阶段')
        }

        // 提取当前已接收的 thinking 和 draft 内容
        const thinkingMatch = buffer.match(/<thinking>([\s\S]*?)(?:<\/thinking>|$)/)
        const draftMatch = buffer.match(/<draft>([\s\S]*?)(?:<\/draft>|$)/)

        if (thinkingMatch) {
          thinkingContent.value = thinkingMatch[1].trim()
        }

        // 深度模式下，初稿阶段不流式输出到预览区，只在非深度模式下流式显示
        if (!isDeepMode.value) {
          if (draftMatch) {
            generatedContent.value = draftMatch[1].trim()
          }
          // 如果 AI 没有按 XML 格式输出，直接显示原始内容
          if (!thinkingMatch && !draftMatch && buffer.length > 50) {
            generatedContent.value = buffer
          }
        }
      }, { paradigm: activeParadigm.value })

      // 流式完成后，最终解析确保内容完整
      const { thinking, draft, hasStructuredOutput } = streamParser.getResult()
      console.log('Store: XML 解析完成', { hasStructuredOutput, thinkingLength: thinking.length, draftLength: draft.length })

      thinkingContent.value = thinking
      // 非深度模式下才直接显示初稿
      if (!isDeepMode.value) {
        generatedContent.value = draft
      }

      // 如果是深度模式，进入 Agentic Workflow
      if (isDeepMode.value) {
        // 深度模式下显示进度提示
        generatedContent.value = '⏳ **深度模式处理中...**\n\n'
        generatedContent.value += '✅ 初稿生成完成\n'
        // 2. 质检阶段（如果有专家指令）
        if (activeParadigm.value && expertGuidelines.value.length > 0) {
          generationStage.value = 'inspect'
          console.log('Store: 进入质检阶段...')

          // 构建质检 Prompt
          const guidelinesText = expertGuidelines.value
            .map((g, i) => `${i + 1}. 【${g.title}】${g.description}`)
            .join('\n')

          const inspectPrompt = `你是一名严格的质检专家。请根据以下专家评价标准，逐条检查这篇文章的质量。

# 专家评价标准
${guidelinesText}

# 待检查的文章
${draft}

# 输出要求
请严格按照以下 JSON 格式输出检查结果（不要输出其他内容）：
{
  "checks": [
    {"key": "对应的检查项英文key", "title": "检查项标题", "status": "pass|warning|fail", "message": "具体评价说明"}
  ],
  "overall": "pass|warning|fail",
  "summary": "整体评价总结（一句话）"
}`

          let inspectResult = ''
          await api.generateContent(inspectPrompt, (content) => {
            inspectResult += content
          }, { temperature: 0.3 })

          // 解析质检结果
          try {
            // 提取 JSON（可能被包裹在 markdown 代码块中）
            const jsonMatch = inspectResult.match(/\{[\s\S]*\}/)
            if (jsonMatch) {
              qualityReport.value = JSON.parse(jsonMatch[0])
              console.log('Store: 质检完成', qualityReport.value)
            }
          } catch (e) {
            console.warn('Store: 质检结果解析失败', e)
            qualityReport.value = {
              checks: expertGuidelines.value.map(g => ({
                key: g.checkKey,
                title: g.title,
                status: 'warning',
                message: '质检解析异常，请人工复核'
              })),
              overall: 'warning',
              summary: '质检结果解析失败，建议人工复核'
            }
          }
          generatedContent.value += '✅ 质检完成\n'
        }

        // 3. 批判阶段
        generationStage.value = 'critique'
        console.log('Store: 进入批判阶段...')
        generatedContent.value += '🔍 AI 深度反思中...\n'

        const critiquePrompt = `你是一个严厉的主编。请分析以下文章的逻辑漏洞、论证强度和风格一致性。请列出3-5条具体的修改建议。不要重写文章，只提供建议。\n\n文章内容：\n${draft}`

        let critiqueContent = ''
        await api.generateContent(critiquePrompt, (content) => {
          // 不流式输出到预览区，只收集内容
          critiqueContent += content
        })
        generatedContent.value += '✅ 反思分析完成\n'

        // 4. 修正阶段 - 只有这个阶段流式输出
        generationStage.value = 'refine'
        console.log('Store: 进入修正阶段...')
        generatedContent.value += '✨ 深度润色中...\n\n---\n\n'

        const refinePrompt = `你是一个专业的写作专家。请根据以下修改建议，重写这篇文章。保持原文的优秀风格，同时修复提到的问题。\n\n原文：\n${draft}\n\n修改建议：\n${critiqueContent}\n\n请直接输出重写后的正文：`

        await api.generateContent(refinePrompt, (content) => {
          generatedContent.value += content
        })
      }

      console.log('Store: 生成流程完成')
    } catch (error) {
      console.error('Store: 生成内容失败:', error)
      throw error
    } finally {
      isGenerating.value = false
      generationStage.value = ''
      console.log('Store: isGenerating 重置为 false')
    }
  }

  // 分析文章动作
  const analyzeArticleAction = async (text, detectParadigmFn) => {
    if (!text.trim()) {
      throw new Error('请输入要分析的文章内容')
    }

    console.log('Store: analyzeArticleAction 启动')
    isAnalyzing.value = true
    analysisResult.value = {
      paradigm: '分析中...',
      paradigmType: null,
      analysis: '',
      timestamp: new Date()
    }

    try {
      const api = new DeepSeekAPI({
        url: apiUrl.value,
        key: apiKey.value,
        model: currentProvider.value.model,
        appId: currentProvider.value.appId
      })
      let fullContent = ''

      console.log('Store: 调用 API 分析文章...')
      await api.analyzeContent(text, (content) => {
        fullContent += content
        // 实时更新分析结果，用于 UI 展示流式效果
        analysisResult.value = {
          paradigm: '分析中...',
          paradigmType: null,
          analysis: fullContent,
          timestamp: new Date()
        }
      })
      console.log('Store: 分析文章流式接收完成')

      // 分析完成后检测范式类型
      const detectedParadigm = detectParadigmFn(fullContent)
      console.log('Store: 检测到范式类型:', detectedParadigm.name)

      analysisResult.value = {
        paradigm: detectedParadigm.name,
        paradigmType: detectedParadigm.type,
        analysis: fullContent,
        timestamp: new Date()
      }

      return { paradigm: detectedParadigm.name, content: fullContent }
    } catch (error) {
      console.error('Store: 分析失败:', error)
      analysisResult.value = {
        error: true,
        message: error.message
      }
      throw error
    } finally {
      isAnalyzing.value = false
      console.log('Store: isAnalyzing 重置为 false')
    }
  }

  // 切换页面
  const switchPage = (page) => {
    currentPage.value = page
  }

  // 设置当前页面（别名）
  const setCurrentPage = (page) => {
    currentPage.value = page
  }

  // 设置当前文稿（用于从文稿列表打开编辑）
  const setCurrentDocument = (doc) => {
    if (doc) {
      inputTask.value = doc.content || ''
      generatedContent.value = doc.content || ''
      // 可以扩展更多字段
    }
  }

  // 加载范式预设
  const loadParadigmPreset = (paradigmId) => {
    const paradigm = getParadigmById(paradigmId)
    if (!paradigm) {
      console.warn('Store: Paradigm not found:', paradigmId)
      return
    }

    console.log('Store: Loading paradigm preset:', paradigm.name)

    // 1. 设置当前范式
    activeParadigm.value = paradigm
    expertGuidelines.value = paradigm.expertGuidelines || []

    // 2. 预填充大纲模板（如果有）
    if (paradigm.outlineTemplate) {
      inputType.value = 'outline'
      inputTask.value = paradigm.outlineTemplate
    } else {
      inputType.value = 'text'
      inputTask.value = ''
    }

    // 3. 自动挂载默认参考案例
    if (paradigm.defaultReference) {
      references.value = [{
        title: paradigm.defaultReference.title,
        content: paradigm.defaultReference.content,
        styleTags: [],
        isAnalyzing: false
      }]
    }

    // 4. 自动选中推荐标签
    if (paradigm.recommendedTags) {
      selectedTags.value = [...paradigm.recommendedTags]
    }

    // 5. 注入系统约束到自定义要求（简化版，完整版在 specializedPrompt）
    if (paradigm.systemConstraints?.length > 0) {
      customConstraint.value = paradigm.systemConstraints.join('；')
    }

    // 6. 清空之前的生成内容
    generatedContent.value = ''
    thinkingContent.value = ''
    qualityReport.value = null

    // 7. 跳转到写作页面
    currentPage.value = 'writer'
  }

  // 清除当前范式
  const clearParadigm = () => {
    activeParadigm.value = null
    expertGuidelines.value = []
    qualityReport.value = null
  }

  // 通用 API 调用方法
  const callApi = async (prompt, onContent, options = {}) => {
    const api = new DeepSeekAPI({
      url: apiUrl.value,
      key: apiKey.value,
      model: currentProvider.value.model,
      appId: currentProvider.value.appId
    })
    return api.generateContent(prompt, onContent, options)
  }

  /**
   * 范式写作：解析大纲模板为章节
   */
  const parseOutlineToSections = (paradigmId) => {
    const paradigm = getParadigmById(paradigmId)
    if (!paradigm) return []

    // 如果有 outlineTemplate，则解析它
    if (paradigm.outlineTemplate) {
      const template = paradigm.outlineTemplate
      const sections = []
      const lines = template.split('\n')

      let currentMainSection = null

      lines.forEach(line => {
        const h2Match = line.match(/^##\s+(.+)/)
        const h3Match = line.match(/^###\s+(.+)/)
        const listItemMatch = line.match(/^[-*]\s+(.+)/)

        if (h2Match) {
          currentMainSection = h2Match[1].trim()
          sections.push({
            title: currentMainSection,
            type: 'h2',
            userInput: '',
            // 新增结构化字段
            inputType: 'idea', // 默认思路型
            corePoint: '',
            materialData: '',
            supplementNote: '',
            generatedContent: '',
            isGenerating: false
          })
        } else if (h3Match) {
          sections.push({
            title: h3Match[1].trim(),
            type: 'h3',
            parentTitle: currentMainSection,
            userInput: '',
            // 新增结构化字段
            inputType: 'idea',
            corePoint: '',
            materialData: '',
            supplementNote: '',
            generatedContent: '',
            isGenerating: false
          })
        } else if (listItemMatch) {
          // 如果是列表项，通常是具体的提示或占位符
          const content = listItemMatch[1].trim()
          if (sections.length > 0) {
            const lastSection = sections[sections.length - 1]
            if (!lastSection.placeholder) {
              lastSection.placeholder = content
            } else {
              lastSection.placeholder += '\n' + content
            }
          }
        }
      })

      return sections
    }

    // 自定义范式没有 outlineTemplate：根据 expertGuidelines 生成基础章节
    const sections = []

    // 添加默认的开篇章节
    sections.push({
      title: '开篇引言',
      type: 'h2',
      userInput: '',
      inputType: 'idea',
      corePoint: '',
      materialData: '',
      supplementNote: '',
      placeholder: '请输入文章的背景、目的或主题介绍...',
      generatedContent: '',
      isGenerating: false
    })

    // 如果有 expertGuidelines，根据其内容生成章节
    if (paradigm.expertGuidelines && paradigm.expertGuidelines.length > 0) {
      // 分析 expertGuidelines 中是否有结构性建议
      const guidelines = paradigm.expertGuidelines

      // 按 scope 分组，document 级别的可能包含结构要求
      const docLevelGuidelines = guidelines.filter(g =>
        (typeof g === 'object' && g.scope === 'document') ||
        (typeof g === 'string' && /章节|结构|部分|篇幅/.test(g))
      )

      if (docLevelGuidelines.length > 0) {
        // 有文档级别指令，尝试提取章节建议
        docLevelGuidelines.forEach((g, i) => {
          const title = typeof g === 'object' ? g.title : `核心内容 ${i + 1}`
          sections.push({
            title: title,
            type: 'h2',
            userInput: '',
            inputType: 'idea',
            corePoint: '',
            materialData: '',
            supplementNote: '',
            placeholder: typeof g === 'object' ? g.description : g,
            generatedContent: '',
            isGenerating: false
          })
        })
      } else {
        // 没有明确的结构要求，生成通用章节
        sections.push({
          title: '核心内容',
          type: 'h2',
          userInput: '',
          inputType: 'idea',
          corePoint: '',
          materialData: '',
          supplementNote: '',
          placeholder: '请输入主要论点、分析或内容...',
          generatedContent: '',
          isGenerating: false
        })
      }
    } else {
      // 没有 expertGuidelines，生成最基础的章节
      sections.push({
        title: '主体内容',
        type: 'h2',
        userInput: '',
        inputType: 'idea',
        corePoint: '',
        materialData: '',
        supplementNote: '',
        placeholder: '请输入文章的主要内容...',
        generatedContent: '',
        isGenerating: false
      })
    }

    // 添加默认的结尾章节
    sections.push({
      title: '总结与展望',
      type: 'h2',
      userInput: '',
      inputType: 'idea',
      corePoint: '',
      materialData: '',
      supplementNote: '',
      placeholder: '请输入总结、建议或下一步计划...',
      generatedContent: '',
      isGenerating: false
    })

    return sections
  }

  /**
   * 范式写作：加载范式
   */
  const loadParadigmForWriting = (paradigmId) => {
    const paradigm = getParadigmById(paradigmId)
    if (!paradigm) return

    paradigmWriterState.value.selectedParadigmId = paradigmId
    paradigmWriterState.value.sections = parseOutlineToSections(paradigmId)
    paradigmWriterState.value.currentSectionIndex = 0

    // 同时设置全局激活范式以便在预览中使用专家指令
    activeParadigm.value = paradigm
    expertGuidelines.value = paradigm.expertGuidelines || []
  }

  /**
   * 范式写作：生成单个章节内容
   */
  const generateSectionContentAction = async (index) => {
    const section = paradigmWriterState.value.sections[index]
    if (!section) return

    const paradigm = getParadigmById(paradigmWriterState.value.selectedParadigmId)
    if (!paradigm) return

    section.isGenerating = true
    section.generatedContent = ''

    try {
      const api = new DeepSeekAPI({
        url: apiUrl.value,
        key: apiKey.value,
        model: currentProvider.value.model,
        appId: currentProvider.value.appId
      })
      const streamParser = createStreamParser()

      // 构建上文内容，保持连贯性
      const previousContent = paradigmWriterState.value.sections
        .slice(0, index)
        .filter(s => s.generatedContent)
        .map(s => `## ${s.title}\n${s.generatedContent}`)
        .join('\n\n')

      // 判断输入类型
      const isMaterialType = section.inputType === 'material'

      // 构建结构化输入内容
      const corePointText = section.corePoint?.trim() || ''
      const materialDataText = section.materialData?.trim() || ''
      const supplementNoteText = section.supplementNote?.trim() || section.placeholder || ''

      // 兼容旧数据：如果新字段都为空，则使用旧的 userInput
      const hasStructuredInput = corePointText || materialDataText || supplementNoteText
      const userInputFallback = section.userInput?.trim() || ''

      // 根据输入类型构建不同的 Prompt
      let inputSection = ''
      if (hasStructuredInput) {
        inputSection = `
【用户输入】

📌 核心论点：
${corePointText || '(未提供，请根据章节主题自由发挥)'}

📊 数据/案例：
${materialDataText ? (isMaterialType
            ? `⚠️ 【严格模式】以下内容必须100%完整保留，不可改写、删除或替换任何数据、数字、名称：\n${materialDataText}`
            : `以下内容可进行适当润色，但核心事实需保留：\n${materialDataText}`)
            : '(未提供)'}

💡 补充说明：
${supplementNoteText || '(无特殊要求)'}
`
      } else if (userInputFallback) {
        // 兼容旧数据
        inputSection = `
【用户提供的写作要点】：
${userInputFallback}
`
      } else {
        inputSection = `
【用户提供的写作要点】：
请根据章节标题自主发挥
`
      }

      const prompt = `你正在按照「${paradigm.name}」范式进行写作。
现在请撰写章节：${section.title}

${section.parentTitle ? `属于：${section.parentTitle}` : ''}
${inputSection}
---
${previousContent ? `【已生成的上文参考】：\n${previousContent}\n\n---` : ''}

【写作要求】：
1. 严格遵循 "${paradigm.name}" 的专家标准和文风。
2. 仅输出当前章节 "${section.title}" 的内容，不要包含标题。
3. 如果上文已提及相关背景，请简洁衔接，避免重复。
${isMaterialType && materialDataText ? '4. ⚠️ 特别注意：用户提供的数据/案例必须原文引用，不可改动任何数字或事实。' : ''}

开始写作：`

      // 使用流式解析，仅提取 <draft> 内容
      await api.generateContent(prompt, (chunk) => {
        const { buffer } = streamParser.process(chunk)

        // 实时更新当前章节内容 - 只要 draft
        const draftMatch = buffer.match(/<draft>([\s\S]*?)(?:<\/draft>|$)/)
        if (draftMatch) {
          section.generatedContent = draftMatch[1].trim()
        } else if (!buffer.includes('<thinking>') && buffer.length > 50) {
          // fallback: 如果 AI 没吐格式，且吐了一定长度了，则认为是直接内容
          section.generatedContent = buffer
        }

        updateTotalGeneratedContent()
      }, { paradigm })

    } catch (error) {
      console.error('Section generation failed:', error)
      section.generatedContent = `[生成失败: ${error.message}]`
    } finally {
      section.isGenerating = false
    }
  }

  /**
   * 将所有章节内容合并到主预览区
   */
  const updateTotalGeneratedContent = () => {
    const fullContent = paradigmWriterState.value.sections
      .map(s => {
        const titlePrefix = s.type === 'h2' ? '## ' : '### '
        return `${titlePrefix}${s.title}\n\n${s.generatedContent}`
      })
      .join('\n\n')

    generatedContent.value = fullContent
  }

  return {
    // 状态
    currentPage,
    apiUrl,
    apiKey,
    inputTask,
    inputType,
    outlinePoints,
    references,
    selectedTags,
    customConstraint,
    activeParadigm,
    expertGuidelines,
    qualityReport,
    isGenerating,
    isDeepMode,
    generationStage,
    generatedContent,
    thinkingContent,
    rawStreamBuffer,
    analysisText,
    analysisResult,
    isAnalyzing,
    styleAnalysis,
    currentDocument,
    showPromptDebug,
    showRefInput,
    newRefTitle,
    newRefContent,

    // 模型配置
    selectedProviderId,
    currentProvider,

    // 范式写作
    paradigmWriterState,
    loadParadigmForWriting,
    generateSectionContentAction,
    updateTotalGeneratedContent,

    // 范式编辑
    paradigmEditState,

    // 方法
    switchPage,
    setCurrentPage,
    setCurrentDocument,
    addReferenceFromAnalysis,
    generateContentAction,
    analyzeArticleAction,
    loadParadigmPreset,
    clearParadigm,
    callApi
  }
})
