import type {
  SmartContextRequest,
  SmartContextResponse,
  UpdateSmartContextParams,
  ContextSnippet,
  RollingSummary,
} from "../ipc_types";

export class SmartContextStore {
  private contextCache = new Map<number, SmartContextResponse>();
  private maxContextSize = 100000; // 100k characters
  private maxSnippets = 50;
  private summaryThreshold = 20000; // Summarize when context exceeds this

  async getContext(request: SmartContextRequest): Promise<SmartContextResponse> {
    const cached = this.contextCache.get(request.chatId);
    if (cached && !this.isStale(cached)) {
      return cached;
    }

    // Build fresh context
    const context = await this.buildContext(request);
    this.contextCache.set(request.chatId, context);
    return context;
  }

  async updateContext(params: UpdateSmartContextParams): Promise<void> {
    const current = this.contextCache.get(params.chatId) || {
      snippets: [],
      rollingSummary: null,
      totalSize: 0,
      lastUpdated: Date.now(),
    };

    // Add new snippet
    const snippet: ContextSnippet = {
      id: Date.now().toString(),
      content: params.content,
      type: params.type || "message",
      timestamp: Date.now(),
      importance: params.importance || 1.0,
    };

    current.snippets.push(snippet);
    current.lastUpdated = Date.now();

    // Manage context size
    await this.manageContextSize(current, params.chatId);
    
    this.contextCache.set(params.chatId, current);
  }

  async clearContext(chatId: number): Promise<void> {
    this.contextCache.delete(chatId);
  }

  async getContextStats(chatId: number): Promise<{
    snippetCount: number;
    totalSize: number;
    hasSummary: boolean;
  }> {
    const context = this.contextCache.get(chatId);
    if (!context) {
      return { snippetCount: 0, totalSize: 0, hasSummary: false };
    }

    return {
      snippetCount: context.snippets.length,
      totalSize: context.totalSize,
      hasSummary: !!context.rollingSummary,
    };
  }

  private async buildContext(request: SmartContextRequest): Promise<SmartContextResponse> {
    // This would integrate with the actual chat system
    // For now, return empty context
    return {
      snippets: [],
      rollingSummary: null,
      totalSize: 0,
      lastUpdated: Date.now(),
    };
  }

  private isStale(context: SmartContextResponse): boolean {
    const maxAge = 30 * 60 * 1000; // 30 minutes
    return Date.now() - context.lastUpdated > maxAge;
  }

  private async manageContextSize(context: SmartContextResponse, chatId: number): Promise<void> {
    context.totalSize = context.snippets.reduce((sum, snippet) => sum + snippet.content.length, 0);

    // If we exceed the threshold, create summary
    if (context.totalSize > this.summaryThreshold && !context.rollingSummary) {
      await this.createRollingSummary(context);
    }

    // If we still exceed max size, remove old snippets
    if (context.totalSize > this.maxContextSize) {
      await this.trimOldSnippets(context);
    }
  }

  private async createRollingSummary(context: SmartContextResponse): Promise<void> {
    // This would integrate with AI to create summaries
    // For now, create a simple summary
    const oldSnippets = context.snippets.slice(0, -10); // Keep last 10 snippets
    const summaryContent = `Summary of ${oldSnippets.length} previous messages...`;
    
    context.rollingSummary = {
      content: summaryContent,
      createdAt: Date.now(),
      snippetCount: oldSnippets.length,
    };
    
    // Remove summarized snippets
    context.snippets = context.snippets.slice(-10);
  }

  private async trimOldSnippets(context: SmartContextResponse): Promise<void> {
    // Sort by importance and timestamp, keep the best ones
    context.snippets.sort((a, b) => {
      const scoreA = a.importance * (Date.now() - a.timestamp);
      const scoreB = b.importance * (Date.now() - b.timestamp);
      return scoreB - scoreA;
    });

    context.snippets = context.snippets.slice(0, this.maxSnippets);
  }
}
