const TRANSLATE_PIPE_KEY_PATTERN = /['"]([a-z][a-zA-Z0-9_.]*)['"]\s*\|\s*translate/g;
const INSTANT_KEY_PATTERN = /\.instant\(\s*['"]([a-z][a-zA-Z0-9_.]*)['"]/g;

export function flattenCatalogKeys(
  catalog: Record<string, unknown>,
  prefix = ''
): Set<string> {
  const keys = new Set<string>();

  for (const [key, value] of Object.entries(catalog)) {
    const path = prefix ? `${prefix}.${key}` : key;

    if (value && typeof value === 'object' && !Array.isArray(value)) {
      for (const nestedKey of flattenCatalogKeys(value as Record<string, unknown>, path)) {
        keys.add(nestedKey);
      }

      continue;
    }

    keys.add(path);
  }

  return keys;
}

export function extractTranslationKeysFromSource(source: string): Set<string> {
  const keys = new Set<string>();

  for (const pattern of [TRANSLATE_PIPE_KEY_PATTERN, INSTANT_KEY_PATTERN]) {
    pattern.lastIndex = 0;

    let match: RegExpExecArray | null;

    while ((match = pattern.exec(source)) !== null) {
      keys.add(match[1]);
    }
  }

  return keys;
}

export function findMissingCatalogKeys(definedKeys: Set<string>, usedKeys: Set<string>): string[] {
  return [...usedKeys]
    .filter((key) => !definedKeys.has(key))
    .sort();
}
