<template>
  <div class="kb-settings">
    <a-spin :spinning="kbStore.isLoading" tip="加载设置中...">
      <a-form
        v-if="form"
        layout="vertical"
        :model="form"
        :disabled="!canEdit"
      >
        <a-alert
          v-if="!canEdit"
          type="info"
          show-icon
          message="仅 KB 所有者（或管理员）可修改设置"
          description="当前账号为只读权限，以下设置不可编辑。"
          style="margin-bottom: 16px"
        />

        <a-form-item label="检索模式默认">
          <a-select v-model:value="form.default_query_mode">
            <a-select-option value="embedding">语义检索（embedding）</a-select-option>
            <a-select-option value="keywords">关键词检索（keywords）</a-select-option>
            <a-select-option value="blend">混合检索（blend）</a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="命中处理默认">
          <a-select v-model:value="form.default_hit_processing">
            <a-select-option value="model_opt">模型优化（model_opt）</a-select-option>
            <a-select-option value="direct">直接返回（direct）</a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="禁用结果缓存" name="caching_disabled">
          <a-switch v-model:checked="form.caching_disabled" />
          <span class="form-hint">开启后每次检索都重新计算，不读取缓存</span>
        </a-form-item>

        <a-divider orientation="left">Rerank 重排</a-divider>

        <a-form-item label="启用 Rerank" name="rerank_enabled">
          <a-switch v-model:checked="form.rerank_enabled" />
        </a-form-item>

        <template v-if="form.rerank_enabled">
          <a-form-item label="Rerank 提供方">
            <a-select v-model:value="form.rerank_provider">
              <a-select-option value="cohere">Cohere</a-select-option>
              <a-select-option value="bge">BGE</a-select-option>
              <a-select-option value="none">无</a-select-option>
            </a-select>
          </a-form-item>

          <a-form-item v-if="form.rerank_provider !== 'none'" label="Rerank API Key">
            <a-input-password
              v-model:value="rerankApiKey"
              placeholder="留空则不修改"
            />
          </a-form-item>

          <a-form-item v-if="form.rerank_provider !== 'none'" label="Rerank Base URL">
            <a-input
              v-model:value="rerankBaseUrl"
              placeholder="https://api.cohere.ai"
            />
          </a-form-item>

          <a-alert
            v-if="form.rerank_provider !== 'none'"
            type="warning"
            show-icon
            :message="`使用 ${rerankProviderLabel} 处理数据可能涉及数据外发，请确认合规要求`"
            style="margin-bottom: 16px"
          />
        </template>

        <a-divider orientation="left">授权信息</a-divider>

        <a-descriptions :column="1" size="small" bordered>
          <a-descriptions-item label="KB ID">
            {{ form.kb_id }}
          </a-descriptions-item>
          <a-descriptions-item label="所有者">
            <a-tag v-if="form.owner" color="blue">{{ form.owner }}</a-tag>
            <span v-else class="form-hint">未设置（首次保存时绑定当前用户）</span>
          </a-descriptions-item>
        </a-descriptions>

        <a-form-item v-if="canEdit" style="margin-top: 16px">
          <a-space>
            <a-button
              type="primary"
              :loading="kbStore.isSavingSettings"
              @click="handleSave"
            >
              保存设置
            </a-button>
            <a-button @click="handleReset">重置</a-button>
          </a-space>
        </a-form-item>
      </a-form>

      <a-empty
        v-else-if="!kbStore.isLoading"
        description="无法加载 KB 设置"
      />
    </a-spin>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { useKnowledgeStore, DEFAULT_KB_ID } from '@/stores/knowledge'
import { useAuthStore } from '@/stores/auth'
import type { IKBSettings, IKBSettingsUpdate, QueryMode, HitProcessing, RerankProvider } from '@/api/kb'

const kbStore = useKnowledgeStore()
const authStore = useAuthStore()

/** Local editable copy of settings — kept separate from the store snapshot. */
const form = ref<IKBSettings | null>(null)
const rerankApiKey = ref<string>('')
const rerankBaseUrl = ref<string>('')

/**
 * Whether the current user may edit settings.
 *
 * Backend ACL: owner (or admin) can PUT. Before the first save the
 * owner is null and any KB_WRITE user may save (becoming the owner).
 * ponytail: we approximate "can edit" client-side as "has KB_WRITE";
 * the server enforces the real ACL and returns 403 otherwise.
 */
const canEdit = computed(() => authStore.hasPermission('KB_WRITE'))

const rerankProviderLabel = computed(() => {
  switch (form.value?.rerank_provider) {
    case 'cohere':
      return 'Cohere'
    case 'bge':
      return 'BGE'
    default:
      return '云端'
  }
})

function syncFormFromStore(): void {
  if (!kbStore.kbSettings) {
    form.value = null
    return
  }
  // Deep copy so edits don't mutate the store snapshot until save.
  form.value = {
    ...kbStore.kbSettings,
    default_query_mode: kbStore.kbSettings.default_query_mode as QueryMode,
    default_hit_processing: kbStore.kbSettings.default_hit_processing as HitProcessing,
    rerank_provider: kbStore.kbSettings.rerank_provider as RerankProvider,
  }
  // Don't prefill secrets — leave blank; blank = "don't change".
  rerankApiKey.value = ''
  rerankBaseUrl.value = kbStore.kbSettings.rerank_base_url ?? ''
}

watch(() => kbStore.kbSettings, syncFormFromStore, { deep: true })

function handleReset(): void {
  syncFormFromStore()
}

async function handleSave(): Promise<void> {
  if (!form.value) return
  const update: IKBSettingsUpdate = {
    default_query_mode: form.value.default_query_mode,
    default_hit_processing: form.value.default_hit_processing,
    caching_disabled: form.value.caching_disabled,
    rerank_enabled: form.value.rerank_enabled,
    rerank_provider: form.value.rerank_provider,
  }
  // Only send rerank credentials when the user typed something.
  if (form.value.rerank_enabled && form.value.rerank_provider !== 'none') {
    if (rerankApiKey.value) update.rerank_api_key = rerankApiKey.value
    if (rerankBaseUrl.value) update.rerank_base_url = rerankBaseUrl.value
  }
  try {
    await kbStore.saveKbSettings(update, DEFAULT_KB_ID)
    message.success('KB 设置已保存')
  } catch (err) {
    const detail = err instanceof Error ? err.message : '保存 KB 设置失败'
    message.error(detail)
  }
}

onMounted(() => {
  kbStore.fetchKbSettings(DEFAULT_KB_ID)
})
</script>

<style scoped>
.kb-settings {
  padding: 8px 0;
  max-width: 640px;
}

.form-hint {
  margin-left: 12px;
  color: var(--text-placeholder);
  font-size: 12px;
}
</style>
