/**
 * Hash utilities for document identification
 */

/**
 * Compute a fast, non-cryptographic content fingerprint for an ArrayBuffer.
 *
 * This is NOT a cryptographic hash (not MD5/SHA): it samples the bytes and
 * combines them with the file size. It is used only for deduplicating detected
 * PDFs, never for security. Returns a `${sizeHex}-${hashHex}` fingerprint.
 */
export async function computeContentFingerprint(data: ArrayBuffer): Promise<string> {
  const bytes = new Uint8Array(data);

  // Sample bytes (not the full buffer) and fold them together for speed.
  let hash = 0;
  const sampleSize = Math.min(bytes.length, 10000); // Sample first 10KB
  const step = Math.max(1, Math.floor(bytes.length / sampleSize));

  for (let i = 0; i < bytes.length; i += step) {
    hash = ((hash << 5) - hash + bytes[i]) | 0;
  }

  // Include file size in hash for better uniqueness
  const sizeHash = bytes.length.toString(16);
  const contentHash = (hash >>> 0).toString(16).padStart(8, '0');

  return `${sizeHash}-${contentHash}`;
}

/**
 * Generate a unique document ID from filename and content hash
 */
export function generateDocumentId(filename: string, contentHash: string): string {
  return `${filename}:${contentHash}`;
}
