<template>
  <section class="panel">
    <div class="panel-header">
      <h2>{{ $t('settings.panelKnowledge') }}</h2>
    </div>
    <div class="general-settings">
      <div class="setting-row">
        <div class="setting-info">
          <span class="setting-label">{{ $t('settings.labelAutoExtract') }}</span>
          <span class="setting-desc">{{ $t('settings.descAutoExtract') }}</span>
        </div>
        <div class="setting-control">
          <label class="toggle">
            <input type="checkbox" v-model="knowledgeConfig.auto_extract" />
            <span class="toggle-slider"></span>
          </label>
        </div>
      </div>
      <div class="setting-row">
        <div class="setting-info">
          <span class="setting-label">{{ $t('settings.labelTriggerMode') }}</span>
          <span class="setting-desc">{{ $t('settings.descTriggerMode') }}</span>
        </div>
        <div class="setting-control">
          <select v-model="knowledgeConfig.trigger_mode" class="setting-select">
            <option value="on_complete">{{ $t('settings.triggerOnComplete') }}</option>
            <option value="on_idle">{{ $t('settings.triggerOnIdle') }}</option>
            <option value="manual_only">{{ $t('settings.triggerManualOnly') }}</option>
          </select>
        </div>
      </div>
      <div class="setting-row">
        <div class="setting-info">
          <span class="setting-label">{{ $t('settings.labelMinMessages') }}</span>
          <span class="setting-desc">{{ $t('settings.descMinMessages') }}</span>
        </div>
        <div class="setting-control">
          <input type="number" min="2" max="50" v-model.number="knowledgeConfig.min_messages" class="setting-select" style="width:80px" />
        </div>
      </div>
      <div class="setting-row">
        <div class="setting-info">
          <span class="setting-label">{{ $t('settings.labelIdleTimeout') }}</span>
          <span class="setting-desc">{{ $t('settings.descIdleTimeout') }}</span>
        </div>
        <div class="setting-control">
          <input type="number" min="5" max="600" :value="Math.round(knowledgeConfig.idle_timeout_ms / 1000)" @input="knowledgeConfig.idle_timeout_ms = ($event.target as HTMLInputElement).valueAsNumber * 1000 || 30000" class="setting-select" style="width:80px" />
        </div>
      </div>
      <div class="setting-row">
        <div class="setting-info">
          <span class="setting-label">{{ $t('settings.labelAutoInject') }}</span>
          <span class="setting-desc">{{ $t('settings.descAutoInject') }}</span>
        </div>
        <div class="setting-control">
          <label class="toggle">
            <input type="checkbox" v-model="knowledgeConfig.auto_inject" />
            <span class="toggle-slider"></span>
          </label>
        </div>
      </div>
      <div class="setting-row">
        <div class="setting-info">
          <span class="setting-label">{{ $t('settings.labelVectorEnabled') }}</span>
          <span class="setting-desc">{{ $t('settings.descVectorEnabled') }}</span>
        </div>
        <div class="setting-control">
          <label class="toggle">
            <input type="checkbox" v-model="knowledgeConfig.vector_enabled" />
            <span class="toggle-slider"></span>
          </label>
        </div>
      </div>
      <div class="setting-row" v-if="knowledgeConfig.vector_enabled">
        <div class="setting-info">
          <span class="setting-label">{{ $t('settings.labelEmbeddingProvider') }}</span>
          <span class="setting-desc">{{ $t('settings.descEmbeddingProvider') }}</span>
        </div>
        <div class="setting-control">
          <select v-model="knowledgeConfig.embedding_provider_id" class="setting-select">
            <option :value="null">{{ $t('settings.embeddingProviderNone') }}</option>
            <option v-for="p in embeddingProviders" :key="p.id" :value="p.id">{{ p.name }}</option>
          </select>
        </div>
      </div>
      <div class="setting-row" v-if="knowledgeConfig.vector_enabled">
        <div class="setting-info">
          <span class="setting-label">{{ $t('settings.labelEmbeddingModel') }}</span>
          <span class="setting-desc">{{ $t('settings.descEmbeddingModel') }}</span>
        </div>
        <div class="setting-control">
          <input type="text" :value="knowledgeConfig.embedding_model ?? ''" @input="knowledgeConfig.embedding_model = ($event.target as HTMLInputElement).value || null" class="setting-select" :placeholder="$t('settings.phEmbeddingModel')" style="width:220px" />
        </div>
      </div>
    </div>
  </section>
</template>

<script setup lang="ts">
import { reactive, computed, watch, onMounted, onUnmounted } from 'vue'
import { knowledgeApi } from '@/api'
import type { AiProviderConfig } from '@/api/types'

// ============================================================
// 知识库配置域(提取 + 注入) — 走后端 IPC,非 localStorage
// ============================================================
const props = defineProps<{
  /** Provider 列表(embedding provider 下拉依赖,由 ProviderPanel 上抛同步) */
  aiProviders: AiProviderConfig[]
}>()

const knowledgeConfig = reactive({
  loaded: false,
  auto_extract: true,
  trigger_mode: 'on_complete' as 'on_complete' | 'on_idle' | 'manual_only',
  min_messages: 4,
  idle_timeout_ms: 30000,
  auto_inject: true,
  vector_enabled: false,
  embedding_provider_id: null as string | null,
  embedding_model: null as string | null,
})

// 可做 embedding 的 provider(仅 openai_compat,Anthropic 无 embed API)
const embeddingProviders = computed(() =>
  props.aiProviders.filter(p => p.provider_type !== 'anthropic')
)

async function loadKnowledgeConfig() {
  try {
    const cfg = await knowledgeApi.getConfig()
    Object.assign(knowledgeConfig, cfg)
    knowledgeConfig.loaded = true
  } catch (e) {
    console.error('加载知识库配置失败:', e)
  }
}

let _knowledgeSaveTimer: ReturnType<typeof setTimeout> | null = null
function saveKnowledgeConfigDebounced() {
  if (_knowledgeSaveTimer) clearTimeout(_knowledgeSaveTimer)
  _knowledgeSaveTimer = setTimeout(async () => {
    try {
      const { loaded, ...cfg } = knowledgeConfig
      void loaded
      await knowledgeApi.saveConfig(cfg as any)
    } catch (e) {
      console.error('保存知识库配置失败:', e)
    }
  }, 500)
}

watch(
  () => ({ ...knowledgeConfig }),
  () => {
    if (knowledgeConfig.loaded) saveKnowledgeConfigDebounced()
  },
  { deep: true },
)

onMounted(() => {
  loadKnowledgeConfig()
})

// 组件卸载清 debounce timer,防 unmount 后旧 timer 仍 fire 写已销毁 reactive(timer 泄漏 FR-C3)
onUnmounted(() => {
  if (_knowledgeSaveTimer) clearTimeout(_knowledgeSaveTimer)
})
</script>

<style scoped>
/* ===== 面板容器(原 Settings.vue 抽出,各子组件自持 scoped 副本) ===== */
.panel {
  background: var(--df-bg-card);
  border: 0.5px solid var(--df-border);
  border-radius: var(--df-radius-lg);
  padding: var(--df-pad-panel);
}
.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: var(--df-gap-head);
}
.panel-header h2 { font-size: 15px; font-weight: 500; }

/* ===== 通用设置行(Knowledge 复用 setting-row 布局) ===== */
.general-settings { display: flex; flex-direction: column; }
.setting-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 14px 0;
  border-bottom: 0.5px solid var(--df-border);
}
.setting-row:last-child { border-bottom: none; }
.setting-info { display: flex; flex-direction: column; gap: 2px; }
.setting-label { font-size: 14px; font-weight: 500; color: var(--df-text); }
.setting-desc { font-size: 12px; color: var(--df-text-dim); }

.setting-control { display: flex; align-items: center; }

.setting-select { padding: 6px 12px; background: var(--df-bg); border: 0.5px solid var(--df-border); border-radius: var(--df-radius-sm); color: var(--df-text); font-size: 13px; outline: none; cursor: pointer; min-width: 160px; }
.setting-select:focus { border-color: var(--df-accent); }

/* Toggle */
.toggle { position: relative; display: inline-block; width: 40px; height: 22px; cursor: pointer; }
.toggle input { opacity: 0; width: 0; height: 0; }
.toggle-slider { position: absolute; top: 0; left: 0; right: 0; bottom: 0; background: var(--df-border); border-radius: var(--df-radius-lg); transition: background 0.2s; }
.toggle-slider::before { content: ''; position: absolute; width: 16px; height: 16px; left: 3px; bottom: 3px; background: var(--df-text-dim); border-radius: 50%; transition: transform 0.2s, background 0.2s; }
.toggle input:checked + .toggle-slider { background: var(--df-accent); }
.toggle input:checked + .toggle-slider::before { transform: translateX(18px); background: #fff; }
</style>
