import {
  splitOutsideParenthesesAndArrays,
  joinParenthesesAndArrays,
} from '~codeyam/ai';
import { cleanKnownObjectFunctionsFromMapping } from '~codeyam/ai';
import { DataStructure, Entity, ReadonlyAnalysis } from '~codeyam/types';
import { transformationTracer } from './TransformationTracer';

export interface DataStructureInfo {
  signatureSchema: { [key: string]: string };
  returnValueSchema: { [key: string]: string };
  usageEquivalencies?: {
    [path: string]: { schemaPath: string; scopeNodeName: string }[];
  };
  sourceEquivalencies?: {
    [path: string]: { schemaPath: string; scopeNodeName: string }[];
  };
  environmentVariables?: string[];
}

function cleanFunctionName(functionName: string) {
  return functionName?.split('<')[0];
}

// Extract the type parameter from a function name, e.g., 'useFetcher<{ data: UserData }>()' -> '{ data: UserData }'
function getTypeParameter(functionName: string): string | null {
  if (!functionName) return null;
  const openBracket = functionName.indexOf('<');
  if (openBracket === -1) return null;
  // Find matching closing bracket, accounting for nested brackets
  let depth = 0;
  for (let i = openBracket; i < functionName.length; i++) {
    if (functionName[i] === '<') depth++;
    else if (functionName[i] === '>') {
      depth--;
      if (depth === 0) {
        return functionName.slice(openBracket + 1, i);
      }
    }
  }
  return null;
}

/**
 * Check if a schema path contains a Set/Map collection method call.
 * Paths like `.has(articleId)`, `.delete(articleId)`, `.add(articleId)` represent
 * membership checks on Sets/Maps, not meaningful data flow for schema generation.
 * These create massive combinatorial explosions when every filter field (filterRatings,
 * filterPublications, filterAuthors, etc.) × every method (has, delete, add) gets
 * tracked as a separate equivalency.
 */
const COLLECTION_METHOD_PATTERN = /\.(?:has|delete|add|clear|get|set)\(/;
function isCollectionMethodPath(path: string): boolean {
  return COLLECTION_METHOD_PATTERN.test(path);
}

/**
 * Check if a path contains an inline object literal inside a function call argument.
 * e.g., setUndoEntry({ label: '...', undo: () => {} }) has '{' inside '(' ')'.
 * These paths are call-site snapshots where the source code text was captured
 * as the path. They don't represent schema structure and are very expensive to
 * parse (avg 319 chars). They account for ~55% of equivalencies in complex entities.
 */
const INLINE_OBJECT_ARG_PATTERN = /\([^)]*\{[^}]*:/;
function hasInlineObjectArg(path: string): boolean {
  // Match function calls containing object literals with key-value pairs.
  // Pattern: open paren, then { with a : inside before closing }.
  // e.g., setUndoEntry({ label: '...' }) matches
  // e.g., find(item) does NOT match
  // e.g., fn({a:1, b:2}) matches
  return INLINE_OBJECT_ARG_PATTERN.test(path);
}

// Primitive types that should not have child paths
const PRIMITIVE_TYPES = new Set([
  'number',
  'string',
  'boolean',
  'null',
  'undefined',
]);

// Check if a type string represents a primitive type
// Handles union types like "string | undefined" or "number | null"
// Also handles string literal unions like "'suggestion' | 'warning' | 'tip'"
function isPrimitiveType(typeStr: string): boolean {
  if (PRIMITIVE_TYPES.has(typeStr)) {
    return true;
  }
  // Check union types - if ALL parts of the union are primitives, it's primitive
  // e.g., "string | undefined" -> ["string", "undefined"] -> both are primitive -> true
  // e.g., "object | null" -> ["object", "null"] -> object is not primitive -> false
  // e.g., "'suggestion' | 'warning'" -> string literal union -> true
  if (typeStr.includes('|')) {
    const parts = typeStr.split('|').map((p) => p.trim());
    return parts.every(
      (part) =>
        PRIMITIVE_TYPES.has(part) ||
        // String literal values like 'suggestion', 'warning' are primitives
        (part.startsWith("'") && part.endsWith("'")),
    );
  }
  return false;
}

// Extract signature index from a path like "signature[0]" or "signature[0].foo"
// Returns the index number or undefined if not a signature path
function extractSignatureIndex(path: string): number | undefined {
  const match = path.match(/^signature\[(\d+)\]/);
  return match ? parseInt(match[1], 10) : undefined;
}

// Check if a new schema path would go through a primitive type
// e.g., if schema has 'entities[].scenarioCount': 'number', then
// 'entities[].scenarioCount.sha' would go through a primitive and should be rejected
function wouldGoThroughPrimitive(
  newPath: string,
  schema: { [key: string]: string },
): boolean {
  const pathParts = splitOutsideParenthesesAndArrays(newPath);

  // Check each prefix of the path (excluding the full path itself)
  for (let i = 1; i < pathParts.length; i++) {
    const prefixPath = joinParenthesesAndArrays(pathParts.slice(0, i));
    const prefixType = schema[prefixPath];
    if (prefixType && isPrimitiveType(prefixType)) {
      return true;
    }
  }

  return false;
}

// Check if schemaPathPart matches or is a function call variant of pathPart
// e.g., 'isEntityBeingAnalyzed(entity.sha)' matches 'isEntityBeingAnalyzed'
function pathPartMatches(pathPart: string, schemaPathPart: string): boolean {
  if (pathPart === schemaPathPart) return true;

  // Check if schemaPathPart is a function call variant of pathPart
  // pathPart: 'isEntityBeingAnalyzed'
  // schemaPathPart: 'isEntityBeingAnalyzed(entity.sha)'
  if (schemaPathPart.startsWith(pathPart + '(')) return true;

  return false;
}

function bestValueFromOptions(options: Array<string | undefined>) {
  options = options.filter(Boolean) as string[];

  const known = options.filter((o) => !o.includes('unknown'));
  if (known.length > 0) {
    // Among known values, prefer string literal unions over bare primitives.
    // e.g., "'draft' | 'inProgress' | 'paused' | 'completed'" is more specific than "string".
    // This handles cases where a dependency schema has a bare type like "string" but the
    // child entity's analysis has the actual literal union from TypeScript type resolution.
    if (known.length > 1 && known.some((o) => PRIMITIVE_TYPES.has(o))) {
      const literalUnion = known.find(
        (o) => !PRIMITIVE_TYPES.has(o) && o.includes("'"),
      );
      if (literalUnion) {
        return literalUnion;
      }
    }
    return known[0];
  }

  const notUnknown = options.find((o) => o !== 'unknown');
  if (notUnknown) {
    return notUnknown;
  }

  return options[0] ?? 'unknown';
}

/** Timeout (ms) for the merge operation. Throws DataStructureTimeoutError if exceeded.
 *  All successful merges complete in <300ms. Anything exceeding 2s is pathological. */
const MERGE_TIMEOUT_MS = 2_000;

/** Cap for schema size during postfix application and dep copy.
 *  Successful merges produce <3K ret keys. Beyond 5K, further entries
 *  are cross-products of unrelated equivalencies — noise, not signal. */
const SCHEMA_KEY_CAP = 5_000;

export class DataStructureTimeoutError extends Error {
  constructor(entityName: string, elapsedMs: number) {
    super(
      `Data structure merge timed out for ${entityName} after ${Math.round(elapsedMs / 1000)}s (limit: ${MERGE_TIMEOUT_MS / 1000}s)`,
    );
    this.name = 'DataStructureTimeoutError';
  }
}

export default function mergeInDependentDataStructure({
  importedExports,
  dependentAnalyses,
  rootScopeName,
  dataStructure,
  dependencySchemas,
  timeoutMs = MERGE_TIMEOUT_MS,
}: {
  importedExports: Pick<
    Entity['metadata']['importedExports'][0],
    'filePath' | 'name' | 'isMocked'
  >[];
  dependentAnalyses: {
    [filePath: string]: {
      [name: string]: {
        metadata?: {
          mergedDataStructure?: ReadonlyAnalysis['metadata']['mergedDataStructure'];
        };
      };
    };
  };
  rootScopeName: string;
  dataStructure: DataStructureInfo;
  dependencySchemas: {
    [filePath: string]: {
      [name: string]: DataStructureInfo;
    };
  };
  /** Override the default timeout (ms). Set to 0 to disable. */
  timeoutMs?: number;
}) {
  const mergeStartTime = Date.now();
  const mergeDeadline = timeoutMs > 0 ? mergeStartTime + timeoutMs : 0;

  /** Call in hot loops. Throws DataStructureTimeoutError if deadline exceeded.
   *  Date.now() is ~20ns — negligible vs the ms-scale string ops in each iteration. */
  const checkDeadline = () => {
    if (!mergeDeadline) return;
    if (Date.now() > mergeDeadline) {
      throw new DataStructureTimeoutError(
        rootScopeName,
        Date.now() - mergeStartTime,
      );
    }
  };
  const mergedDataStructure: Omit<
    DataStructure,
    'equivalentSignatureVariables'
  > = {
    signatureSchema: { ...(dataStructure.signatureSchema ?? {}) },
    returnValueSchema: { ...(dataStructure.returnValueSchema ?? {}) },
    usageEquivalencies: { ...(dataStructure.usageEquivalencies ?? {}) },
    sourceEquivalencies: { ...(dataStructure.sourceEquivalencies ?? {}) },
    dependencySchemas: {},
    environmentVariables: [...(dataStructure.environmentVariables || [])],
  };

  try {
    // Build a set of functions that have multiple DIFFERENT type parameters.
    // For these functions, we must NOT normalize paths to avoid merging different schemas.
    // e.g., if we have both useFetcher<{ data: UserData }>() and useFetcher<{ data: ConfigData }>(),
    // they must stay separate and not both become 'returnValue'.
    const functionsWithMultipleTypeParams = new Set<string>();
    const typeParamsByFunction: Record<string, Set<string>> = {};

    // Helper to scan a schema for type parameters
    const scanSchemaForTypeParams = (schema: { [key: string]: string }) => {
      for (const schemaPath of Object.keys(schema ?? {})) {
        const parts = splitOutsideParenthesesAndArrays(schemaPath);
        if (parts.length > 0) {
          const firstPart = parts[0];
          const typeParam = getTypeParameter(firstPart);
          if (typeParam) {
            const baseName = cleanFunctionName(firstPart);
            typeParamsByFunction[baseName] ||= new Set();
            typeParamsByFunction[baseName].add(typeParam);
            if (typeParamsByFunction[baseName].size > 1) {
              functionsWithMultipleTypeParams.add(baseName);
            }
          }
        }
      }
    };

    // Scan the root entity's schema
    scanSchemaForTypeParams(dataStructure.returnValueSchema);

    // Also scan all dependency schemas for type parameters
    for (const filePath of Object.keys(dependencySchemas ?? {})) {
      for (const name of Object.keys(dependencySchemas[filePath] ?? {})) {
        scanSchemaForTypeParams(
          dependencySchemas[filePath][name]?.returnValueSchema,
        );
      }
    }

    let equivalentSchemaPaths: {
      equivalentRoots: {
        schemaRootPath: string;
        function?: { filePath?: string; name: string };
        postfix?: string;
      }[];
      equivalentPostfixes: Record<string, string>;
    }[] = [];

    // O(1) index for findOrCreateEquivalentSchemaPathsEntry.
    // Maps "(rootPath)::(normalizedFuncName)" → the entry containing that root.
    // This replaces the O(E) linear search that was causing O(E²) gather performance.
    const espIndex = new Map<string, (typeof equivalentSchemaPaths)[0]>();
    const espIndexKey = (path: string, functionName: string | undefined) => {
      const normalized = cleanFunctionName(functionName);
      const funcKey =
        normalized === rootScopeName ? '__self__' : normalized || '__self__';
      return `${path}::${funcKey}`;
    };
    const updateEspIndex = (entry: (typeof equivalentSchemaPaths)[0]) => {
      for (const root of entry.equivalentRoots) {
        const funcName = root.function?.name ?? rootScopeName;
        espIndex.set(espIndexKey(root.schemaRootPath, funcName), entry);
      }
    };

    // Pre-build a lookup map from cleaned function name to dependency for O(1) lookups.
    // This avoids O(n) linear search in findRelevantDependency which was causing O(n²) performance.
    const dependencyByCleanedName = new Map<
      string,
      (typeof importedExports)[0]
    >();
    for (const dep of importedExports) {
      const cleanedName = cleanFunctionName(dep.name);
      if (!dependencyByCleanedName.has(cleanedName)) {
        dependencyByCleanedName.set(cleanedName, dep);
      }
    }

    const findRelevantDependency = (functionName: any) => {
      return dependencyByCleanedName.get(cleanFunctionName(functionName));
    };

    const findRelevantDependentDataStructure = (functionName: any) => {
      const dependency = findRelevantDependency(functionName);
      if (!dependency) return;

      return dependencySchemas?.[dependency.filePath]?.[dependency.name];
    };

    const findRelevantDependentAnalysisDataStructure = (functionName: any) => {
      const dependency = findRelevantDependency(functionName);
      if (!dependency) return;

      const dependentAnalysis =
        dependentAnalyses[dependency.filePath]?.[dependency.name];
      if (!dependentAnalysis?.metadata?.mergedDataStructure) {
        return;
      }

      return dependentAnalysis.metadata.mergedDataStructure;
    };

    const findOrCreateDependentSchemas = (dependency: {
      filePath?: string;
      name: string;
    }) => {
      const { filePath, name } = dependency;
      mergedDataStructure.dependencySchemas[filePath] ||= {};
      mergedDataStructure.dependencySchemas[filePath][name] ||= {
        signatureSchema: {},
        returnValueSchema: {},
      };

      return mergedDataStructure.dependencySchemas[filePath][name];
    };

    const cleanSchema = (
      schema: { [key: string]: string },
      context?: Record<string, any>,
    ) => {
      transformationTracer.traceSchemaTransform(
        rootScopeName,
        'cleanKnownObjectFunctionsFromMapping',
        schema,
        cleanKnownObjectFunctionsFromMapping,
        context,
      );
    };

    // Cache translatePath results — the same path is often translated multiple times
    // (once per equivalency entry that references it). Avoids redundant
    // splitOutsideParenthesesAndArrays calls on long paths.
    const translatePathCache = new Map<string, string>();

    const translatePath = (path: string, dependencyName: string) => {
      const cacheKey = `${dependencyName}\0${path}`;
      const cached = translatePathCache.get(cacheKey);
      if (cached !== undefined) return cached;

      let result = path;
      if (path.startsWith(dependencyName)) {
        const pathParts = splitOutsideParenthesesAndArrays(path);
        if (pathParts.length > 1) {
          if (pathParts[1].startsWith('functionCallReturnValue')) {
            // Check if this function has multiple DIFFERENT type parameters.
            // If so, DON'T normalize to returnValue - keep the full path to avoid
            // merging different type-parameterized variants together.
            const baseName = cleanFunctionName(pathParts[0]);
            if (!functionsWithMultipleTypeParams.has(baseName)) {
              // functionCallReturnValue immediately follows - normalize to returnValue
              result = joinParenthesesAndArrays([
                'returnValue',
                ...pathParts.slice(2),
              ]);
            }
          } else if (
            pathParts[0].endsWith(')') &&
            pathParts[1].startsWith('signature[')
          ) {
            // Hook-style with signature access
            result = joinParenthesesAndArrays(pathParts.slice(1));
          }
        }
      }

      translatePathCache.set(cacheKey, result);
      return result;
    };

    const gatherAllEquivalentSchemaPaths = (
      functionName: string,
      sourceAndUsageEquivalencies: Pick<
        DataStructure,
        'sourceEquivalencies' | 'usageEquivalencies'
      >,
      dataStructure?: Pick<
        DataStructure,
        'signatureSchema' | 'returnValueSchema'
      >,
    ) => {
      checkDeadline();
      if (!sourceAndUsageEquivalencies) return;

      // Pre-computed normalized schema index cache.
      // Avoids repeated splitOutsideParenthesesAndArrays calls and function-name
      // normalization for the same schema paths across multiple equivalency iterations.
      // The normalization depends on `functionName` (constant per gatherAllEquivalentSchemaPaths call),
      // so this cache is scoped to this call.
      type NormalizedEntry = { path: string; parts: string[] };
      const normalizedSchemaCache = new Map<
        object,
        {
          byFirstPart: Map<string, NormalizedEntry[]>;
        }
      >();
      const getSchemaIndex = (
        schema: Record<string, string> | undefined,
      ): { byFirstPart: Map<string, NormalizedEntry[]> } => {
        if (!schema) return { byFirstPart: new Map() };
        const cached = normalizedSchemaCache.get(schema);
        if (cached) return cached;
        const byFirstPart = new Map<string, NormalizedEntry[]>();
        for (const path in schema) {
          checkDeadline();
          let parts = splitOutsideParenthesesAndArrays(path);
          if (parts[0].startsWith(functionName)) {
            const baseName = cleanFunctionName(parts[0]);
            if (!functionsWithMultipleTypeParams.has(baseName)) {
              parts =
                parts[1] === 'functionCallReturnValue'
                  ? ['returnValue', ...parts.slice(2)]
                  : parts.slice(1);
            }
          }
          const entry: NormalizedEntry = { path, parts };
          // Index by the base of the first part (before any function call args)
          const firstPart = parts[0] ?? '';
          const parenIdx = firstPart.indexOf('(');
          const firstPartBase =
            parenIdx >= 0 ? firstPart.slice(0, parenIdx) : firstPart;
          let bucket = byFirstPart.get(firstPartBase);
          if (!bucket) {
            bucket = [];
            byFirstPart.set(firstPartBase, bucket);
          }
          bucket.push(entry);
        }
        const result = { byFirstPart };
        normalizedSchemaCache.set(schema, result);
        return result;
      };

      const findOrCreateEquivalentSchemaPathsEntry = (
        allPaths: { path: string; functionName?: string }[],
      ) => {
        const equivalentRoots = allPaths
          .filter(
            (p) =>
              p.functionName === rootScopeName ||
              !!findRelevantDependency(p.functionName),
          )
          .map((p) => ({
            schemaRootPath: p.path,
            function:
              p.functionName === rootScopeName
                ? undefined
                : findRelevantDependency(p.functionName),
          }));

        let equivalentSchemaPathsEntry:
          | (typeof equivalentSchemaPaths)[0]
          | undefined;

        // Collect the signature indices from the new roots we want to add
        const newRootSignatureIndices = new Set<number>();
        for (const root of equivalentRoots) {
          const idx = extractSignatureIndex(root.schemaRootPath);
          if (idx !== undefined) {
            newRootSignatureIndices.add(idx);
          }
        }

        // Use espIndex Map for O(1) lookup instead of O(E) linear search.
        // Falls back to linear search only when Map hit has a signature index conflict.
        for (const pathInfo of allPaths) {
          checkDeadline();
          if (equivalentSchemaPathsEntry) break;
          const candidate = espIndex.get(
            espIndexKey(pathInfo.path, pathInfo.functionName),
          );
          if (!candidate) continue;

          // Verify no signature index conflict with the candidate entry
          if (newRootSignatureIndices.size > 0) {
            const existingIndicesByFunction = new Map<string, Set<number>>();
            for (const er of candidate.equivalentRoots) {
              const funcKey = er.function
                ? `${er.function.name}::${er.function.filePath}`
                : '__self__';
              const idx = extractSignatureIndex(er.schemaRootPath);
              if (idx !== undefined) {
                if (!existingIndicesByFunction.has(funcKey)) {
                  existingIndicesByFunction.set(funcKey, new Set());
                }
                existingIndicesByFunction.get(funcKey)!.add(idx);
              }
            }

            let hasConflict = false;
            for (const newRoot of equivalentRoots) {
              const funcKey = newRoot.function
                ? `${newRoot.function.name}::${newRoot.function.filePath}`
                : '__self__';
              const newIdx = extractSignatureIndex(newRoot.schemaRootPath);
              if (newIdx !== undefined) {
                const existingIndices = existingIndicesByFunction.get(funcKey);
                if (existingIndices && existingIndices.size > 0) {
                  if (!existingIndices.has(newIdx)) {
                    hasConflict = true;
                    break;
                  }
                }
              }
            }

            if (hasConflict) continue;
          }

          equivalentSchemaPathsEntry = candidate;
        }

        if (!equivalentSchemaPathsEntry) {
          // Before creating a new entry, filter out roots that have conflicting
          // signature indices from the same function. An entry should never contain
          // roots with different signature indices from the same function.
          // This prevents the bug where signature[1], signature[2], signature[4]
          // all get merged together due to incorrect sourceEquivalencies.
          let filteredRoots = equivalentRoots;
          if (newRootSignatureIndices.size > 1) {
            // There are multiple signature indices - we need to filter to keep only
            // one consistent set. We'll keep the roots that match the PRIMARY index
            // (the first signature index we encounter from self, or the lowest index).

            // First, determine the primary index - prefer the self root's index
            let primaryIndex: number | undefined;
            for (const root of equivalentRoots) {
              if (!root.function) {
                // This is a self root
                const idx = extractSignatureIndex(root.schemaRootPath);
                if (idx !== undefined) {
                  primaryIndex = idx;
                  break;
                }
              }
            }
            // If no self root has a signature index, use the lowest index
            if (primaryIndex === undefined) {
              primaryIndex = Math.min(...newRootSignatureIndices);
            }

            // Filter roots: keep if no signature index OR signature index matches primary
            filteredRoots = equivalentRoots.filter((root) => {
              const idx = extractSignatureIndex(root.schemaRootPath);
              return idx === undefined || idx === primaryIndex;
            });
          }

          equivalentSchemaPathsEntry = {
            equivalentRoots: filteredRoots,
            equivalentPostfixes: {},
          };
          equivalentSchemaPaths.push(equivalentSchemaPathsEntry);
        } else {
          equivalentSchemaPathsEntry.equivalentRoots.push(...equivalentRoots);
        }

        // Deduplicate roots using a Set for O(n) instead of O(n²)
        const seenRoots = new Set<string>();
        equivalentSchemaPathsEntry.equivalentRoots =
          equivalentSchemaPathsEntry.equivalentRoots.filter((er) => {
            const key = er.schemaRootPath + '::' + (er.function?.name ?? '');
            if (seenRoots.has(key)) return false;
            seenRoots.add(key);
            return true;
          });

        // Keep the espIndex in sync after adding/deduplicating roots
        updateEspIndex(equivalentSchemaPathsEntry);

        return equivalentSchemaPathsEntry;
      };

      // Helper to extract function name from a path that starts with a function call.
      // e.g., 'ScenarioViewer().signature[0].scenario' -> 'ScenarioViewer'
      // Returns undefined if the path doesn't start with a function call or the function isn't a dependency.
      const extractFunctionNameFromPath = (
        path: string,
      ): string | undefined => {
        const parts = splitOutsideParenthesesAndArrays(path);
        if (parts.length > 0 && parts[0].endsWith(')')) {
          // Extract the function name without the () suffix and type params
          const funcCallPart = parts[0];
          const funcName = cleanFunctionName(funcCallPart.replace(/\(\)$/, ''));
          // Check if this function is a dependency
          if (findRelevantDependency(funcName)) {
            return funcName;
          }
        }
        return undefined;
      };

      const allEquivalencies = [
        sourceAndUsageEquivalencies.usageEquivalencies,
        sourceAndUsageEquivalencies.sourceEquivalencies,
      ].filter(Boolean);

      // Global dedup across ALL equivalency entries. The same (scope, targetPath)
      // pair often appears in 30-50 different source entries (e.g., every variable
      // that flows through loadView references the same 50 target paths).
      // Processing these redundantly accounts for 96% of work in the gather phase.
      const globalSeenTargets = new Set<string>();

      for (const equivalencies of allEquivalencies) {
        const schemaPathEntries = Object.entries(equivalencies);
        for (const [schemaPath, usages] of schemaPathEntries) {
          checkDeadline();

          // Skip equivalency entries whose source path is a Set/Map membership operation.
          // Patterns like `.has(articleId)`, `.delete(articleId)`, `.add(articleId)` on
          // Sets/Maps represent membership checks, not meaningful data flow for schema generation.
          // In the Margo LibraryPage case, these account for 74% of all equivalency targets
          // (19,444 of 26,340) and cause a combinatorial explosion in the merge.
          if (isCollectionMethodPath(schemaPath)) continue;

          // Skip paths with inline object literals in function call arguments.
          // These are call-site snapshots (e.g., setUndoEntry({ label: '...', undo: ... }))
          // that embed source code text as path strings. They're expensive to parse
          // and don't contribute useful schema information.
          if (hasInlineObjectArg(schemaPath)) continue;

          // First, check if the raw schemaPath starts with a function call to a dependency.
          // If so, use that dependency name for translation (so translatePath can strip the prefix).
          const extractedFuncName = extractFunctionNameFromPath(schemaPath);
          const effectiveFunctionName = extractedFuncName || functionName;
          const translatedPath = translatePath(
            schemaPath,
            effectiveFunctionName,
          );

          const allPathsRaw: { path: string; functionName?: string }[] = [
            { path: translatedPath, functionName: effectiveFunctionName },
            ...usages
              .filter((u) => !isCollectionMethodPath(u.schemaPath))
              .map((u) => ({
                path: translatePath(u.schemaPath, u.scopeNodeName),
                functionName: u.scopeNodeName,
              })),
          ].filter((pathInfo) => !pathInfo.path.includes('.map('));

          // Deduplicate by translated path + function name, both within this entry
          // AND across all entries. The same target path appears in 30-50 different
          // source entries (every variable flowing through loadView references the same
          // 50 target paths). Without global dedup, we process 5,533 targets instead of 217.
          const allPaths = allPathsRaw.filter((p) => {
            const key = `${p.functionName ?? ''}::${p.path}`;
            if (globalSeenTargets.has(key)) return false;
            globalSeenTargets.add(key);
            return true;
          });

          // Fix 38: Derive base paths from property access paths.
          // When we have equivalent paths like:
          //   Parent: signature[0].scenarios[].name
          //   Child:  signature[0].selectedScenario.name
          // We want to derive the base paths by finding the common suffix:
          //   Common suffix: .name
          //   Parent base: signature[0].scenarios[]
          //   Child base:  signature[0].selectedScenario
          // This allows the merge to find nested child schema fields under the base prop.

          // Find child signature paths (paths from child components)
          const childPaths = allPaths.filter(
            (p) =>
              p.functionName &&
              p.functionName !== rootScopeName &&
              p.functionName !== effectiveFunctionName,
          );
          // Find parent paths (paths from this component)
          const parentPaths = allPaths.filter(
            (p) =>
              !p.functionName ||
              p.functionName === rootScopeName ||
              p.functionName === effectiveFunctionName,
          );

          const derivedBasePaths: { path: string; functionName?: string }[] =
            [];
          const allPathSet = new Set(allPaths.map((p) => p.path));
          const derivedBasePathSet = new Set<string>();

          // For each child path, find its equivalent parent path and derive bases
          for (const childPathInfo of childPaths) {
            checkDeadline();
            const childParts = splitOutsideParenthesesAndArrays(
              childPathInfo.path,
            );

            // Look for a parent path that shares a common suffix with this child path
            for (const parentPathInfo of parentPaths) {
              const parentParts = splitOutsideParenthesesAndArrays(
                parentPathInfo.path,
              );

              // Find the common suffix (from the end)
              let commonSuffixLength = 0;
              const minLen = Math.min(childParts.length, parentParts.length);
              for (let i = 1; i <= minLen; i++) {
                if (
                  childParts[childParts.length - i] ===
                  parentParts[parentParts.length - i]
                ) {
                  commonSuffixLength = i;
                } else {
                  break;
                }
              }

              // If there's a common suffix and both paths have more parts than the suffix
              if (
                commonSuffixLength > 0 &&
                childParts.length > commonSuffixLength &&
                parentParts.length > commonSuffixLength
              ) {
                const childBaseParts = childParts.slice(
                  0,
                  childParts.length - commonSuffixLength,
                );
                const parentBaseParts = parentParts.slice(
                  0,
                  parentParts.length - commonSuffixLength,
                );

                // Only derive if BOTH paths look like signature paths.
                // This ensures we're handling JSX child-to-parent prop mappings,
                // not other complex equivalencies like function call returns.
                const isChildSignaturePath =
                  childBaseParts[0]?.startsWith('signature[') ||
                  (childBaseParts[0]?.endsWith(')') &&
                    childBaseParts[1]?.startsWith('signature['));
                const isParentSignaturePath =
                  parentBaseParts[0]?.startsWith('signature[');

                if (isChildSignaturePath && isParentSignaturePath) {
                  const childBase = joinParenthesesAndArrays(childBaseParts);
                  const parentBase = joinParenthesesAndArrays(parentBaseParts);

                  // Only derive if:
                  // 1. Parent has array iteration (e.g., scenarios[]) and child does NOT
                  // 2. Bases are different
                  // 3. Child base is NOT just "signature[N]" (too generic - every component has this)
                  //    We only want specific prop paths like "signature[0].selectedScenario"
                  // This targets array-to-object mappings like scenarios[] -> selectedScenario
                  const parentHasArrayIterator = parentBase.includes('[]');
                  const childHasArrayIterator = childBase.includes('[]');

                  // Skip if child base is just the generic signature marker (e.g., "signature[0]")
                  const childBaseIsGenericSignature = /^signature\[\d+\]$/.test(
                    childBase,
                  );

                  if (
                    childBase !== parentBase &&
                    parentHasArrayIterator &&
                    !childHasArrayIterator &&
                    !childBaseIsGenericSignature
                  ) {
                    // Add child base if not already present (O(1) Set lookup)
                    if (
                      !allPathSet.has(childBase) &&
                      !derivedBasePathSet.has(childBase)
                    ) {
                      derivedBasePaths.push({
                        path: childBase,
                        functionName: childPathInfo.functionName,
                      });
                      derivedBasePathSet.add(childBase);
                    }

                    // Add parent base if not already present (O(1) Set lookup)
                    if (
                      !allPathSet.has(parentBase) &&
                      !derivedBasePathSet.has(parentBase)
                    ) {
                      derivedBasePaths.push({
                        path: parentBase,
                        functionName: parentPathInfo.functionName,
                      });
                      derivedBasePathSet.add(parentBase);
                    }
                  }
                }
              }
            }
          }

          allPaths.push(...derivedBasePaths);

          const entry = findOrCreateEquivalentSchemaPathsEntry(allPaths);

          // Trace equivalency gathering - helps debug why paths may not be connected
          if (allPaths.length > 1) {
            transformationTracer.operation(rootScopeName, {
              operation: 'gatherEquivalency',
              stage: 'gathering',
              path: translatedPath,
              context: {
                sourceFunction: functionName,
                equivalentPaths: allPaths.map((p) => ({
                  path: p.path,
                  function: p.functionName,
                })),
                equivalentRoots: entry.equivalentRoots.map((r) => ({
                  path: r.schemaRootPath,
                  function: r.function?.name,
                })),
              },
            });
          }
          for (const equivalentRoot of entry.equivalentRoots) {
            checkDeadline();
            const dataStructures =
              equivalentRoot.function &&
              equivalentRoot.function.name !== rootScopeName
                ? [
                    findRelevantDependentDataStructure(
                      equivalentRoot.function.name,
                    ),
                    findRelevantDependentAnalysisDataStructure(
                      equivalentRoot.function.name,
                    ),
                  ]
                : [dataStructure];

            // Determine if this is a signature schema path.
            // The path might be 'signature[0]...' directly, or 'FuncName().signature[0]...' if it has a function prefix.
            const schemaRootParts = splitOutsideParenthesesAndArrays(
              equivalentRoot.schemaRootPath,
            );
            const isSignaturePath =
              equivalentRoot.schemaRootPath.startsWith('signature[') ||
              (schemaRootParts[0]?.endsWith(')') &&
                schemaRootParts[1]?.startsWith('signature['));

            const schemas = dataStructures.map((dataStructure) =>
              isSignaturePath
                ? dataStructure?.signatureSchema
                : dataStructure?.returnValueSchema,
            );

            let pathParts = splitOutsideParenthesesAndArrays(
              equivalentRoot.schemaRootPath,
            );

            // Fix: When processing a child component's schema, the schemaRootPath has the function
            // prefix (e.g., 'ScenarioViewer().signature[0].scenario'), but the child's schema paths
            // don't have that prefix (e.g., 'signature[0].scenario.metadata.screenshotPaths').
            // Strip the function prefix from pathParts so they can match.
            if (
              equivalentRoot.function &&
              pathParts[0].endsWith(')') &&
              pathParts[1]?.startsWith('signature[')
            ) {
              pathParts = pathParts.slice(1);
            }

            for (const schema of schemas) {
              // Use pre-computed index to only iterate schema entries whose
              // normalized first part matches pathParts[0], instead of all entries.
              const schemaIndex = getSchemaIndex(schema);
              const lookupPart = pathParts[0] ?? '';
              const lookupParenIdx = lookupPart.indexOf('(');
              const lookupBase =
                lookupParenIdx >= 0
                  ? lookupPart.slice(0, lookupParenIdx)
                  : lookupPart;
              const candidates = schemaIndex.byFirstPart.get(lookupBase) || [];
              for (const {
                path: schemaPath,
                parts: schemaPathParts,
              } of candidates) {
                checkDeadline();
                if (schemaPathParts.length < pathParts.length) continue;

                // Check if all path parts match (allowing function call variants)
                let allMatch = true;
                let matchedUpToIndex = pathParts.length;
                for (let i = 0; i < pathParts.length; i++) {
                  if (!pathPartMatches(pathParts[i], schemaPathParts[i])) {
                    allMatch = false;
                    break;
                  }
                  // If the last pathPart matched a function call variant,
                  // we need to include it in the postfix calculation
                  if (
                    i === pathParts.length - 1 &&
                    schemaPathParts[i] !== pathParts[i] &&
                    schemaPathParts[i].startsWith(pathParts[i] + '(')
                  ) {
                    // The schemaPathPart is a function call variant (e.g., 'isEntityBeingAnalyzed(entity.sha)')
                    // We want to include this as part of the postfix
                    matchedUpToIndex = i;
                  }
                }

                if (allMatch) {
                  // When we matched a function call variant at the end (e.g., 'foo' matched 'foo(args)'),
                  // the base itself should be marked as a function, and the function call details
                  // should be included as sub-paths
                  if (matchedUpToIndex < pathParts.length) {
                    // This is a function call variant match at the last position
                    // Mark the base as a function (empty postfix = the base path itself)
                    entry.equivalentPostfixes[''] = bestValueFromOptions([
                      entry.equivalentPostfixes[''],
                      'function',
                    ]);

                    // Also capture the function call and any remaining parts
                    // e.g., 'isEntityBeingAnalyzed(entity.sha)' or 'isEntityBeingAnalyzed(entity.sha).functionCallReturnValue'
                    const funcCallPart = schemaPathParts[matchedUpToIndex];
                    const baseName = pathParts[matchedUpToIndex]; // e.g., 'isEntityBeingAnalyzed'
                    const argsMatch = funcCallPart.match(/\(.*\)$/);

                    if (argsMatch) {
                      // Create postfix using just the args portion: (entity.sha) instead of isEntityBeingAnalyzed(entity.sha)
                      // This avoids duplicating the base name in the final path
                      const argsPortion = argsMatch[0]; // e.g., '(entity.sha)'
                      const remainingParts = schemaPathParts.slice(
                        matchedUpToIndex + 1,
                      );

                      // Build the postfix as: (args).remaining.parts
                      const funcPostfix = joinParenthesesAndArrays([
                        argsPortion,
                        ...remainingParts,
                      ]);
                      entry.equivalentPostfixes[funcPostfix] = entry
                        .equivalentPostfixes[funcPostfix]
                        ? bestValueFromOptions([
                            entry.equivalentPostfixes[funcPostfix],
                            schema[schemaPath],
                          ])
                        : schema[schemaPath];
                    }
                  } else {
                    // Regular exact match - use the standard postfix logic
                    const postfix = joinParenthesesAndArrays(
                      schemaPathParts.slice(matchedUpToIndex),
                    );

                    const previousValue = entry.equivalentPostfixes[postfix];
                    const newValue = schema[schemaPath];
                    entry.equivalentPostfixes[postfix] = previousValue
                      ? bestValueFromOptions([previousValue, newValue])
                      : newValue;

                    // Trace postfix gathering - shows where type info comes from
                    if (entry.equivalentPostfixes[postfix] !== previousValue) {
                      transformationTracer.operation(rootScopeName, {
                        operation: 'gatherPostfix',
                        stage: 'gathering',
                        path: postfix || '(root)',
                        before: previousValue,
                        after: entry.equivalentPostfixes[postfix],
                        context: {
                          sourceSchemaPath: schemaPath,
                          sourceFunction:
                            equivalentRoot.function?.name || rootScopeName,
                          equivalentRootPath: equivalentRoot.schemaRootPath,
                          rawValue: newValue,
                        },
                      });
                    }
                  }
                }
              }
            }
          }
        }
      }

      if (Object.keys(dataStructure?.returnValueSchema ?? {}).length > 0) {
        // Find all paths that contain functionCallReturnValue and extract unique base paths
        // For each path containing functionCallReturnValue, find the FIRST occurrence and use
        // that as a base path. This handles nested cases like:
        //   X().functionCallReturnValue.A.B.Y().functionCallReturnValue
        // where we want both X().functionCallReturnValue and Y().functionCallReturnValue as bases
        const allBasePaths = new Set<string>();
        for (const path of Object.keys(dataStructure.returnValueSchema)) {
          checkDeadline();
          const parts = splitOutsideParenthesesAndArrays(path);
          // Find all positions of functionCallReturnValue and create base paths for each
          for (let i = 0; i < parts.length; i++) {
            if (parts[i] === 'functionCallReturnValue') {
              const basePath = joinParenthesesAndArrays(parts.slice(0, i + 1));
              allBasePaths.add(basePath);
            }
          }
        }

        // Sort by length so shorter paths are processed first
        const sortedBasePaths = [...allBasePaths].sort(
          (a, b) => a.length - b.length,
        );

        for (const basePath of sortedBasePaths) {
          const translatedBasePath = translatePath(basePath, functionName);
          const entry = findOrCreateEquivalentSchemaPathsEntry([
            { path: translatedBasePath, functionName: functionName },
          ]);
          const newRoot = {
            schemaRootPath: translatedBasePath,
            function: findRelevantDependency(functionName),
          };
          entry.equivalentRoots.push(newRoot);
          // Update index for the newly added root
          const newRootFuncName = newRoot.function?.name ?? rootScopeName;
          espIndex.set(
            espIndexKey(newRoot.schemaRootPath, newRootFuncName),
            entry,
          );

          const basePathParts = splitOutsideParenthesesAndArrays(basePath);
          for (const schemaPath in dataStructure.returnValueSchema) {
            checkDeadline();
            const schemaPathParts =
              splitOutsideParenthesesAndArrays(schemaPath);
            if (schemaPathParts.length < basePathParts.length) continue;

            // Check if this schemaPath actually starts with this basePath
            // (not just has the same length prefix)
            const prefixParts = schemaPathParts.slice(0, basePathParts.length);
            if (
              joinParenthesesAndArrays(prefixParts) !==
              joinParenthesesAndArrays(basePathParts)
            ) {
              continue;
            }

            const postfix = joinParenthesesAndArrays(
              schemaPathParts.slice(basePathParts.length),
            );
            const newValue = entry.equivalentPostfixes[postfix]
              ? bestValueFromOptions([
                  entry.equivalentPostfixes[postfix],
                  dataStructure.returnValueSchema[schemaPath],
                ])
              : dataStructure.returnValueSchema[schemaPath];

            entry.equivalentPostfixes[postfix] = newValue;
          }
        }
      }
    };

    const mergeAllEquivalentSchemaPaths = () => {
      const mergedEquivalentSchemaPaths: typeof equivalentSchemaPaths = [];

      // Pre-pass: Connect entries with array/array-element relationships.
      // This handles cases like:
      // - Entry A has root 'surveys' (array)
      // - Entry B has root 'surveys[]' (array element)
      // These need to be connected so Entry B's field postfixes flow to Entry A.
      // We do this before the main merge to ensure the connection happens regardless
      // of processing order.
      for (const esp of equivalentSchemaPaths) {
        checkDeadline();
        for (const root of esp.equivalentRoots) {
          if (root.schemaRootPath.endsWith('[]')) {
            // Find a matching parent entry with the base array path
            const baseArrayPath = root.schemaRootPath.slice(0, -2);
            const parentEntry = equivalentSchemaPaths.find(
              (other) =>
                other !== esp &&
                other.equivalentRoots.some(
                  (otherRoot) =>
                    otherRoot.schemaRootPath === baseArrayPath &&
                    otherRoot.function?.name === root.function?.name &&
                    otherRoot.function?.filePath === root.function?.filePath,
                ),
            );
            if (parentEntry) {
              // Add transformed postfixes from child (array element) to parent (array)
              // so they can be applied with [] prefix to parent paths
              for (const [postfixPath, postfixValue] of Object.entries(
                esp.equivalentPostfixes,
              )) {
                checkDeadline();
                const transformedPostfix = joinParenthesesAndArrays(
                  ['[]', postfixPath].filter(Boolean),
                );
                if (!(transformedPostfix in parentEntry.equivalentPostfixes)) {
                  parentEntry.equivalentPostfixes[transformedPostfix] =
                    postfixValue;
                }
              }
            }
          }
        }
      }

      const findEquivalentSchemaPathEntry = (
        schemaSubPath: string,
        equivalentRootFunction: (typeof equivalentSchemaPaths)[0]['equivalentRoots'][0]['function'],
      ) => {
        let postfix: string | undefined;

        // Get the signature index we're looking for (if any)
        const lookingForSignatureIndex = extractSignatureIndex(schemaSubPath);

        const equivalentEntry = mergedEquivalentSchemaPaths.find((esp) =>
          esp.equivalentRoots.some((er) => {
            if (
              (schemaSubPath.startsWith('returnValue') ||
                schemaSubPath.startsWith('signature[')) &&
              (er.function?.name !== equivalentRootFunction?.name ||
                er.function?.filePath !== equivalentRootFunction?.filePath)
            ) {
              return false;
            }

            if (schemaSubPath === er.schemaRootPath) {
              // Additional check: if we're looking for a signature path, make sure
              // the entry doesn't already have DIFFERENT signature indices.
              // This prevents entries with signature[1], signature[2], signature[4]
              // from all being merged together.
              if (lookingForSignatureIndex !== undefined) {
                const hasConflictingSignatureIndex = esp.equivalentRoots.some(
                  (otherRoot) => {
                    // Only check roots from the same function
                    if (
                      otherRoot.function?.name !==
                        equivalentRootFunction?.name ||
                      otherRoot.function?.filePath !==
                        equivalentRootFunction?.filePath
                    ) {
                      return false;
                    }
                    const otherIndex = extractSignatureIndex(
                      otherRoot.schemaRootPath,
                    );
                    return (
                      otherIndex !== undefined &&
                      otherIndex !== lookingForSignatureIndex
                    );
                  },
                );
                if (hasConflictingSignatureIndex) {
                  return false;
                }
              }

              postfix = er.postfix;
              return true;
            }

            return false;
          }),
        );

        return { equivalentEntry, postfix };
      };

      const sortedEquivalentSchemaPaths = equivalentSchemaPaths.sort(
        (a, b) =>
          Math.max(
            ...a.equivalentRoots.map(
              (er) =>
                splitOutsideParenthesesAndArrays(er.schemaRootPath).length,
            ),
          ) -
          Math.max(
            ...b.equivalentRoots.map(
              (er) =>
                splitOutsideParenthesesAndArrays(er.schemaRootPath).length,
            ),
          ),
      );

      for (const esp of sortedEquivalentSchemaPaths) {
        checkDeadline();
        if (esp.equivalentRoots.length === 0) continue;
        let bestCandidateLength: number | undefined;
        let bestCandidate: (typeof equivalentSchemaPaths)[0] | undefined;
        let postfix: string | undefined;
        for (const equivalentRoot of esp.equivalentRoots) {
          const rootSchemaPath = equivalentRoot.schemaRootPath;
          const schemaPathParts =
            splitOutsideParenthesesAndArrays(rootSchemaPath);

          for (let i = 0; i < schemaPathParts.length; i++) {
            const subPath = joinParenthesesAndArrays(
              schemaPathParts.slice(0, i + 1),
            );

            const { equivalentEntry, postfix: equivalentEntryPostfix } =
              findEquivalentSchemaPathEntry(subPath, equivalentRoot.function);
            if (
              equivalentEntry &&
              (!bestCandidateLength || bestCandidateLength > i + 1)
            ) {
              bestCandidate = equivalentEntry;
              bestCandidateLength = i + 1;
              postfix = joinParenthesesAndArrays(
                [
                  equivalentEntryPostfix,
                  ...schemaPathParts.slice(i + 1),
                ].filter(Boolean),
              );
            }
          }
        }

        if (bestCandidate) {
          for (const root of esp.equivalentRoots) {
            if (postfix.length > 0) {
              root.postfix = postfix;
            }

            bestCandidate.equivalentRoots.push(root);
          }

          const postfixesToMerge =
            postfix.length > 0
              ? Object.keys(esp.equivalentPostfixes).reduce(
                  (acc, postfixPath) => {
                    const fullPath = joinParenthesesAndArrays([
                      postfix,
                      postfixPath,
                    ]);
                    acc[fullPath] = esp.equivalentPostfixes[postfixPath];
                    return acc;
                  },
                  {} as Record<string, string>,
                )
              : esp.equivalentPostfixes;

          bestCandidate.equivalentPostfixes = {
            ...bestCandidate.equivalentPostfixes,
            ...postfixesToMerge,
          };
        } else {
          mergedEquivalentSchemaPaths.push(esp);
        }
      }

      return mergedEquivalentSchemaPaths;
    };

    // Build a lookup of mocked dependencies to skip their internal implementation
    const mockedDependencies = new Set<string>();
    for (const dep of importedExports) {
      if (dep.isMocked) {
        mockedDependencies.add(`${dep.filePath}::${dep.name}`);
      }
    }

    gatherAllEquivalentSchemaPaths(rootScopeName, dataStructure);

    // Process dependencySchemas for all dependencies (including mocked ones)
    // dependencySchemas contains usage information (how dependencies are called),
    // not internal implementation, so we want this for mocked dependencies too
    for (const dependency of importedExports) {
      checkDeadline();
      const dependentDataStructure =
        dependencySchemas?.[dependency.filePath]?.[dependency.name];
      if (!dependentDataStructure) continue;
      gatherAllEquivalentSchemaPaths(
        dependency.name,
        dependentDataStructure,
        dependentDataStructure,
      );
    }

    for (const filePath in dependentAnalyses) {
      for (const name in dependentAnalyses[filePath]) {
        // Skip mocked dependencies - we don't want to merge in their internal implementation
        if (mockedDependencies.has(`${filePath}::${name}`)) {
          continue;
        }

        const childMergedDataStructure =
          dependentAnalyses[filePath][name].metadata?.mergedDataStructure || {};

        gatherAllEquivalentSchemaPaths(name, childMergedDataStructure as any);
      }
    }

    const gatherElapsed = Date.now() - mergeStartTime;

    equivalentSchemaPaths = mergeAllEquivalentSchemaPaths();

    const mergeEspElapsed = Date.now() - mergeStartTime;

    // Collect schemas that need cleaning — batch the calls for the end instead of
    // calling cleanSchema inside the inner root loop (which was O(roots * schemaSize)).
    const schemasToClean = new Set<{ [key: string]: string }>();

    for (const esp of equivalentSchemaPaths) {
      checkDeadline();
      // Pre-compute which postfixes have children to avoid O(n²) lookups in the inner loop.
      // A postfix "has children" if there are other postfixes that extend it.
      const postfixesWithChildren = new Set<string>();
      const postfixKeys = Object.keys(esp.equivalentPostfixes);

      // Pre-parse ALL postfix paths once. These parsed parts are reused in:
      // 1. The children detection loop below
      // 2. The inner postfix application loop (lines that split postfixPath and equivalentRoot.postfix)
      // This eliminates thousands of redundant splitOutsideParenthesesAndArrays calls.
      const postfixPartsCache = new Map<string, string[]>();
      for (const postfixPath of postfixKeys) {
        if (!postfixPath) continue;
        postfixPartsCache.set(
          postfixPath,
          splitOutsideParenthesesAndArrays(postfixPath),
        );
      }

      // Check for empty postfix having children (any other postfixes exist)
      if (postfixKeys.length > 1 && '' in esp.equivalentPostfixes) {
        postfixesWithChildren.add('');
      }

      // Check for array element postfixes having children using a prefix set.
      // This avoids O(n²) scans across large postfix lists.
      // e.g., 'currentEntities[]' has children if a path like 'currentEntities[].sha' exists.
      const postfixPrefixSet = new Set<string>();
      for (const postfixPath of postfixKeys) {
        if (!postfixPath) continue;
        const parts = postfixPartsCache.get(postfixPath)!;
        for (let i = 1; i < parts.length; i++) {
          postfixPrefixSet.add(joinParenthesesAndArrays(parts.slice(0, i)));
        }
      }
      for (const postfixPath of postfixKeys) {
        if (postfixPath.endsWith('[]') && postfixPrefixSet.has(postfixPath)) {
          postfixesWithChildren.add(postfixPath);
        }
      }

      // Deduplicate equivalentRoots that would write to the same schema paths.
      // Roots with the same (function, schemaRootPath, postfix) are redundant.
      const seenRootKeys = new Set<string>();
      const uniqueRoots = esp.equivalentRoots.filter((root) => {
        const key = `${root.function?.filePath ?? ''}::${root.function?.name ?? ''}::${root.schemaRootPath}::${root.postfix ?? ''}`;
        if (seenRootKeys.has(key)) return false;
        seenRootKeys.add(key);
        return true;
      });

      for (const equivalentRoot of uniqueRoots) {
        checkDeadline();
        let merged:
          | {
              signatureSchema: { [key: string]: string };
              returnValueSchema: { [key: string]: string };
            }
          | undefined;

        if (equivalentRoot.function) {
          merged = findOrCreateDependentSchemas(equivalentRoot.function);
        } else {
          merged = mergedDataStructure;
        }

        if (!merged) continue;

        const schema = equivalentRoot.schemaRootPath.startsWith('signature[')
          ? merged.signatureSchema
          : merged.returnValueSchema;

        // Skip if this schema has already grown past the cap
        if (Object.keys(schema).length > SCHEMA_KEY_CAP) continue;

        for (const [postfixPath, postfixValue] of Object.entries(
          esp.equivalentPostfixes,
        )) {
          checkDeadline();
          let relevantPostfix = postfixPath;
          if (equivalentRoot.postfix) {
            // Check if postfixPath starts with equivalentRoot.postfix at a path boundary.
            // Must ensure exact path part match - "entityCode" should NOT match "entity" prefix.
            // Valid: "entity.foo" starts with "entity" (boundary at '.')
            // Valid: "entity[0]" starts with "entity" (boundary at '[')
            // Invalid: "entityCode" starts with "entity" (no boundary, different property)
            if (!postfixPath.startsWith(equivalentRoot.postfix)) {
              continue;
            }
            // Additional check: ensure the match is at a path boundary
            const nextChar = postfixPath[equivalentRoot.postfix.length];
            if (
              nextChar !== undefined &&
              nextChar !== '.' &&
              nextChar !== '['
            ) {
              // The postfixPath continues with more characters that aren't a path separator.
              // This means "entity" matched "entityCode" which is wrong - they're different properties.
              continue;
            }

            const postFixPathParts =
              postfixPartsCache.get(postfixPath) ??
              splitOutsideParenthesesAndArrays(postfixPath);
            // Cache equivalentRoot.postfix parts — same root reused across all postfixes
            if (!postfixPartsCache.has(equivalentRoot.postfix)) {
              postfixPartsCache.set(
                equivalentRoot.postfix,
                splitOutsideParenthesesAndArrays(equivalentRoot.postfix),
              );
            }
            const equivalentRootPostFixParts = postfixPartsCache.get(
              equivalentRoot.postfix,
            )!;
            relevantPostfix = joinParenthesesAndArrays(
              postFixPathParts.slice(equivalentRootPostFixParts.length),
            );
          }

          const newSchemaPath = joinParenthesesAndArrays([
            equivalentRoot.schemaRootPath,
            relevantPostfix,
          ]);

          // Skip paths that would go through a primitive type
          // e.g., if schema has 'entities[].scenarioCount': 'number', skip 'entities[].scenarioCount.sha'
          if (wouldGoThroughPrimitive(newSchemaPath, schema)) {
            transformationTracer.operation(rootScopeName, {
              operation: 'skipPrimitivePath',
              stage: 'merged',
              path: newSchemaPath,
              context: {
                reason: 'would go through primitive type',
                postfixValue,
              },
            });
            continue;
          }

          // Skip setting primitive type when there are child postfixes that indicate structure.
          // This prevents downgrading an object/array element to a primitive type.
          // Uses pre-computed postfixesWithChildren Set for O(1) lookup instead of O(n) iteration.
          const hasChildPostfixes =
            (relevantPostfix === '' || relevantPostfix.endsWith('[]')) &&
            postfixesWithChildren.has(postfixPath);
          if (PRIMITIVE_TYPES.has(postfixValue) && hasChildPostfixes) {
            continue;
          }

          // Don't overwrite a more specific type with a less specific one
          // This can happen when nested roots share entries with their parent roots
          const existingType = schema[newSchemaPath];
          if (existingType) {
            // Don't overwrite a primitive type with 'object' or 'array'
            // e.g., if schema has 'entities[].scenarioCount': 'number', don't overwrite with 'object'
            if (
              PRIMITIVE_TYPES.has(existingType) &&
              (postfixValue === 'object' || postfixValue === 'array')
            ) {
              transformationTracer.operation(rootScopeName, {
                operation: 'skipTypeDowngrade',
                stage: 'merged',
                path: newSchemaPath,
                context: {
                  reason: 'would overwrite primitive with object/array',
                  existingType,
                  newType: postfixValue,
                },
              });
              continue;
            }
            // Don't overwrite a complex/union type with a primitive
            // e.g., if schema has 'scenarios[]': 'Scenario | null', don't overwrite with 'string'
            if (
              !PRIMITIVE_TYPES.has(existingType) &&
              PRIMITIVE_TYPES.has(postfixValue)
            ) {
              transformationTracer.operation(rootScopeName, {
                operation: 'skipTypeDowngrade',
                stage: 'merged',
                path: newSchemaPath,
                context: {
                  reason: 'would overwrite complex type with primitive',
                  existingType,
                  newType: postfixValue,
                },
              });
              continue;
            }
          }

          // Log the successful postfix merge
          transformationTracer.operation(rootScopeName, {
            operation: 'mergePostfix',
            stage: 'merged',
            path: newSchemaPath,
            before: existingType,
            after: postfixValue,
            context: {
              schemaRootPath: equivalentRoot.schemaRootPath,
              postfix: relevantPostfix,
              dependency: equivalentRoot.function?.name,
            },
          });
          schema[newSchemaPath] = postfixValue;
        }

        schemasToClean.add(schema);
      }
    }

    const postfixElapsed = Date.now() - mergeStartTime;

    // Batch-clean all modified schemas once (instead of once per root per ESP entry)
    for (const schema of schemasToClean) {
      cleanSchema(schema, { stage: 'afterMergePostfix' });
    }

    const cleanElapsed = Date.now() - mergeStartTime;

    // Propagate equivalency-derived attributes to generic function call variants.
    // When attributes are traced via equivalencies (e.g., fileComparisons from buildDataMap.signature[2]),
    // they get written to non-generic paths (returnValue.data.x or funcName().functionCallReturnValue.data.x).
    // If the ORIGINAL input schema has generic variants (funcName<T>().functionCallReturnValue.data),
    // we need to copy the attributes to those paths too.
    for (const filePath in mergedDataStructure.dependencySchemas) {
      for (const depName in mergedDataStructure.dependencySchemas[filePath]) {
        const depSchema =
          mergedDataStructure.dependencySchemas[filePath][depName];
        const returnValueSchema = depSchema.returnValueSchema;

        // Look at the ORIGINAL input dependencySchemas for generic variants,
        // since the merged schema may have lost them during equivalency processing
        const originalSchema = dependencySchemas?.[filePath]?.[depName];
        const schemaToSearchForGenericVariants =
          originalSchema?.returnValueSchema || returnValueSchema;

        // Find all unique generic variants of this function
        // e.g., useFetcher<BranchEntityDiffResult>() from useFetcher<BranchEntityDiffResult>().functionCallReturnValue.data
        const genericVariants = new Set<string>();
        const genericRegex = new RegExp(
          `^${depName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}<[^>]+>\\(\\)`,
        );

        for (const path in schemaToSearchForGenericVariants) {
          checkDeadline();
          const match = path.match(genericRegex);
          if (match) {
            genericVariants.add(match[0]);
          }
        }

        if (genericVariants.size === 0) continue;

        // For each returnValue. path or non-generic function call path,
        // create corresponding paths for each generic variant
        const pathsToAdd: [string, string][] = [];

        for (const path in returnValueSchema) {
          checkDeadline();
          const value = returnValueSchema[path];

          // Handle returnValue. paths
          if (path.startsWith('returnValue.')) {
            const suffix = path.slice('returnValue.'.length);
            for (const genericVariant of genericVariants) {
              const genericPath = `${genericVariant}.functionCallReturnValue.${suffix}`;
              if (!(genericPath in returnValueSchema)) {
                pathsToAdd.push([genericPath, value]);
              }
            }
          }
          // Handle non-generic function call paths like depName().functionCallReturnValue.x
          else if (path.startsWith(`${depName}().functionCallReturnValue.`)) {
            const suffix = path.slice(
              `${depName}().functionCallReturnValue.`.length,
            );
            for (const genericVariant of genericVariants) {
              const genericPath = `${genericVariant}.functionCallReturnValue.${suffix}`;
              if (!(genericPath in returnValueSchema)) {
                pathsToAdd.push([genericPath, value]);
              }
            }
          }
        }

        // Add the new generic variant paths
        for (const [path, value] of pathsToAdd) {
          returnValueSchema[path] = value;
        }
      }
    }

    // For mocked dependencies: copy paths from dependencySchemas (usage info) and normalize
    // returnValue. paths that were created by equivalency processing.
    // This ensures all paths use the consistent functionName().functionCallReturnValue. format.
    for (const dependency of importedExports) {
      if (!dependency.isMocked) continue;

      const srcSchema =
        dependencySchemas?.[dependency.filePath]?.[dependency.name];
      if (!srcSchema?.returnValueSchema) continue;

      const depSchema = findOrCreateDependentSchemas({
        filePath: dependency.filePath,
        name: dependency.name,
      });

      // First, normalize any returnValue paths that were written by equivalency processing
      // to the standard functionName().functionCallReturnValue format.
      // This includes both returnValue. (dot) and returnValue[ (array) paths.
      const pathsToNormalize: [string, string][] = [];
      for (const path in depSchema.returnValueSchema) {
        checkDeadline();
        if (
          path === 'returnValue' ||
          path.startsWith('returnValue.') ||
          path.startsWith('returnValue[')
        ) {
          pathsToNormalize.push([path, depSchema.returnValueSchema[path]]);
        }
      }
      for (const [path, value] of pathsToNormalize) {
        delete depSchema.returnValueSchema[path];
        let normalizedPath: string;
        if (path === 'returnValue') {
          normalizedPath = `${dependency.name}().functionCallReturnValue`;
        } else if (path.startsWith('returnValue.')) {
          normalizedPath = path.replace(
            /^returnValue\./,
            `${dependency.name}().functionCallReturnValue.`,
          );
        } else {
          // path.startsWith('returnValue[')
          // e.g., returnValue[] -> getOptions().functionCallReturnValue[]
          // e.g., returnValue[].label -> getOptions().functionCallReturnValue[].label
          normalizedPath = path.replace(
            /^returnValue/,
            `${dependency.name}().functionCallReturnValue`,
          );
        }
        transformationTracer.operation(rootScopeName, {
          operation: 'normalizeReturnValuePath',
          stage: 'merged',
          path: normalizedPath,
          before: path,
          after: normalizedPath,
          context: { dependency: dependency.name, value },
        });
        depSchema.returnValueSchema[normalizedPath] = value;
      }

      // Now copy paths from the source schema (dependencySchemas)
      for (const path in srcSchema.returnValueSchema) {
        checkDeadline();
        const value = srcSchema.returnValueSchema[path];

        // Normalize paths starting with 'returnValue' to use the standard format:
        // 'returnValue.foo' -> 'dependencyName().functionCallReturnValue.foo'
        // This ensures consistency across the codebase and allows constructMockCode
        // and gatherDataForMocks to work correctly.
        if (path === 'returnValue' || path.startsWith('returnValue.')) {
          // Convert 'returnValue' -> 'name().functionCallReturnValue'
          // Convert 'returnValue.foo' -> 'name().functionCallReturnValue.foo'
          const normalizedPath =
            path === 'returnValue'
              ? `${dependency.name}().functionCallReturnValue`
              : path.replace(
                  /^returnValue\./,
                  `${dependency.name}().functionCallReturnValue.`,
                );

          // Always write srcSchema values - they take precedence over equivalency-derived values
          depSchema.returnValueSchema[normalizedPath] = value;
          continue;
        }

        // Copy paths containing functionCallReturnValue (return value structures)
        // These are needed for constructMockCode to build the proper mock data hierarchy
        // Example: supabase.auth.getSession().functionCallReturnValue.data.session
        if (path.includes('.functionCallReturnValue')) {
          // Always write srcSchema values - they take precedence over equivalency-derived values
          depSchema.returnValueSchema[path] = value;
          continue;
        }

        // Copy function-typed paths that end with () (are function calls)
        // These include:
        // - Function stubs without functionCallReturnValue (like onAuthStateChange)
        // - Function markers with async-function type (like getSession(): async-function)
        //   which are needed for constructMockCode to know to generate async functions
        // Skip paths starting with 'returnValue' - they were already handled above
        if (
          ['function', 'async-function'].includes(value) &&
          path.endsWith(')') &&
          !path.startsWith('returnValue')
        ) {
          if (!(path in depSchema.returnValueSchema)) {
            depSchema.returnValueSchema[path] = value;
          }
        }

        // Copy object-typed paths for chained API access patterns (like trpc.customer.getCustomersByOrg)
        // These intermediate paths are needed for constructMockCode to build the nested mock structure.
        // Example: for trpc.customer.getCustomersByOrg.useQuery().functionCallReturnValue.data,
        // we need 'trpc', 'trpc.customer', 'trpc.customer.getCustomersByOrg' all typed as 'object'.
        // Skip paths starting with 'returnValue' - they were already handled above
        //
        // EXCEPTION: For function-style dependencies like getSupabase(), skip intermediate object
        // paths like 'getSupabase().auth' that are just property access after a function call.
        // These aren't needed because constructMockCode can infer the structure from the actual
        // function call paths like 'getSupabase().auth.getUser()'. We only need object paths
        // for object-style dependencies like 'supabase.auth' where the dependency itself is an object.
        if (value === 'object' && !path.startsWith('returnValue')) {
          // Check if this is a function-style dependency (path starts with name() or name<T>())
          const isFunctionStyleDependency =
            path.startsWith(`${dependency.name}()`) ||
            path.match(new RegExp(`^${dependency.name}<[^>]+>\\(\\)`));

          // For function-style dependencies, skip intermediate object paths
          // Only keep object paths that are within functionCallReturnValue
          if (
            isFunctionStyleDependency &&
            !path.includes('.functionCallReturnValue')
          ) {
            continue;
          }

          if (!(path in depSchema.returnValueSchema)) {
            depSchema.returnValueSchema[path] = value;
          }
        }
      }

      cleanSchema(depSchema.returnValueSchema, {
        stage: 'afterMockedDependencyMerge',
        dependency: dependency.name,
      });

      // Pull signature requirements from downstream functions into the mocked return value.
      // When a mocked function's return flows into another function's signature (via usageEquivalencies),
      // we need to include that function's signature requirements in the mock.
      //
      // Example: fromE5() returns a currency object that flows to calculateTotalPrice(price, quantity).
      // calculateTotalPrice's signatureSchema shows signature[0].multiply() is required.
      // We need to add multiply() to fromE5's mock return value.
      const usageEquivalencies = srcSchema.usageEquivalencies ?? {};
      for (const [returnPath, equivalencies] of Object.entries(
        usageEquivalencies,
      )) {
        // Only process return value paths (functionCallReturnValue)
        if (!returnPath.includes('.functionCallReturnValue')) continue;

        for (const equiv of equivalencies) {
          // Check if this equivalency points to a signature path
          const signatureMatch = equiv.schemaPath.match(
            /\.signature\[(\d+)\]$/,
          );
          if (!signatureMatch) continue;

          const targetFunctionName = cleanFunctionName(equiv.scopeNodeName);
          const signatureIndex = signatureMatch[1];

          // Look up the target function's analysis to get its signature requirements
          // First try dependentAnalyses, then dependencySchemas
          let targetSignatureSchema: Record<string, string> | undefined;

          // Check dependentAnalyses first (has the full merged analysis)
          for (const depFilePath in dependentAnalyses) {
            const analysis =
              dependentAnalyses[depFilePath]?.[targetFunctionName];
            if (analysis?.metadata?.mergedDataStructure?.signatureSchema) {
              targetSignatureSchema =
                analysis.metadata.mergedDataStructure.signatureSchema;
              break;
            }
          }

          // Fallback to dependencySchemas if not found
          if (!targetSignatureSchema) {
            for (const depFilePath in dependencySchemas) {
              const schema =
                dependencySchemas[depFilePath]?.[targetFunctionName];
              if (schema?.signatureSchema) {
                targetSignatureSchema = schema.signatureSchema;
                break;
              }
            }
          }

          if (!targetSignatureSchema) continue;

          // Find all paths in the target's signatureSchema that extend from signature[N]
          // e.g., signature[0].multiply(quantity) -> .multiply(quantity)
          const signaturePrefix = `signature[${signatureIndex}]`;
          for (const [sigPath, sigType] of Object.entries(
            targetSignatureSchema,
          )) {
            if (!sigPath.startsWith(signaturePrefix)) continue;

            // Skip the base signature[N] path itself - we only want the method/property extensions
            if (sigPath === signaturePrefix) continue;

            // Extract the suffix after signature[N] (e.g., ".multiply(quantity)")
            const suffix = sigPath.slice(signaturePrefix.length);

            // Build the path for the mocked return value
            // e.g., fromE5(priceE5).functionCallReturnValue.multiply(quantity)
            const returnValuePath = returnPath + suffix;

            // Add to the mocked dependency's return value schema if not already present
            if (!(returnValuePath in depSchema.returnValueSchema)) {
              depSchema.returnValueSchema[returnValuePath] = sigType;
            }
          }
        }
      }

      cleanSchema(depSchema.returnValueSchema, {
        stage: 'afterSignatureRequirementsMerge',
        dependency: dependency.name,
      });
    }

    // Process the input dependencySchemas FIRST (before child dependentAnalyses).
    // This ensures the parent entity's direct usage of dependencies takes precedence.
    // When both parent and child use the same dependency (e.g., useLoaderData),
    // the parent's schema paths are preserved, and child's paths are merged in later.
    //
    // Some dependencies (like .d.ts type declaration files) may not have:
    // - Equivalencies with the root scope
    // - A dependent analysis (they're just type declarations)
    // - Be marked as mocked
    // Without this, their schemas would be lost entirely.
    for (const filePath in dependencySchemas) {
      for (const name in dependencySchemas[filePath]) {
        const srcSchema = dependencySchemas[filePath][name];
        if (!srcSchema) continue;

        // Skip mocked dependencies - they were already processed above with path normalization
        if (mockedDependencies.has(`${filePath}::${name}`)) {
          continue;
        }

        // Check if this dependency was already processed by equivalencies
        const existingSchema =
          mergedDataStructure.dependencySchemas[filePath]?.[name];

        // Only add if no existing schema (equivalencies didn't process it)
        if (!existingSchema) {
          const depSchema = findOrCreateDependentSchemas({ filePath, name });
          for (const path in srcSchema.returnValueSchema) {
            checkDeadline();
            depSchema.returnValueSchema[path] =
              srcSchema.returnValueSchema[path];
          }
          for (const path in srcSchema.signatureSchema) {
            checkDeadline();
            depSchema.signatureSchema[path] = srcSchema.signatureSchema[path];
          }

          // Clean known object functions (like String.prototype.replace, Array.prototype.map)
          // from the copied schema. Without this, method call paths on primitives like
          // "projectSlug.replace(...)" would cause convertDotNotation to create nested
          // object structures instead of preserving the primitive type.
          cleanSchema(depSchema.returnValueSchema, {
            stage: 'afterDependencySchemaCopy',
            filePath,
            dependency: name,
          });
        }

        // TYPE REFINEMENT: Check if dependentAnalyses has a more specific type for this dependency.
        // When a parent passes `entity.filePath` (string | undefined) to a child component
        // that requires `filePath: string`, we should use the child's more specific type.
        // This prevents mock data from having undefined values for required props.
        //
        // This runs REGARDLESS of whether equivalencies already processed the schema,
        // because equivalencies copy the parent's type (string | undefined), not the child's
        // required type (string).
        const depSchema = findOrCreateDependentSchemas({ filePath, name });
        const childAnalysis = dependentAnalyses[filePath]?.[name];
        const childSignatureSchema =
          childAnalysis?.metadata?.mergedDataStructure?.signatureSchema;

        if (childSignatureSchema) {
          for (const path in depSchema.signatureSchema) {
            checkDeadline();
            const parentType = depSchema.signatureSchema[path];
            const childType = childSignatureSchema[path];

            if (parentType && childType) {
              // Check if parent has optional type and child has required type
              const parentIsOptional =
                parentType.includes('| undefined') ||
                parentType.includes('| null');
              const childIsOptional =
                childType.includes('| undefined') ||
                childType.includes('| null');

              // If child requires a more specific type (not optional), use it
              if (parentIsOptional && !childIsOptional) {
                depSchema.signatureSchema[path] = childType;
              }
            }
          }
        }

        // For functions with multiple different type parameters, also create separate entries
        // for each type-parameterized variant. This allows gatherDataForMocks to look up
        // the specific schema for each call signature.
        // This runs regardless of whether the base entry already existed, since we need
        // the separate variant entries for proper schema lookup.
        const baseName = cleanFunctionName(name);
        if (functionsWithMultipleTypeParams.has(baseName)) {
          // Find all unique type-parameterized call signatures in the schema
          const typeParamVariants = new Set<string>();
          for (const path of Object.keys(srcSchema.returnValueSchema)) {
            const parts = splitOutsideParenthesesAndArrays(path);
            if (
              parts.length > 0 &&
              parts[0].includes('<') &&
              parts[0].endsWith(')')
            ) {
              typeParamVariants.add(parts[0]);
            }
          }

          // Create a separate entry for each type-parameterized variant
          for (const variant of typeParamVariants) {
            const variantSchema = findOrCreateDependentSchemas({
              filePath,
              name: variant,
            });

            // Copy only paths that belong to this variant
            for (const path in srcSchema.returnValueSchema) {
              checkDeadline();
              if (path.startsWith(variant)) {
                variantSchema.returnValueSchema[path] =
                  srcSchema.returnValueSchema[path];
              }
            }
            cleanSchema(variantSchema.returnValueSchema, {
              stage: 'afterTypeVariantCopy',
              filePath,
              dependency: name,
              variant,
            });
          }
        }
      }
    }

    // Ensure ALL dependencies from dependentAnalyses are included in dependencySchemas,
    // even if they have no equivalencies with the root scope.
    // This preserves nested functionCallReturnValue paths that would otherwise be lost.
    // EXCEPT: Skip mocked dependencies - we don't want their internal implementation details.
    for (const filePath in dependentAnalyses) {
      for (const name in dependentAnalyses[filePath]) {
        checkDeadline();
        const dependentMergedDataStructure =
          dependentAnalyses[filePath][name].metadata?.mergedDataStructure;

        if (!dependentMergedDataStructure) continue;

        const isMocked = mockedDependencies.has(`${filePath}::${name}`);

        // For mocked dependencies: ONLY copy nested dependencySchemas (skip internal implementation)
        // For non-mocked dependencies: copy everything (signature, returnValue, and nested dependencySchemas)
        if (!isMocked) {
          // Create the dependency schema entry if it doesn't exist
          const depSchema = findOrCreateDependentSchemas({ filePath, name });

          // Copy over paths from the dependent's returnValueSchema.
          // Only add paths that don't already exist (don't overwrite values set by equivalencies).
          // Skip if either source or target exceeds the cap — copying 2,531 paths from
          // ArticleTable with translatePath on each takes ~1.5s for one entity.
          const srcRetSize = Object.keys(
            dependentMergedDataStructure.returnValueSchema || {},
          ).length;
          if (
            srcRetSize > SCHEMA_KEY_CAP ||
            Object.keys(depSchema.returnValueSchema).length > SCHEMA_KEY_CAP
          )
            continue;
          for (const path in dependentMergedDataStructure.returnValueSchema) {
            // Fast path: only call translatePath when the path starts with the
            // dependency name (e.g., "ArticleTable().functionCallReturnValue.x").
            // Most paths start with "returnValue" or "signature" and don't need translation.
            const translatedPath = path.startsWith(name)
              ? translatePath(path, name)
              : path;
            if (!(translatedPath in depSchema.returnValueSchema)) {
              depSchema.returnValueSchema[translatedPath] =
                dependentMergedDataStructure.returnValueSchema[path];
            }
          }

          // Copy over signature schema as well
          for (const path in dependentMergedDataStructure.signatureSchema) {
            const translatedPath = path.startsWith(name)
              ? translatePath(path, name)
              : path;
            if (!(translatedPath in depSchema.signatureSchema)) {
              depSchema.signatureSchema[translatedPath] =
                dependentMergedDataStructure.signatureSchema[path];
            }
          }
        }

        // Copy nested dependencySchemas for ALL entities (including mocked ones)
        // This represents what dependencies THIS entity uses, not its internal implementation
        if (dependentMergedDataStructure.dependencySchemas) {
          for (const depFilePath in dependentMergedDataStructure.dependencySchemas) {
            for (const depName in dependentMergedDataStructure
              .dependencySchemas[depFilePath]) {
              const nestedDepSchema =
                dependentMergedDataStructure.dependencySchemas[depFilePath][
                  depName
                ];
              const targetDepSchema = findOrCreateDependentSchemas({
                filePath: depFilePath,
                name: depName,
              });

              // Merge in the nested dependency schemas
              for (const path in nestedDepSchema.returnValueSchema) {
                checkDeadline();
                if (!(path in targetDepSchema.returnValueSchema)) {
                  const value = nestedDepSchema.returnValueSchema[path];
                  targetDepSchema.returnValueSchema[path] = value;
                }
              }

              for (const path in nestedDepSchema.signatureSchema) {
                checkDeadline();
                if (!(path in targetDepSchema.signatureSchema)) {
                  targetDepSchema.signatureSchema[path] =
                    nestedDepSchema.signatureSchema[path];
                }
              }
            }
          }
        }
      }
    }

    const totalElapsed = Date.now() - mergeStartTime;
    const retKeys = Object.keys(mergedDataStructure.returnValueSchema).length;

    // Only log phase breakdown for slow merges (>2s)
    if (totalElapsed > 2000) {
      console.log(
        `CodeYam Log Level 2: ${rootScopeName} merge phases: gather=${gatherElapsed}ms mergeESP=${mergeEspElapsed - gatherElapsed}ms postfix=${postfixElapsed - mergeEspElapsed}ms clean=${cleanElapsed - postfixElapsed}ms depCopy=${totalElapsed - cleanElapsed}ms total=${totalElapsed}ms ret=${retKeys}`,
      );
    }

    return mergedDataStructure;
  } catch (error) {
    if (error instanceof DataStructureTimeoutError) {
      // Return partial results instead of propagating the timeout.
      // By this point, mergedDataStructure has valid data from completed phases
      // (gather + mergeESP complete in <1s, postfix/clean/depCopy may be partial).
      const retKeys = Object.keys(mergedDataStructure.returnValueSchema).length;
      console.log(
        `CodeYam Log Level 1: ${rootScopeName} merge timed out — returning partial results (${retKeys} ret keys, ${Math.round((Date.now() - mergeStartTime) / 1000)}s)`,
      );
      (mergedDataStructure as any).timedOut = true;
      return mergedDataStructure;
    }
    throw error;
  }
}
