// @ts-nocheck
const SEARCH_INITIAL_BATCH = 5000;
const SEARCH_MORE_BATCH = 200;
const SEARCH_PREVIEW_LIMIT = 20;

export const searchMethods = {
  handleSidebarSearchInput(value) {
    this.searchQuery = value;
  },

  handleSidebarSearchSubmit(value) {
    this.searchQuery = value;
    const trimmed = String(value || '').trim();
    if (!trimmed) {
      this.exitConversationSearch();
      return;
    }
    this.startConversationSearch(trimmed);
  },

  exitConversationSearch() {
    this.searchActive = false;
    this.searchInProgress = false;
    this.searchMoreAvailable = false;
    this.searchOffset = 0;
    this.searchTotal = 0;
    this.searchResults = [];
    this.searchActiveQuery = '';
    this.searchResultIdSet = new Set();
    this.conversationsOffset = 0;
    this.loadConversationsList();
  },

  async startConversationSearch(query) {
    const trimmed = String(query || '').trim();
    if (!trimmed) {
      return;
    }
    const requestSeq = ++this.searchRequestSeq;
    this.searchActiveQuery = trimmed;
    this.searchActive = true;
    this.searchInProgress = true;
    this.searchMoreAvailable = false;
    this.searchOffset = 0;
    this.searchTotal = 0;
    this.searchResults = [];
    this.searchResultIdSet = new Set();
    await this.searchNextConversationBatch(SEARCH_INITIAL_BATCH, requestSeq);
  },

  async loadMoreSearchResults() {
    if (!this.searchActive || this.searchInProgress || !this.searchMoreAvailable) {
      return;
    }
    const requestSeq = this.searchRequestSeq;
    this.searchInProgress = true;
    await this.searchNextConversationBatch(SEARCH_MORE_BATCH, requestSeq);
  },

  async searchNextConversationBatch(batchSize, requestSeq) {
    const query = this.searchActiveQuery;
    if (!query) {
      if (requestSeq === this.searchRequestSeq) {
        this.searchInProgress = false;
      }
      return;
    }
    try {
      const response = await fetch(
        `/api/conversations?limit=${batchSize}&offset=${this.searchOffset}`
      );
      const payload = await response.json();

      if (requestSeq !== this.searchRequestSeq) {
        return;
      }

      if (!payload.success) {
        console.error('搜索对话失败:', payload.error || payload.message);
        this.searchInProgress = false;
        return;
      }

      const data = payload.data || {};
      const conversations = data.conversations || [];
      if (!this.searchTotal) {
        this.searchTotal = data.total || 0;
      }

      for (const conv of conversations) {
        if (requestSeq !== this.searchRequestSeq) {
          return;
        }
        await this.matchConversation(conv, query, requestSeq);
      }

      this.searchOffset += conversations.length;
      this.searchMoreAvailable = this.searchOffset < (this.searchTotal || 0);
    } catch (error) {
      console.error('搜索对话异常:', error);
    } finally {
      if (requestSeq === this.searchRequestSeq) {
        this.searchInProgress = false;
      }
    }
  },

  async matchConversation(conversation, query, requestSeq) {
    if (!conversation || !conversation.id) {
      return;
    }
    if (this.searchResultIdSet && this.searchResultIdSet.has(conversation.id)) {
      return;
    }
    const firstSentence = await this.getConversationFirstUserSentence(conversation.id, requestSeq);
    if (requestSeq !== this.searchRequestSeq) {
      return;
    }
    const queryLower = String(query || '').toLowerCase();
    const combined = `${conversation.title || ''} ${firstSentence || ''}`.toLowerCase();
    if (queryLower && combined.includes(queryLower)) {
      this.searchResults.push(conversation);
      this.searchResultIdSet.add(conversation.id);
    }
  },

  async getConversationFirstUserSentence(conversationId, requestSeq) {
    if (!conversationId) {
      return '';
    }
    if (
      this.searchPreviewCache &&
      Object.prototype.hasOwnProperty.call(this.searchPreviewCache, conversationId)
    ) {
      return this.searchPreviewCache[conversationId];
    }
    try {
      const resp = await fetch(
        `/api/conversations/${conversationId}/review_preview?limit=${SEARCH_PREVIEW_LIMIT}`
      );
      const payload = await resp.json();
      if (requestSeq !== this.searchRequestSeq) {
        return '';
      }
      const lines = payload?.data?.preview || [];
      let firstUserLine = '';
      for (const line of lines) {
        if (typeof line === 'string' && line.startsWith('user：')) {
          firstUserLine = line.slice('user：'.length).trim();
          break;
        }
      }
      const firstSentence = this.extractFirstSentence(firstUserLine);
      const cached = firstSentence || firstUserLine || '';
      if (!this.searchPreviewCache) {
        this.searchPreviewCache = {};
      }
      this.searchPreviewCache[conversationId] = cached;
      return cached;
    } catch (error) {
      console.error('获取对话预览失败:', error);
      return '';
    }
  },

  extractFirstSentence(text) {
    if (!text) {
      return '';
    }
    const normalized = String(text).replace(/\s+/g, ' ').trim();
    const match = normalized.match(/(.+?[。！？.!?])/);
    if (match) {
      return match[1];
    }
    return normalized;
  }
};
