<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import AppShell from '@/layouts/AppShell.vue'
import AgentKindForm from '@/components/acp/AgentKindForm.vue'
import AgentConfigFilesPanel from '@/components/acp/AgentConfigFilesPanel.vue'
import { useAcpStore } from '@/stores/acp'
import { useAlert } from '@/composables/useAlert'
import type { AgentClientType, McpServerSpec, UpdateAgentKindReq } from '@/api/acp'

const route = useRoute()
const router = useRouter()
const store = useAcpStore()
const alert = useAlert()

function goBack() {
  router.push('/admin/acp/agent-kinds')
}

const id = computed(() => (route.params.id as string | undefined) ?? null)
const isEdit = computed(() => id.value !== null)

const form = ref({
  name: '',
  display_name: '',
  description: '',
  binary_path: '',
  args: [] as string[],
  env: {} as Record<string, string>,
  enabled: true,
  tool_allowlist: [] as string[],
  client_type: 'generic' as AgentClientType,
  mcp_servers: [] as McpServerSpec[],
})
const existingEnvKeys = ref<string[]>([])

onMounted(async () => {
  if (isEdit.value && id.value) {
    const k = await store.getAgentKind(id.value)
    form.value = {
      name: k.name,
      display_name: k.display_name,
      description: k.description,
      binary_path: k.binary_path,
      args: [...k.args],
      env: {}, // Edit mode: do not prefill values; user must replace entirely if they want to change.
      enabled: k.enabled,
      tool_allowlist: [...(k.tool_allowlist ?? [])],
      client_type: k.client_type ?? 'generic',
      mcp_servers: [...(k.mcp_servers ?? [])],
    }
    existingEnvKeys.value = [...k.env_keys]
  }
})

async function submit() {
  try {
    if (isEdit.value && id.value) {
      const req: UpdateAgentKindReq = {
        display_name: form.value.display_name,
        description: form.value.description,
        binary_path: form.value.binary_path,
        args: form.value.args,
        enabled: form.value.enabled,
        tool_allowlist: form.value.tool_allowlist,
        client_type: form.value.client_type,
        // mcp_servers 与 env 不同：编辑页有完整回显，整体替换语义安全。
        mcp_servers: form.value.mcp_servers,
      }
      // Only send env if user actually entered some values; an empty map would
      // wipe existing env on the backend (per service patch semantics).
      if (Object.keys(form.value.env).length > 0) req.env = form.value.env
      await store.updateAgentKind(id.value, req)
    } else {
      await store.createAgentKind({
        name: form.value.name,
        display_name: form.value.display_name,
        description: form.value.description,
        binary_path: form.value.binary_path,
        args: form.value.args,
        env: form.value.env,
        enabled: form.value.enabled,
        tool_allowlist: form.value.tool_allowlist,
        client_type: form.value.client_type,
        mcp_servers: form.value.mcp_servers,
      })
    }
    goBack()
  } catch (e) {
    alert(`Save failed: ${e instanceof Error ? e.message : 'unknown'}`)
  }
}
</script>

<template>
  <AppShell>
    <div class="p-6 max-w-2xl">
      <h1 class="text-2xl font-semibold mb-4">
        {{ isEdit ? 'Edit Agent Kind' : 'New Agent Kind' }}
      </h1>
      <AgentKindForm
        v-model="form"
        :is-edit="isEdit"
        :existing-env-keys="existingEnvKeys"
        @submit="submit"
        @cancel="goBack"
      />
      <div v-if="isEdit && id" class="mt-8">
        <AgentConfigFilesPanel :kind-id="id" :client-type="form.client_type" />
      </div>
      <p v-else class="text-xs text-gray-500 mt-6">
        保存后可在编辑页配置该客户端的配置文件（settings.json / config.toml 等）
      </p>
    </div>
  </AppShell>
</template>
