import { create } from 'zustand';
import type { KnowledgeBase, Document } from '../api/knowledgeBaseApi';
import { knowledgeBaseApi, documentApi } from '../api/knowledgeBaseApi';

interface KnowledgeBaseState {
  // 知识库列表
  knowledgeBases: KnowledgeBase[];
  currentKb: KnowledgeBase | null;
  
  // 文档列表
  documents: Document[];
  
  // 加载状态
  loading: boolean;
  error: string | null;
  
  // 操作方法
  fetchKnowledgeBases: () => Promise<void>;
  fetchKnowledgeBaseById: (id: string) => Promise<void>;
  createKnowledgeBase: (name: string, description?: string) => Promise<KnowledgeBase>;
  updateKnowledgeBase: (id: string, name?: string, description?: string) => Promise<void>;
  deleteKnowledgeBase: (id: string) => Promise<void>;
  
  // 文档操作
  fetchDocuments: (kbId: string) => Promise<void>;
  uploadDocument: (kbId: string, file: File, onProgress?: (progress: number) => void) => Promise<Document>;
  deleteDocument: (id: string) => Promise<void>;
  reprocessDocument: (id: string) => Promise<void>;
  
  // 辅助方法
  setCurrentKb: (kb: KnowledgeBase | null) => void;
  clearError: () => void;
}

export const useKnowledgeBaseStore = create<KnowledgeBaseState>((set, get) => ({
  knowledgeBases: [],
  currentKb: null,
  documents: [],
  loading: false,
  error: null,

  // 获取知识库列表
  fetchKnowledgeBases: async () => {
    set({ loading: true, error: null });
    try {
      const knowledgeBases = await knowledgeBaseApi.getList();
      set({ knowledgeBases, loading: false });
    } catch (error: any) {
      set({ 
        error: error.response?.data?.message || '获取知识库列表失败', 
        loading: false 
      });
    }
  },

  // 获取知识库详情
  fetchKnowledgeBaseById: async (id: string) => {
    set({ loading: true, error: null });
    try {
      const kb = await knowledgeBaseApi.getById(id);
      set({ currentKb: kb, loading: false });
      
      // 同时获取文档列表
      if (kb.id) {
        await get().fetchDocuments(kb.id);
      }
    } catch (error: any) {
      set({ 
        error: error.response?.data?.message || '获取知识库详情失败', 
        loading: false 
      });
    }
  },

  // 创建知识库
  createKnowledgeBase: async (name: string, description?: string) => {
    set({ loading: true, error: null });
    try {
      const kb = await knowledgeBaseApi.create({ name, description });
      
      // 更新列表
      const knowledgeBases = [...get().knowledgeBases, kb];
      set({ knowledgeBases, loading: false });
      
      return kb;
    } catch (error: any) {
      const errorMsg = error.response?.data?.message || '创建知识库失败';
      set({ error: errorMsg, loading: false });
      throw new Error(errorMsg);
    }
  },

  // 更新知识库
  updateKnowledgeBase: async (id: string, name?: string, description?: string) => {
    set({ loading: true, error: null });
    try {
      const updatedKb = await knowledgeBaseApi.update(id, { name, description });
      
      // 更新列表
      const knowledgeBases = get().knowledgeBases.map(kb => 
        kb.id === id ? updatedKb : kb
      );
      
      // 更新当前知识库
      const currentKb = get().currentKb?.id === id ? updatedKb : get().currentKb;
      
      set({ knowledgeBases, currentKb, loading: false });
    } catch (error: any) {
      set({ 
        error: error.response?.data?.message || '更新知识库失败', 
        loading: false 
      });
      throw error;
    }
  },

  // 删除知识库
  deleteKnowledgeBase: async (id: string) => {
    set({ loading: true, error: null });
    try {
      await knowledgeBaseApi.delete(id);
      
      // 更新列表
      const knowledgeBases = get().knowledgeBases.filter(kb => kb.id !== id);
      
      // 清除当前知识库（如果是被删除的）
      const currentKb = get().currentKb?.id === id ? null : get().currentKb;
      
      set({ knowledgeBases, currentKb, loading: false });
    } catch (error: any) {
      set({ 
        error: error.response?.data?.message || '删除知识库失败', 
        loading: false 
      });
      throw error;
    }
  },

  // 获取文档列表
  fetchDocuments: async (kbId: string) => {
    try {
      const documents = await documentApi.getList(kbId);
      set({ documents });
    } catch (error: any) {
      set({ 
        error: error.response?.data?.message || '获取文档列表失败'
      });
    }
  },

  // 上传文档
  uploadDocument: async (kbId: string, file: File, onProgress?: (progress: number) => void) => {
    set({ loading: true, error: null });
    try {
      const document = await documentApi.upload(kbId, file, onProgress);
      
      // 更新文档列表
      const documents = [document, ...get().documents];
      set({ documents, loading: false });
      
      return document;
    } catch (error: any) {
      const errorMsg = error.response?.data?.message || '上传文档失败';
      set({ error: errorMsg, loading: false });
      throw new Error(errorMsg);
    }
  },

  // 删除文档
  deleteDocument: async (id: string) => {
    set({ loading: true, error: null });
    try {
      await documentApi.delete(id);
      
      // 更新文档列表
      const documents = get().documents.filter(doc => doc.id !== id);
      set({ documents, loading: false });
    } catch (error: any) {
      set({ 
        error: error.response?.data?.message || '删除文档失败', 
        loading: false 
      });
      throw error;
    }
  },

  // 重新处理文档
  reprocessDocument: async (id: string) => {
    set({ loading: true, error: null });
    try {
      await documentApi.reprocess(id);
      
      // 更新文档状态
      const documents = get().documents.map(doc => 
        doc.id === id ? { ...doc, status: 'parsing' as const, progress: 0 } : doc
      );
      set({ documents, loading: false });
    } catch (error: any) {
      set({ 
        error: error.response?.data?.message || '重新处理文档失败', 
        loading: false 
      });
      throw error;
    }
  },

  // 设置当前知识库
  setCurrentKb: (kb: KnowledgeBase | null) => {
    set({ currentKb: kb });
  },

  // 清除错误
  clearError: () => {
    set({ error: null });
  },
}));


