import { ref } from 'vue'
import { addNode, addEdge, updateNode } from '@/stores/canvas'

const WORKFLOW_TYPES = {
  TEXT_TO_IMAGE: 'text_to_image',
  TEXT_TO_IMAGE_TO_VIDEO: 'text_to_image_to_video',
  STORYBOARD: 'storyboard'
}

export const useWorkflowOrchestrator = () => {
  const isAnalyzing = ref(false)
  const isExecuting = ref(false)
  const currentStep = ref(0)
  const totalSteps = ref(0)
  const executionLog = ref([])

  const addLog = (type, message) => {
    executionLog.value.push({ type, message, timestamp: Date.now() })
  }

  const analyzeIntent = async (userInput) => {
    const text = String(userInput || '')
    const wantsVideo = /视频|动起来|镜头|运动|video|motion/i.test(text)
    return {
      workflow_type: wantsVideo ? WORKFLOW_TYPES.TEXT_TO_IMAGE_TO_VIDEO : WORKFLOW_TYPES.TEXT_TO_IMAGE,
      description: wantsVideo ? 'SKG 文生视频' : 'SKG 文生图',
      image_prompt: text,
      video_prompt: text
    }
  }

  const executeWorkflow = async (params, position = { x: 100, y: 100 }) => {
    isExecuting.value = true
    currentStep.value = 1
    totalSteps.value = params.workflow_type === WORKFLOW_TYPES.TEXT_TO_IMAGE_TO_VIDEO ? 3 : 2
    try {
      const textId = addNode('text', position, {
        label: '提示词',
        content: params.image_prompt || params.video_prompt || ''
      })
      if (params.workflow_type === WORKFLOW_TYPES.TEXT_TO_IMAGE_TO_VIDEO) {
        const videoConfigId = addNode('videoConfig', { x: position.x + 400, y: position.y }, {
          label: '文生视频',
          autoExecute: true
        })
        addEdge({ source: textId, target: videoConfigId, sourceHandle: 'right', targetHandle: 'left', type: 'promptOrder', data: { promptOrder: 1 } })
        updateNode(videoConfigId, { autoExecute: true })
      } else {
        const imageConfigId = addNode('imageConfig', { x: position.x + 400, y: position.y }, {
          label: '文生图',
          autoExecute: true
        })
        addEdge({ source: textId, target: imageConfigId, sourceHandle: 'right', targetHandle: 'left', type: 'promptOrder', data: { promptOrder: 1 } })
        updateNode(imageConfigId, { autoExecute: true })
      }
      addLog('success', 'SKG 工作流已启动')
    } finally {
      isExecuting.value = false
    }
  }

  const createTextToImageWorkflow = (imagePrompt, position) => executeWorkflow({
    workflow_type: WORKFLOW_TYPES.TEXT_TO_IMAGE,
    image_prompt: imagePrompt
  }, position)

  const createMultiAngleStoryboard = (characterDescription, position) => executeWorkflow({
    workflow_type: WORKFLOW_TYPES.STORYBOARD,
    image_prompt: `SKG 多角度营销分镜，主体要求：${characterDescription || '保持主体和产品一致'}`
  }, position)

  return {
    isAnalyzing,
    isExecuting,
    currentStep,
    totalSteps,
    executionLog,
    analyzeIntent,
    executeWorkflow,
    createTextToImageWorkflow,
    createMultiAngleStoryboard,
    WORKFLOW_TYPES
  }
}

export default useWorkflowOrchestrator
