<script setup lang="ts">
import { computed } from 'vue'
import type { PermissionRequest } from '@/api/acp'

const props = defineProps<{
  requests: PermissionRequest[]
  canDecide: boolean
}>()

const emit = defineEmits<{
  approve: [reqID: string, optionId?: string]
  deny: [reqID: string]
}>()

const list = computed(() => props.requests)

// allowOptions 过滤出“批准”类选项，作为可点击的批准按钮；其余统一走 Deny。
function allowOptions(r: PermissionRequest) {
  return r.options.filter((o) => {
    const id = o.id.toLowerCase()
    return id.includes('allow') || id.includes('yes') || id.includes('approve') || id.includes('accept')
  })
}

function summarize(toolCall: unknown): string {
  try {
    return JSON.stringify(toolCall)
  } catch {
    return ''
  }
}
</script>

<template>
  <div
    v-if="list.length"
    class="border-b bg-amber-50 px-4 py-3 space-y-3"
  >
    <div class="text-sm font-semibold text-amber-800">
      待审批的工具调用（{{ list.length }}）
    </div>
    <div
      v-for="r in list"
      :key="r.id"
      class="rounded border border-amber-300 bg-white px-3 py-2"
    >
      <div class="flex items-center justify-between gap-2">
        <span class="font-mono text-sm">{{ r.tool_name || '(未命名工具)' }}</span>
        <div
          v-if="canDecide"
          class="flex items-center gap-2"
        >
          <template v-if="allowOptions(r).length">
            <button
              v-for="opt in allowOptions(r)"
              :key="opt.id"
              class="px-2 py-1 text-xs rounded border text-green-700 border-green-300 hover:bg-green-50"
              @click="emit('approve', r.id, opt.id)"
            >
              {{ opt.name || opt.id }}
            </button>
          </template>
          <button
            v-else
            class="px-2 py-1 text-xs rounded border text-green-700 border-green-300 hover:bg-green-50"
            @click="emit('approve', r.id)"
          >
            批准
          </button>
          <button
            class="px-2 py-1 text-xs rounded border text-red-600 border-red-300 hover:bg-red-50"
            @click="emit('deny', r.id)"
          >
            拒绝
          </button>
        </div>
        <span
          v-else
          class="text-xs text-gray-400"
        >
          等待 owner 审批…
        </span>
      </div>
      <pre
        class="mt-1 text-xs text-gray-500 whitespace-pre-wrap break-all max-h-24 overflow-y-auto"
      >{{ summarize(r.tool_call) }}</pre>
    </div>
  </div>
</template>
