/**
 * knowledge_store.js — 知识库存储层（纯 IndexedDB）
 *
 * 零后端、零配置、打开即用。
 * 片段数据结构：{ id, name, description, content, source, createdAt }
 *
 * 存储：IndexedDB "AISCKnowledgeBase"，object store "segments"
 * 容量：可用磁盘空间的 50%（几百 MB 没问题）
 */

class KnowledgeStore {
  constructor() {
    this._dbName = 'AISCKnowledgeBase';
    this._storeName = 'segments';
    this._dbInstance = null; // 缓存 DB 实例
  }

  // ===== IndexedDB 基础操作 =====

  /** 打开/复用 DB 连接 */
  async _db() {
    if (this._dbInstance) return this._dbInstance;
    return new Promise((resolve, reject) => {
      const req = indexedDB.open(this._dbName, 1);
      req.onupgradeneeded = () => {
        const db = req.result;
        if (!db.objectStoreNames.contains(this._storeName)) {
          const store = db.createObjectStore(this._storeName, { keyPath: 'id' });
          store.createIndex('source', 'source', { unique: false });
          store.createIndex('createdAt', 'createdAt', { unique: false });
        }
      };
      req.onsuccess = () => {
        this._dbInstance = req.result;
        resolve(this._dbInstance);
      };
      req.onerror = () => reject(req.error);
    });
  }

  /** 获取一个读写事务的 store */
  async _store(mode) {
    const db = await this._db();
    return db.transaction(this._storeName, mode).objectStore(this._storeName);
  }

  // ===== 初始化（永远返回 true，因为 IndexedDB 无需配置） =====

  async init() {
    await this._db(); // 确保 DB 就绪
    return true;
  }

  isConfigured() { return true; }

  async getStats() {
    const store = await this._store('readonly');
    return new Promise((resolve) => {
      const req = store.count();
      req.onsuccess = () => {
        resolve({ total: req.result, ready: true });
      };
      req.onerror = () => resolve({ total: 0, ready: true });
    });
  }

  // ===== 片段写入 =====

  /**
   * 写入多个片段
   * @param {Array<{name, description, content}>} segments
   * @param {string} sourceFile
   * @returns {number}
   */
  async writeSegments(segments, sourceFile) {
    const db = await this._db();
    const now = new Date().toISOString();
    const fileId = Date.now().toString(36);
    let count = 0;

    return new Promise((resolve, reject) => {
      const tx = db.transaction(this._storeName, 'readwrite');
      const store = tx.objectStore(this._storeName);

      for (let i = 0; i < segments.length; i++) {
        const seg = segments[i];
        const record = {
          id: 'seg_' + fileId + '_' + (i + 1),
          name: seg.name || ('片段' + (i + 1)),
          description: seg.description || '',
          content: seg.content || '',
          source: sourceFile,
          createdAt: now
        };
        store.put(record);
        count++;
      }

      tx.oncomplete = () => resolve(count);
      tx.onerror = () => reject(tx.error);
    });
  }

  // ===== 片段读取 =====

  /** 列出所有片段（不含 content，节省内存） */
  async listSegments() {
    const db = await this._db();
    return new Promise((resolve, reject) => {
      const tx = db.transaction(this._storeName, 'readonly');
      const store = tx.objectStore(this._storeName);
      const req = store.getAll();
      req.onsuccess = () => {
        // 返回元信息列表（不返回 content 大段文本）
        const list = req.result.map(r => ({
          id: r.id,
          name: r.name,
          description: r.description,
          source: r.source,
          createdAt: r.createdAt,
          contentLength: (r.content || '').length
        }));
        resolve(list);
      };
      req.onerror = () => reject(req.error);
    });
  }

  /** 读取单个片段完整内容 */
  async readSegment(id) {
    const store = await this._store('readonly');
    return new Promise((resolve, reject) => {
      const req = store.get(id);
      req.onsuccess = () => resolve(req.result || null);
      req.onerror = () => reject(req.error);
    });
  }

  // ===== 搜索 =====

  /**
   * 关键词搜索
   * @param {string} query
   * @param {number} maxResults
   * @returns {Promise<Array<{id, name, description, content, source}>>}
   */
  async search(query, maxResults = 3) {
    if (!query) return [];

    // 分词
    const keywords = query.toLowerCase()
      .replace(/[^\u4e00-\u9fa5a-zA-Z0-9]/g, ' ')
      .split(/\s+/)
      .filter(w => w.length > 1);
    if (keywords.length === 0) return [];

    // 全量读取，打分
    const db = await this._db();
    const all = await new Promise((resolve, reject) => {
      const req = db.transaction(this._storeName, 'readonly')
        .objectStore(this._storeName).getAll();
      req.onsuccess = () => resolve(req.result);
      req.onerror = () => reject(req.error);
    });

    const scored = all.map(seg => {
      const text = (seg.name + ' ' + seg.description + ' ' + seg.content).toLowerCase();
      let score = 0;
      keywords.forEach(kw => {
        // 统计每个关键词出现次数
        let idx = 0, count = 0;
        while ((idx = text.indexOf(kw, idx)) !== -1) { count++; idx += kw.length; }
        score += count;
      });
      return { ...seg, score };
    }).filter(s => s.score > 0).sort((a, b) => b.score - a.score);

    return scored.slice(0, maxResults).map(s => ({
      id: s.id,
      name: s.name,
      description: s.description,
      content: s.content,
      source: s.source
    }));
  }

  // ===== 删除 =====

  /** 删除单个片段 */
  async deleteSegment(id) {
    const store = await this._store('readwrite');
    return new Promise((resolve, reject) => {
      const req = store.delete(id);
      req.onsuccess = () => resolve();
      req.onerror = () => reject(req.error);
    });
  }

  /** 删除某个来源的所有片段 */
  async deleteBySource(sourceFile) {
    const db = await this._db();
    return new Promise((resolve, reject) => {
      const tx = db.transaction(this._storeName, 'readwrite');
      const store = tx.objectStore(this._storeName);
      const index = store.index('source');
      const req = index.openCursor(IDBKeyRange.only(sourceFile));
      let count = 0;
      req.onsuccess = (e) => {
        const cursor = e.target.result;
        if (cursor) {
          cursor.delete();
          count++;
          cursor.continue();
        }
      };
      tx.oncomplete = () => resolve(count);
      tx.onerror = () => reject(tx.error);
    });
  }

  /** 清空全部 */
  async clearAll() {
    const store = await this._store('readwrite');
    return new Promise((resolve, reject) => {
      const req = store.clear();
      req.onsuccess = () => resolve();
      req.onerror = () => reject(req.error);
    });
  }
}

// 全局单例
window.knowledgeStore = new KnowledgeStore();
