import { hashText, normalizeText } from "../shared/hash";
import type { InferenceResult } from "../shared/types";

const DEFAULT_MAX_SIZE = 5_000;

export class ResultCache {
  private readonly values = new Map<string, InferenceResult>();

  constructor(private readonly maxSize = DEFAULT_MAX_SIZE) {
    if (!Number.isInteger(maxSize) || maxSize < 1) {
      throw new Error("Result cache max size must be a positive integer");
    }
  }

  get(text: string): InferenceResult | undefined {
    return this.values.get(hashText(text));
  }

  set(text: string, result: InferenceResult): void {
    this.values.set(hashText(normalizeText(text)), result);
    if (this.values.size > this.maxSize) {
      const oldest = this.values.keys().next().value;
      if (oldest !== undefined) this.values.delete(oldest);
    }
  }

  clear(): void {
    this.values.clear();
  }

  get size(): number {
    return this.values.size;
  }
}
