<script setup lang="ts">
import type { SpanInputsOutputs, Message } from '@/types/trace'
import NodeMessage from './NodeMessage.vue'
import DataBlock from './DataBlock.vue'

const props = defineProps<{
  data: SpanInputsOutputs | undefined
}>()

function shouldUseNodeMessage(message: Message): boolean {
  const hasContent = message.text || message.content
  const isMemoryFragment = message.role === 'memoryFragment'
  return Boolean(hasContent) && !isMemoryFragment
}
</script>

<template>
  <div class="grid grid-cols-[auto_1fr_auto] gap-x-3 gap-y-1 items-start">
    <!-- Completion query messages -->
    <template v-if="data?.messages?.length">
      <template v-for="(message, index) in data.messages" :key="index">
        <NodeMessage
          v-if="shouldUseNodeMessage(message)"
          :role="message.role"
          :content="message.text || message.content || ''"
        />
        <DataBlock v-else :label="message.role" :data="message" />
      </template>
    </template>

    <!-- Single text (embedding input / LLM response text) -->
    <NodeMessage v-if="data?.text" role="text" :content="data.text" />

    <!-- PII guardrail checked text -->
    <NodeMessage v-if="data?.checkedText" role="input" :content="data.checkedText" />

    <!-- Tool execution input -->
    <NodeMessage
      v-if="data?.input !== undefined && typeof data.input === 'string'"
      role="input"
      :content="data.input"
    />
    <DataBlock v-else-if="data?.input !== undefined" label="input" :data="data.input" />

    <!-- Reranking query -->
    <DataBlock v-if="data?.query" label="input" :data="data.query" />

    <!-- LLM response tool calls -->
    <DataBlock v-if="data?.toolCalls?.length" label="tool" :data="data.toolCalls" />

    <!-- Tool validation requests -->
    <DataBlock
      v-if="data?.toolValidationRequests?.length"
      label="tool"
      :data="data.toolValidationRequests"
    />

    <!-- Tool execution output -->
    <NodeMessage
      v-if="data?.output !== undefined && typeof data.output === 'string'"
      role="output"
      :content="data.output as string"
    />
    <DataBlock v-else-if="data?.output !== undefined" label="output" :data="data.output" />

    <!-- Tool execution error -->
    <NodeMessage v-if="data?.error" role="error" :content="data.error" />

    <!-- Tool execution sources -->
    <DataBlock v-if="data?.sources?.length" label="sources" :data="data.sources" />

    <!-- Tool execution artifacts -->
    <DataBlock v-if="data?.artifacts?.length" label="artifacts" :data="data.artifacts" />

    <!-- PII detection results -->
    <DataBlock
      v-if="data?.detectedEntities?.length"
      label="detectedEntities"
      :data="data.detectedEntities"
    />

    <!-- Memory fragment -->
    <DataBlock v-if="data?.memoryFragment" label="memoryFragment" :data="data.memoryFragment" />
  </div>
</template>
