<template>
  <n-space>
    <n-button type="success" :disabled="executing" @click="handleExecute" v-if="!isNew">
      <template #icon>
        <n-icon><Icon icon="tabler:play" /></n-icon>
      </template>
      {{ executing ? t('Executing...') : t('Execute') }}
    </n-button>
    <n-button type="info" @click="handleFlowBuilder">
      <template #icon>
        <n-icon><Icon icon="lucide:workflow" /></n-icon>
      </template>
      {{ t('Flow Builder') }}
    </n-button>
  </n-space>
  
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { NSpace, NButton, NIcon, useMessage } from 'naive-ui'
import { Icon } from '@iconify/vue'

const props = defineProps<{ context: {
  entity: any
  id: any
  record: any
  canEdit: any
  loading: any
  save: () => Promise<void> | void
  router: any
  t: (k: string) => string
} }>()

const message = useMessage()
const executing = ref(false)

const t = props.context.t
const isNew = computed(() => String(props.context.id?.value || props.context.id) === 'new')

async function handleExecute() {
  if (isNew.value) return
  try {
    executing.value = true
    const id = String(props.context.id?.value || props.context.id)
    const name = props.context.record?.value?.agent_name || props.context.record?.agent_name || ''
    const response = await fetch('/jingrow/agents/execute', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        agent_id: id,
        agent_name: name,
        session_cookie: document.cookie.split('; ').find(row => row.startsWith('sid='))?.split('=')[1]
      })
    })
    const result = await response.json()
    if (result.success) {
      message.success(t('Agent execution started successfully'))
    } else {
      message.error(result.message || t('Execution failed'))
    }
  } catch (e: any) {
    message.error(e?.message || t('Execution failed'))
  } finally {
    executing.value = false
  }
}

async function handleFlowBuilder() {
  try {
    const raw = props.context.record?.value?.agent_flow ?? props.context.record?.agent_flow ?? {}
    let flowData: any = raw
    if (typeof raw === 'string') {
      try { flowData = JSON.parse(raw) } catch { flowData = {} }
    }
    const agentId = props.context.record?.value?.name || props.context.record?.name || ''
    
    const { useFlowBuilderStore } = await import('@/shared/stores/flowBuilder')
    const flowBuilderStore = useFlowBuilderStore()
    
    flowBuilderStore.activateFlowBuilder(flowData, agentId)
    
    props.context.router.push({ name: 'FlowBuilder', query: { agentId } })
  } catch (_) {}
}

const canEdit = computed(() => !!(props.context.canEdit?.value ?? props.context.canEdit))
const loading = computed(() => !!(props.context.loading?.value ?? props.context.loading))

</script>

<style scoped>
</style>


