// ============================================
// 素材库 - 可引用的政策文件、讲话、案例等
// ============================================
// 这些是"弹药"，可以根据写作需要动态注入到Prompt中

// 素材类型枚举
export const REFERENCE_TYPES = {
  POLICY: 'policy',       // 政策文件
  SPEECH: 'speech',       // 领导讲话
  CASE: 'case',           // 典型案例
  DATA: 'data',           // 数据统计
  QUOTE: 'quote',         // 金句警句
  REGULATION: 'regulation' // 党规党纪
}

// 素材库
export const REFERENCES = {
  // ==================== 政策文件 ====================
  'policy-20th-4th': {
    id: 'policy-20th-4th',
    type: REFERENCE_TYPES.POLICY,
    title: '二十届四中全会精神',
    source: '中国共产党第二十届中央委员会第四次全体会议公报',
    date: '2024-07',
    tags: ['全面深化改革', '中国式现代化', '制度建设'],
    // 可引用的关键段落
    excerpts: [
      {
        id: 'excerpt-1',
        topic: '改革总目标',
        content: '进一步全面深化改革的总目标是继续完善和发展中国特色社会主义制度，推进国家治理体系和治理能力现代化。',
        applicableDimensions: ['political-loyalty', 'thought']
      },
      {
        id: 'excerpt-2',
        topic: '党的领导',
        content: '坚持党中央对进一步全面深化改革的集中统一领导，深刻领悟"两个确立"的决定性意义，增强"四个意识"、坚定"四个自信"、做到"两个维护"。',
        applicableDimensions: ['political-loyalty', 'party-nature']
      }
    ],
    // 关联的维度集
    relatedDimensionSets: ['five-leads', 'five-roots']
  },

  'policy-discipline-education': {
    id: 'policy-discipline-education',
    type: REFERENCE_TYPES.POLICY,
    title: '党纪学习教育',
    source: '中共中央办公厅关于在全党开展党纪学习教育的通知',
    date: '2024-04',
    tags: ['党纪学习', '纪律建设', '从严治党'],
    excerpts: [
      {
        id: 'excerpt-1',
        topic: '学习重点',
        content: '以学习贯彻《中国共产党纪律处分条例》为重点，教育引导党员干部学纪、知纪、明纪、守纪。',
        applicableDimensions: ['discipline', 'party-governance']
      },
      {
        id: 'excerpt-2',
        topic: '目标要求',
        content: '搞清楚党的纪律规矩是什么，弄明白能干什么、不能干什么，把遵规守纪刻印在心，内化为言行准则。',
        applicableDimensions: ['discipline', 'reverence']
      }
    ],
    relatedDimensionSets: ['five-leads', 'five-roots']
  },

  // ==================== 领导讲话 ====================
  'speech-strictparty': {
    id: 'speech-strictparty',
    type: REFERENCE_TYPES.SPEECH,
    title: '全面从严治党重要论述',
    source: '习近平总书记系列重要讲话',
    tags: ['从严治党', '党的建设', '自我革命'],
    excerpts: [
      {
        id: 'excerpt-1',
        topic: '自我革命',
        content: '勇于自我革命，是我们党最鲜明的品格，也是我们党最大的优势。',
        applicableDimensions: ['party-nature', 'party-governance']
      },
      {
        id: 'excerpt-2',
        topic: '作风建设',
        content: '作风问题本质上是党性问题，抓作风建设，就要返璞归真、固本培元，重点突出坚定理想信念、践行根本宗旨、加强道德修养。',
        applicableDimensions: ['style', 'party-nature']
      },
      {
        id: 'excerpt-3',
        topic: '政绩观',
        content: '树立和践行正确政绩观，起决定性作用的是党性。只有党性坚强、摒弃私心杂念，才能保证政绩观不出偏差。',
        applicableDimensions: ['responsibility', 'party-nature']
      }
    ],
    relatedDimensionSets: ['five-leads', 'five-roots']
  },

  'speech-investigation': {
    id: 'speech-investigation',
    type: REFERENCE_TYPES.SPEECH,
    title: '调查研究重要论述',
    source: '习近平总书记关于调查研究的重要讲话',
    tags: ['调查研究', '作风建设', '实事求是'],
    excerpts: [
      {
        id: 'excerpt-1',
        topic: '调研方法',
        content: '调查研究是谋事之基、成事之道，没有调查就没有发言权，没有调查就没有决策权。',
        applicableDimensions: ['style', 'capability']
      },
      {
        id: 'excerpt-2',
        topic: '四下基层',
        content: '要大力弘扬"四下基层"优良传统，推动各级干部深入基层、深入实际、深入群众。',
        applicableDimensions: ['reverence', 'style']
      }
    ],
    relatedDimensionSets: ['five-leads']
  },

  // ==================== 典型案例 ====================
  'case-formalism': {
    id: 'case-formalism',
    type: REFERENCE_TYPES.CASE,
    title: '形式主义典型案例',
    source: '中央纪委国家监委通报',
    tags: ['形式主义', '官僚主义', '作风问题'],
    excerpts: [
      {
        id: 'excerpt-1',
        topic: '文山会海',
        content: '某地区层层加码开会发文，基层干部疲于应付，大量时间消耗在文来文往、会来会往中，真正用于服务群众的时间被严重挤压。',
        applicableDimensions: ['style', 'party-governance'],
        useFor: 'negative' // 反面案例
      },
      {
        id: 'excerpt-2',
        topic: '痕迹管理',
        content: '某单位过度强调工作留痕，要求拍照打卡、层层签字，基层干部戏称"工作没干完，材料摞成山"，重"痕"不重"绩"。',
        applicableDimensions: ['style'],
        useFor: 'negative'
      }
    ],
    relatedDimensionSets: ['five-roots']
  },

  'case-responsibility': {
    id: 'case-responsibility',
    type: REFERENCE_TYPES.CASE,
    title: '担当作为典型案例',
    source: '先进典型事迹汇编',
    tags: ['担当作为', '攻坚克难', '先进典型'],
    excerpts: [
      {
        id: 'excerpt-1',
        topic: '攻坚克难',
        content: '某同志面对历史遗留的信访积案，不推诿、不绕道，主动担责、迎难而上，经过三个月的艰苦努力，成功化解了长达十年的矛盾纠纷。',
        applicableDimensions: ['responsibility'],
        useFor: 'positive' // 正面案例
      }
    ],
    relatedDimensionSets: ['five-leads']
  },

  // ==================== 金句警句 ====================
  'quote-party-spirit': {
    id: 'quote-party-spirit',
    type: REFERENCE_TYPES.QUOTE,
    title: '党性修养金句',
    tags: ['党性', '修养', '自省'],
    excerpts: [
      {
        id: 'excerpt-1',
        topic: '总开关',
        content: '世界观、人生观、价值观是"总开关"，拧紧了这个"总开关"，才能把准政治方向。',
        applicableDimensions: ['thought', 'party-nature']
      },
      {
        id: 'excerpt-2',
        topic: '初心使命',
        content: '走得再远、走到再光辉的未来，也不能忘记走过的过去，不能忘记为什么出发。',
        applicableDimensions: ['party-nature', 'original-mission']
      },
      {
        id: 'excerpt-3',
        topic: '敬畏之心',
        content: '心有所畏，方能言有所戒、行有所止。',
        applicableDimensions: ['reverence', 'discipline']
      }
    ],
    relatedDimensionSets: ['five-leads', 'five-roots', 'four-contrasts']
  },

  // ==================== 党规党纪 ====================
  'regulation-discipline': {
    id: 'regulation-discipline',
    type: REFERENCE_TYPES.REGULATION,
    title: '《中国共产党纪律处分条例》要点',
    source: '2024年修订版',
    date: '2024-01',
    tags: ['纪律处分', '六大纪律', '底线红线'],
    excerpts: [
      {
        id: 'excerpt-1',
        topic: '政治纪律',
        content: '对党不忠诚不老实，表里不一，阳奉阴违，欺上瞒下，搞两面派，做两面人的，给予警告或者严重警告处分。',
        applicableDimensions: ['political-loyalty', 'discipline']
      },
      {
        id: 'excerpt-2',
        topic: '工作纪律',
        content: '工作中不负责任或者疏于管理，贯彻执行、检查督促落实上级决策部署不力的，给予警告或者严重警告处分。',
        applicableDimensions: ['responsibility', 'party-governance']
      }
    ],
    relatedDimensionSets: ['five-roots', 'five-leads']
  }
}

// ============================================
// 素材库工具函数
// ============================================

/**
 * 获取所有素材列表
 */
export const getReferenceList = () => {
  return Object.values(REFERENCES).map(ref => ({
    id: ref.id,
    type: ref.type,
    title: ref.title,
    source: ref.source,
    tags: ref.tags,
    excerptCount: ref.excerpts?.length || 0
  }))
}

/**
 * 根据ID获取素材
 */
export const getReferenceById = (id) => {
  return REFERENCES[id] || null
}

/**
 * 根据类型筛选素材
 */
export const getReferencesByType = (type) => {
  return Object.values(REFERENCES).filter(ref => ref.type === type)
}

/**
 * 根据标签筛选素材
 */
export const getReferencesByTag = (tag) => {
  return Object.values(REFERENCES).filter(ref => ref.tags?.includes(tag))
}

/**
 * 根据维度ID获取相关素材
 * @param {string} dimensionId - 维度ID
 * @returns {Array} 包含相关素材段落的数组
 */
export const getReferencesByDimension = (dimensionId) => {
  const results = []
  
  Object.values(REFERENCES).forEach(ref => {
    ref.excerpts?.forEach(excerpt => {
      if (excerpt.applicableDimensions?.includes(dimensionId)) {
        results.push({
          referenceId: ref.id,
          referenceTitle: ref.title,
          referenceType: ref.type,
          source: ref.source,
          ...excerpt
        })
      }
    })
  })
  
  return results
}

/**
 * 根据维度集获取所有相关素材
 * @param {string} dimensionSetId - 维度集ID
 * @returns {Array} 素材列表
 */
export const getReferencesByDimensionSet = (dimensionSetId) => {
  return Object.values(REFERENCES).filter(ref => 
    ref.relatedDimensionSets?.includes(dimensionSetId)
  )
}

/**
 * 格式化素材为Prompt文本
 * @param {Array} references - 素材ID数组或素材对象数组
 * @param {Object} options - 配置选项
 * @returns {string} 格式化后的Prompt片段
 */
export const formatReferencesForPrompt = (references, options = {}) => {
  const { 
    includeSource = true,
    groupByType = false,
    maxExcerpts = 5
  } = options
  
  let prompt = ''
  let excerptCount = 0
  
  // 处理输入：支持ID数组或对象数组
  const refObjects = references.map(ref => 
    typeof ref === 'string' ? getReferenceById(ref) : ref
  ).filter(Boolean)
  
  if (refObjects.length === 0) return ''
  
  prompt += `\n## 可引用素材\n`
  prompt += `以下素材可在写作中自然引用或化用：\n\n`
  
  refObjects.forEach(ref => {
    if (excerptCount >= maxExcerpts) return
    
    ref.excerpts?.forEach(excerpt => {
      if (excerptCount >= maxExcerpts) return
      
      prompt += `### ${excerpt.topic}\n`
      if (includeSource) {
        prompt += `> 来源：${ref.title}（${ref.source || ''}）\n`
      }
      prompt += `> "${excerpt.content}"\n`
      if (excerpt.useFor) {
        prompt += `> 【${excerpt.useFor === 'positive' ? '正面案例' : '反面案例'}】\n`
      }
      prompt += '\n'
      excerptCount++
    })
  })
  
  prompt += `**引用要求**：自然融入行文，不可生硬堆砌；可适当改写，保留核心要义。\n\n`
  
  return prompt
}

/**
 * 智能匹配素材（根据维度自动推荐）
 * @param {Array} dimensions - 维度配置数组
 * @param {number} maxPerDimension - 每个维度最多推荐数量
 * @returns {Array} 推荐的素材段落
 */
export const autoMatchReferences = (dimensions, maxPerDimension = 2) => {
  const results = []
  const usedExcerptIds = new Set()
  
  dimensions.forEach(dim => {
    const dimRefs = getReferencesByDimension(dim.id)
    let count = 0
    
    dimRefs.forEach(ref => {
      if (count >= maxPerDimension) return
      if (usedExcerptIds.has(ref.id)) return
      
      results.push({
        dimensionId: dim.id,
        dimensionName: dim.name,
        ...ref
      })
      usedExcerptIds.add(ref.id)
      count++
    })
  })
  
  return results
}

/**
 * 获取素材类型的中文名称
 */
export const getReferenceTypeName = (type) => {
  const names = {
    [REFERENCE_TYPES.POLICY]: '政策文件',
    [REFERENCE_TYPES.SPEECH]: '领导讲话',
    [REFERENCE_TYPES.CASE]: '典型案例',
    [REFERENCE_TYPES.DATA]: '数据统计',
    [REFERENCE_TYPES.QUOTE]: '金句警句',
    [REFERENCE_TYPES.REGULATION]: '党规党纪'
  }
  return names[type] || '其他'
}
