import { refreshMappingsForNode, extractTemplateVariables } from '../utils/ioInference'

/**
 * 节点字段编辑 composable
 * 抽取自 WorkflowEditor.vue，承担各类节点（LLM/Agent/Skill/Condition/Output/UserInput）的字段增删改
 *
 * @param {Object} options
 * @param {import('vue').Ref} options.selectedNode 当前选中节点 ref
 * @param {import('vue').ComputedRef} options.selectedData 当前选中节点的 data 计算属性
 * @param {Function} options.vfUpdateNode 更新节点数据的 VueFlow API
 * @param {Function} options.getNodes 获取所有节点
 * @param {Function} options.getEdges 获取所有边
 * @param {Function} options.applyEdgeMappingUpdates 批量应用边映射更新的回调
 * @param {Object} options.skillStore 技能 store（用于根据 ID 找技能的 IO 字段）
 * @param {Function} options.agentOptions 智能体选项（含技能映射）
 * @param {import('vue').Ref} [options.skillsRef] 全量技能列表 ref（可选，用于绕过 store 分页）
 */
export function useNodeFields({
  selectedNode, selectedData, vfUpdateNode,
  getNodes, getEdges, applyEdgeMappingUpdates,
  skillStore, agentOptions, skillsRef
}) {
  /**
   * 同步 selectedNode 引用，并刷新选中节点的边映射
   */
  function syncSelectedNode() {
    selectedNode.value = getNodes().value.find(n => n.id === selectedNode.value.id) || selectedNode.value
    applyEdgeMappingUpdates(refreshMappingsForNode(selectedNode.value.id, getNodes().value, getEdges().value))
  }

  // ========== 通用字段更新 ==========
  function onFieldChange(field, value) {
    if (!selectedNode.value) return
    const update = { [field]: value }
    // 特殊处理：智能体/技能选择时同步名称和 IO 字段
    if (field === 'agentId' || field === 'skillId') {
      const opts = typeof agentOptions === 'function' ? agentOptions() : agentOptions.value
      const opt = opts.find(o => o.value === value)
      if (field === 'agentId') update.agentName = opt ? opt.label : ''
      else update.skillName = opt ? opt.label : ''
      const skill = (skillsRef?.value || skillStore?.skills || []).find(s => s.folderName === value)
      update.inputs = (skill?.inputs || []).map(f => ({ ...f, mapping: f.mapping ?? null }))
      update.outputs = (skill?.outputs || []).map(f => ({ ...f, mapping: f.mapping ?? null }))
    }
    // 模板字段变更：实时同步 inputs（追加新变量，不删除已有字段）
    if (['systemPrompt', 'userPrompt', 'actionPrompt', 'query'].includes(field)) {
      syncInputsFromTemplate(update)
    }
    vfUpdateNode(selectedNode.value.id, update)
    syncSelectedNode()
  }

  function onModelChange(modelId, dbModels) {
    if (!selectedNode.value) return
    const models = Array.isArray(dbModels)
      ? dbModels
      : (typeof dbModels === 'function' ? dbModels() : dbModels?.value)
    // 统一按数值处理 modelId，避免 n-select 返回值类型（string/number）不一致导致不回显
    const normalizedModelId = modelId == null || modelId === '' ? null : Number(modelId)
    const model = (models || []).find(m => m.id === normalizedModelId)
    const update = { modelId: normalizedModelId }
    update.modelName = model ? `${model.name} (${model.modelName})` : null
    vfUpdateNode(selectedNode.value.id, update)
    syncSelectedNode()
  }

  // ========== 模板变量 → inputs 实时同步 ==========
  // 根据节点类型从对应模板字段提取 {{变量名}}，追加到 inputs（不删除已有字段）
  // 用于：LLM（systemPrompt + userPrompt）、SmartAction（actionPrompt）、KnowledgeRetrieval（query）、Condition（conditions[].expression）
  function syncInputsFromTemplate(update) {
    if (!selectedNode.value) return
    // 合并 update 中的最新值，避免读 selectedData 时落后一个字符
    const d = { ...(selectedData.value || {}), ...update }
    const type = selectedNode.value.type

    const texts = []
    if (type === 'llm') {
      texts.push(d.systemPrompt || '', d.userPrompt || '')
    } else if (type === 'smartAction') {
      texts.push(d.actionPrompt || '')
    } else if (type === 'knowledgeRetrieval') {
      texts.push(d.query || '')
    } else if (type === 'condition') {
      for (const c of (d.conditions || [])) texts.push(c.expression || '')
    } else {
      return
    }

    const extracted = new Set()
    for (const t of texts) {
      for (const v of extractTemplateVariables(t)) extracted.add(v)
    }

    // 模板变量动态同步：区分手动字段与自动字段，删除已不在模板中的自动字段，
    // 避免在 {{}} 中缓慢输入 abc 时同时残留 a、ab、abc 三个变量
    const existing = update.inputs || d.inputs || []
    const manualInputs = existing.filter(f => !f.autoTemplate)
    const autoInputs = existing.filter(f => f.autoTemplate)
    const manualNames = new Set(manualInputs.map(f => f.name))

    const newAutoInputs = []
    for (const name of extracted) {
      if (manualNames.has(name)) continue
      const existingAuto = autoInputs.find(f => f.name === name)
      if (existingAuto) {
        newAutoInputs.push(existingAuto)
      } else {
        newAutoInputs.push({ name, label: name, type: 'string', description: '', required: false, mapping: null, autoTemplate: true })
      }
    }

    const merged = [...manualInputs, ...newAutoInputs]
    const oldNames = existing.map(f => f.name).join('\n')
    const newNames = merged.map(f => f.name).join('\n')
    if (oldNames !== newNames) {
      update.inputs = merged
    }
  }

  // ========== 通用字段增删（适用于 LLM/Agent/Skill/Condition 的 inputs/outputs 列表） ==========
  function addListField(field) {
    if (!selectedData.value) return
    const list = [...(selectedData.value[field] || []), { name: '', label: '', type: 'string', description: '', required: false, mapping: null }]
    vfUpdateNode(selectedNode.value.id, { [field]: list })
    syncSelectedNode()
  }

  function removeListField(field, index) {
    const removedName = selectedData.value?.[field]?.[index]?.name
    const list = (selectedData.value?.[field] || []).filter((_, i) => i !== index)
    vfUpdateNode(selectedNode.value.id, { [field]: list })
    if (field === 'outputs' && removedName) {
      revertSuccessorMappings(selectedNode.value.id, removedName)
    }
    syncSelectedNode()
  }

  // ========== UserInput 变量操作 ==========
  function addVariable() {
    if (!selectedData.value) return
    const newVars = [...(selectedData.value.variables || []), { name: '', label: '', type: 'string', description: '', required: false }]
    vfUpdateNode(selectedNode.value.id, { variables: newVars })
    syncSelectedNode()
  }

  function removeVariable(index) {
    const removedName = selectedData.value?.variables?.[index]?.name
    const newVars = (selectedData.value?.variables || []).filter((_, i) => i !== index)
    vfUpdateNode(selectedNode.value.id, { variables: newVars })
    if (removedName) {
      revertSuccessorMappings(selectedNode.value.id, removedName)
    }
    syncSelectedNode()
  }

  // ========== Output 节点字段操作 ==========
  function addOutputField() {
    if (!selectedData.value) return
    const newFields = [...(selectedData.value.fields || []), { name: '', label: '', type: 'string', description: '', required: false }]
    vfUpdateNode(selectedNode.value.id, { fields: newFields })
    syncSelectedNode()
  }

  function removeOutputField(index) {
    const newFields = (selectedData.value?.fields || []).filter((_, i) => i !== index)
    vfUpdateNode(selectedNode.value.id, { fields: newFields })
    syncSelectedNode()
  }

  // ========== Condition 节点条件操作 ==========
  function addElif() {
    if (!selectedData.value?.conditions) return
    const newConditions = [...selectedData.value.conditions, { type: 'ELIF', expression: '' }]
    vfUpdateNode(selectedNode.value.id, { conditions: newConditions })
    syncSelectedNode()
  }

  function removeElif(index) {
    if (!selectedData.value?.conditions) return
    const newConditions = selectedData.value.conditions.filter((_, i) => i !== index)
    vfUpdateNode(selectedNode.value.id, { conditions: newConditions })
    syncSelectedNode()
  }

  function onConditionChange(index, field, value) {
    if (!selectedData.value?.conditions) return
    const newConditions = selectedData.value.conditions.map((c, i) =>
      i === index ? { ...c, [field]: value } : c
    )
    const update = { conditions: newConditions }
    // 条件表达式变更时实时同步 inputs
    if (field === 'expression') {
      syncInputsFromTemplate(update)
    }
    vfUpdateNode(selectedNode.value.id, update)
    syncSelectedNode()
  }

  // ========== 前驱节点变量删除后，后继节点关联回退为自动推断 ==========
  function revertSuccessorMappings(sourceNodeId, sourceFieldName = null) {
    const affectedNodeIds = []
    for (const node of getNodes().value) {
      if (node.id === sourceNodeId) continue
      const update = {}

      // 普通节点的 inputs
      const inputs = node.data?.inputs || []
      let inputsChanged = false
      const newInputs = inputs.map(inp => {
        if (inp.mapping?.sourceNodeId === sourceNodeId) {
          if (sourceFieldName === null || inp.mapping.sourceField === sourceFieldName) {
            inputsChanged = true
            return { ...inp, mapping: null }
          }
        }
        return inp
      })
      if (inputsChanged) update.inputs = newInputs

      // 输出节点的 fields（接收字段也可关联前驱输出）
      const fields = node.data?.fields || []
      let fieldsChanged = false
      const newFields = fields.map(f => {
        if (f.mapping?.sourceNodeId === sourceNodeId) {
          if (sourceFieldName === null || f.mapping.sourceField === sourceFieldName) {
            fieldsChanged = true
            return { ...f, mapping: null }
          }
        }
        return f
      })
      if (fieldsChanged) update.fields = newFields

      if (Object.keys(update).length) {
        vfUpdateNode(node.id, update)
        affectedNodeIds.push(node.id)
      }
    }
    for (const nodeId of affectedNodeIds) {
      applyEdgeMappingUpdates(refreshMappingsForNode(nodeId, getNodes().value, getEdges().value))
    }
  }

  return {
    onFieldChange,
    onModelChange,
    addListField,
    removeListField,
    addVariable,
    removeVariable,
    addOutputField,
    removeOutputField,
    addElif,
    removeElif,
    onConditionChange,
    revertSuccessorMappings
  }
}
