<template>
  <BaseToolCall :tool-call="toolCall" :hide-params="true">
    <template #header>
      <div class="sep-header">
        <span class="note">Find</span>
        <span class="separator" v-if="resourceName">|</span>
        <span class="description" v-if="resourceName">知识库: {{ resourceName }}</span>
        <span class="separator" v-if="fileId">|</span>
        <span class="description" v-if="fileId">文件: {{ fileId }}</span>
        <span class="tag" v-if="patternsLabel" :title="fullPatternsLabel">{{ patternsLabel }}</span>
      </div>
    </template>

    <template #result="{ resultContent }">
      <KbDocumentPreview
        v-if="isPreviewResult(parsedResult(resultContent))"
        :result="parsedResult(resultContent)"
        mode="find"
      />
      <div v-else class="plain-result">{{ stringifyResult(resultContent) }}</div>
    </template>
  </BaseToolCall>
</template>

<script setup>
import { computed } from 'vue'
import BaseToolCall from '../BaseToolCall.vue'
import KbDocumentPreview from './KbDocumentPreview.vue'
import { useDatabaseStore } from '@/stores/database'

const props = defineProps({
  toolCall: {
    type: Object,
    required: true
  }
})

const databaseStore = useDatabaseStore()

const args = computed(() => {
  const value = props.toolCall.args || props.toolCall.function?.arguments
  if (!value) return {}
  if (typeof value === 'object') return value
  try {
    return JSON.parse(value)
  } catch {
    return {}
  }
})

const resourceName = computed(() => databaseStore.getDatabaseNameById(args.value.kb_id))
const fileId = computed(() => args.value.file_id || '')
const patterns = computed(() => (Array.isArray(args.value.patterns) ? args.value.patterns : []))
const fullPatternsLabel = computed(() => patterns.value.join(', '))
const patternsLabel = computed(() => {
  if (patterns.value.length <= 3) return fullPatternsLabel.value
  return `${patterns.value.slice(0, 3).join(', ')}...`
})

const parsedResult = (content) => {
  if (typeof content !== 'string') return content
  try {
    return JSON.parse(content)
  } catch {
    return content
  }
}

const isPreviewResult = (result) =>
  result && typeof result === 'object' && Array.isArray(result.windows)

const stringifyResult = (content) => {
  const result = parsedResult(content)
  return typeof result === 'string' ? result : JSON.stringify(result, null, 2)
}
</script>

<style scoped lang="less">
.plain-result {
  border: 1px solid var(--gray-150);
  border-radius: 8px;
  padding: 10px 12px;
  color: var(--gray-700);
  font-size: 12px;
  white-space: pre-wrap;
  word-break: break-word;
}
</style>
