<script setup lang="ts">
import { ref, watch, computed } from 'vue'
import { Panel, GraphRenderer } from 'mpr-ui-framework'
import type { GraphNode, GraphMode, DataSource } from 'mpr-ui-framework'
import { usePipelineStore } from '../stores/pipeline'
import { useStageRegistry } from '../composables/useStageRegistry'

const props = defineProps<{
  source: DataSource
  status?: 'idle' | 'live' | 'processing' | 'error'
}>()

const pipeline = usePipelineStore()
const { stageNames, editableStages } = useStageRegistry()

const nodes = ref<GraphNode[]>([])

// Derive graph mode from pipeline layout mode
const graphMode = computed<GraphMode>(() => {
  if (pipeline.layoutMode === 'bbox_editor') return 'edit-isolated'
  if (pipeline.layoutMode === 'stage_editor') return 'edit-in-pipeline'
  return 'observe'
})

// Initialize nodes from registry when it loads
watch(stageNames, (names) => {
  if (names.length > 0 && nodes.value.length === 0) {
    nodes.value = names.map((id) => ({ id, status: 'pending' }))
  }
}, { immediate: true })

props.source.on<{ nodes: GraphNode[] }>('graph_update', (e) => {
  nodes.value = e.nodes
})

props.source.on<{ report?: { status?: string } }>('job_complete', (e) => {
  const status = e.report?.status
  if (status === 'failed' || status === 'cancelled') {
    nodes.value = nodes.value.map(n => ({
      ...n,
      status: n.status === 'running' ? 'error' : n.status,
    }))
  } else {
    nodes.value = nodes.value.map(n => ({
      ...n,
      status: n.status === 'running' ? 'done' : n.status,
    }))
  }
})

function onOpenRegionEditor(stage: string) {
  pipeline.openBBoxEditor(stage)
}

function onOpenStageEditor(stage: string) {
  pipeline.openStageEditor(stage)
}
</script>

<template>
  <Panel title="Pipeline" :status="status">
    <GraphRenderer
      :nodes="nodes"
      :mode="graphMode"
      :active-stage="pipeline.editorStage"
      :region-stages="editableStages"
      @open-region-editor="onOpenRegionEditor"
      @open-stage-editor="onOpenStageEditor"
    />
  </Panel>
</template>
