import { invoke } from '@tauri-apps/api/core'
import type {
  KnowledgeRecord,
  KnowledgeEventRecord,
  KnowledgeDetailPayload,
  CreateKnowledgeInput,
  KnowledgeSearchInput,
  UpdateKnowledgeInput,
  KnowledgeConfig,
} from './types'

export const knowledgeApi = {
  /** 列出知识(可按 status 筛选,默认排除 archived) */
  list(status?: string | null): Promise<KnowledgeRecord[]> {
    return invoke('knowledge_list', { status: status ?? null })
  },

  /** 单条查询 */
  get(id: string): Promise<KnowledgeRecord> {
    return invoke('knowledge_get', { id })
  },

  /** 检索知识(top-N,默认 3) */
  search(input: KnowledgeSearchInput): Promise<KnowledgeRecord[]> {
    return invoke('knowledge_search', { input })
  },

  /** 创建知识(始终 candidate 状态) */
  create(input: CreateKnowledgeInput): Promise<KnowledgeRecord> {
    return invoke('knowledge_create', { input })
  },

  /** 状态转换(含合法矩阵校验) */
  updateStatus(id: string, status: string): Promise<boolean> {
    return invoke('knowledge_update_status', { id, status })
  },

  /** 复用计数 +1 */
  recordReuse(id: string): Promise<boolean> {
    return invoke('knowledge_record_reuse', { id })
  },

  /** 审核收件箱(候选列表,按置信度排序) */
  listCandidates(): Promise<KnowledgeRecord[]> {
    return invoke('knowledge_list_candidates')
  },

  /** 归档(软删除) */
  archive(id: string): Promise<boolean> {
    return invoke('knowledge_archive', { id })
  },

  /** 读取知识库行为配置 */
  getConfig(): Promise<KnowledgeConfig> {
    return invoke('knowledge_get_config')
  },

  /** 保存知识库行为配置 */
  saveConfig(config: KnowledgeConfig): Promise<boolean> {
    return invoke('knowledge_save_config', { config })
  },

  /** 手动触发提炼 */
  extractNow(): Promise<boolean> {
    return invoke('knowledge_extract_now')
  },

  /** 知识详情(基本信息 + 生命线事件) */
  getDetail(id: string): Promise<KnowledgeDetailPayload> {
    return invoke('knowledge_get_detail', { id })
  },

  /** 编辑知识(部分更新) */
  update(id: string, input: UpdateKnowledgeInput): Promise<KnowledgeRecord> {
    return invoke('knowledge_update', { id, input })
  },

  /** 查询生命线事件(可按 event_type 过滤) */
  events(knowledgeId: string, eventType?: string, limit?: number): Promise<KnowledgeEventRecord[]> {
    return invoke('knowledge_events', { knowledgeId, eventType: eventType ?? null, limit: limit ?? null })
  },
}
