import crypto from 'crypto';

/**
 * Compute cache key for live URL generation (Section 8.7)
 *
 * Cache key format: SHA-256 hash of (projectId + scope + prompt + params)
 *
 * @param projectId - Project UUID
 * @param scope - Live scope slug
 * @param prompt - User prompt
 * @param params - Additional generation parameters (aspectRatio, etc.)
 * @returns SHA-256 hash string
 */
export const computeLiveUrlCacheKey = (
  projectId: string,
  scope: string,
  prompt: string,
  params: {
    aspectRatio?: string;
    autoEnhance?: boolean;
    template?: string;
  } = {},
): string => {
  // Normalize parameters to ensure consistent cache keys
  const normalizedParams = {
    aspectRatio: params.aspectRatio || '1:1',
    autoEnhance: params.autoEnhance ?? false,
    template: params.template || 'general',
  };

  // Create cache key string
  const cacheKeyString = [
    projectId,
    scope,
    prompt.trim().toLowerCase(), // Normalize prompt
    normalizedParams.aspectRatio,
    normalizedParams.autoEnhance.toString(),
    normalizedParams.template,
  ].join('::');

  // Compute SHA-256 hash
  return crypto.createHash('sha256').update(cacheKeyString).digest('hex');
};

/**
 * Compute prompt hash for prompt URL cache (Section 5 - already implemented)
 *
 * @param prompt - User prompt
 * @returns SHA-256 hash string
 */
export const computePromptHash = (prompt: string): string => {
  return crypto.createHash('sha256').update(prompt.trim().toLowerCase()).digest('hex');
};
