<script setup lang="ts">
/* eslint-disable vue/no-mutating-props */
import type {AgentOption, AgentToolBinding} from '../types';

import {ElButton, ElForm, ElFormItem, ElInput, ElOption, ElSelect, ElSwitch,} from 'element-plus';

const props = defineProps<{
  binding: AgentToolBinding;
  kind: 'plugin' | 'workflow';
  options: AgentOption[];
}>();

const emit = defineEmits<{
  change: [];
  remove: [];
}>();

const SAFE_TOOL_NAME_PATTERN = /^[a-zA-Z0-9_-]+$/;

function isSafeToolName(name?: string) {
  return SAFE_TOOL_NAME_PATTERN.test(String(name || ''));
}

function resolveToolName(option?: AgentOption) {
  const raw = option?.raw || {};
  if (isSafeToolName(raw.englishName)) {
    return String(raw.englishName);
  }
  if (isSafeToolName(raw.name)) {
    return String(raw.name);
  }
  const prefix = props.kind === 'workflow' ? 'workflow' : 'plugin';
  return `${prefix}_${option?.value || Date.now()}`;
}

function shouldSyncToolName() {
  const name = String(props.binding.toolName || '');
  if (!name) return true;
  const prefix = props.kind === 'workflow' ? 'workflow_' : 'plugin_';
  return name.startsWith(prefix);
}

function handleTargetChange(value: string) {
  const option = props.options.find(
    (item) => String(item.value) === String(value),
  );
  props.binding.resourceSummary = option?.raw || {};
  if (shouldSyncToolName()) {
    props.binding.toolName = resolveToolName(option);
  }
  emit('change');
}
</script>

<template>
  <ElForm label-position="top" class="agent-form">
    <ElFormItem :label="kind === 'workflow' ? '工作流' : '插件工具'" required>
      <ElSelect
        v-model="binding.targetId"
        filterable
        placeholder="选择资源"
        @change="handleTargetChange"
      >
        <ElOption
          v-for="item in options"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </ElSelect>
    </ElFormItem>
    <ElFormItem label="工具名称" required>
      <ElInput
        v-model="binding.toolName"
        placeholder="仅支持英文、数字、下划线或中划线"
        @input="emit('change')"
      />
    </ElFormItem>
    <ElFormItem label="执行前确认">
      <ElSwitch v-model="binding.hitlEnabled" @change="emit('change')" />
    </ElFormItem>
    <ElButton
      class="agent-form__danger"
      type="danger"
      plain
      @click="emit('remove')"
    >
      删除节点
    </ElButton>
  </ElForm>
</template>

<style scoped>
.agent-form {
  padding: 16px;
}

.agent-form :deep(.el-select) {
  width: 100%;
}

.agent-form__danger {
  width: 100%;
  margin-top: 8px;
}
</style>
