import type { TEmbeddedDataType } from "@formbricks/types/embedded-data";
import { RESERVED_FIELD_CATALOG } from "@formbricks/types/embedded-data-resolver";
import type { TSurveyBlockLogicAction, TSurveyBlocks } from "@formbricks/types/surveys/blocks";
import { getCopiedOptionsIssues } from "@formbricks/types/surveys/copied-options";
import {
  type TExpressionTypeContext,
  getSetValueExpressionIssues,
} from "@formbricks/types/surveys/expression-types";
import type { TExpression } from "@formbricks/types/surveys/expressions";
import type { TConditionGroup, TDynamicLogicFieldValue } from "@formbricks/types/surveys/logic";
import {
  type TFindMatrix,
  findUnknownMatrixIds,
  getMatrixLookup,
} from "@formbricks/types/surveys/matrix-conditions";
import { type TOptionListKey, getOptionLists } from "@formbricks/types/surveys/show-if";
import type { TSurveyEndings, TSurveyHiddenFields, TSurveyVariables } from "@formbricks/types/surveys/types";
import { capInvalidParams } from "@/app/api/v3/lib/invalid-params";
import type { InvalidParam } from "@/app/api/v3/lib/response";
import { getBooleanCalculateIssue } from "./boolean-assign-validation";

type TReferenceValidationInput = {
  blocks: TSurveyBlocks;
  endings: TSurveyEndings;
  hiddenFields: TSurveyHiddenFields;
  metadata?: unknown;
  variables: TSurveyVariables;
  welcomeCard?: unknown;
  /** ENG-6930's typed fields, when the document carries them: a computed date is declared only here. */
  embeddedFields?: { storageKey?: string; source?: string; dataType?: TEmbeddedDataType }[];
};

type TNamedReference = {
  id: string;
  path: string;
  namespace: "block" | "element" | "ending" | "hiddenField" | "variable" | "variableName";
};

type TReferenceLookup = {
  elementIds: Set<string>;
  variableIds: Set<string>;
  hiddenFieldIds: Set<string>;
  findMatrix: TFindMatrix;
};
type TInvalidParamReferenceType = Exclude<InvalidParam["referenceType"], undefined>;

/**
 * The response boundary for survey validation problems: every 422 the surveys API sends is built from
 * an instance of this, so the `invalid_params` cap lives here (ENG-3384). The validators themselves
 * return full lists — `getIntroducedIssues` diffs the merged document's against the stored survey's,
 * and capping before that comparison would blame the stored survey for a new problem past the cap.
 */
export class V3SurveyReferenceValidationError extends Error {
  invalidParams: InvalidParam[];

  constructor(invalidParams: InvalidParam[]) {
    super("Survey contains invalid references");
    this.name = "V3SurveyReferenceValidationError";
    this.invalidParams = capInvalidParams(invalidParams, "survey", "survey");
  }
}

export type TV3SurveyReferenceValidationResult =
  | { ok: true; invalidParams: [] }
  | { ok: false; invalidParams: InvalidParam[] };

function addDuplicateIdIssues(
  entries: { id: string; path: string }[],
  label: string,
  referenceType: TInvalidParamReferenceType,
  issues: InvalidParam[]
): void {
  const firstPathById = new Map<string, string>();

  entries.forEach(({ id, path }) => {
    const firstPath = firstPathById.get(id);
    if (firstPath !== undefined) {
      issues.push({
        name: path,
        reason: `${label} id '${id}' is duplicated; first used at ${firstPath}`,
        code: "duplicate_identifier",
        identifier: id,
        referenceType,
        firstUsedAt: firstPath,
      });
      return;
    }

    firstPathById.set(id, path);
  });
}

function addDuplicateValueIssues(
  values: string[],
  pathForIndex: (index: number) => string,
  label: string,
  referenceType: TInvalidParamReferenceType,
  issues: InvalidParam[]
): void {
  const firstIndexByValue = new Map<string, number>();

  values.forEach((value, index) => {
    const firstIndex = firstIndexByValue.get(value);
    if (firstIndex !== undefined) {
      issues.push({
        name: pathForIndex(index),
        reason: `${label} '${value}' is duplicated; first used at ${pathForIndex(firstIndex)}`,
        code: "duplicate_identifier",
        identifier: value,
        referenceType,
        firstUsedAt: pathForIndex(firstIndex),
      });
      return;
    }

    firstIndexByValue.set(value, index);
  });
}

function addCrossNamespaceCollisionIssues(entries: TNamedReference[], issues: InvalidParam[]): void {
  const firstEntryById = new Map<string, TNamedReference>();

  entries.forEach((entry) => {
    const lookupId = entry.id.toLowerCase();
    const firstEntry = firstEntryById.get(lookupId);

    if (!firstEntry) {
      firstEntryById.set(lookupId, entry);
      return;
    }

    if (firstEntry.namespace === entry.namespace) {
      return;
    }

    issues.push({
      name: entry.path,
      reason: `${entry.namespace} identifier '${entry.id}' conflicts with ${firstEntry.namespace} identifier at ${firstEntry.path}`,
      code: "duplicate_identifier",
      identifier: entry.id,
      referenceType: entry.namespace,
      conflictsWith: firstEntry.path,
    });
  });
}

function isPlainObject(value: unknown): value is Record<string, unknown> {
  return typeof value === "object" && value !== null && !Array.isArray(value);
}

function addRecallReferenceIssues(
  value: unknown,
  path: string,
  references: TReferenceLookup,
  issues: InvalidParam[]
): void {
  if (typeof value === "string") {
    // One report per distinct id per field: a single label can repeat a `#recall:` token as often as
    // the 2 MB body allows, and every repeat was its own entry (ENG-3384). The list is returned in
    // full — `getIntroducedIssues` compares it with the stored survey's — and capped at the response.
    const seen = new Set<string>();

    for (const match of value.matchAll(/#recall:([A-Za-z0-9_-]+)/g)) {
      const recallId = match[1];
      if (seen.has(recallId)) {
        continue;
      }
      seen.add(recallId);

      const isKnownReference =
        references.elementIds.has(recallId) ||
        references.variableIds.has(recallId) ||
        references.hiddenFieldIds.has(recallId);

      if (!isKnownReference) {
        issues.push({
          name: path,
          reason: `Recall reference '${recallId}' is not defined in blocks, variables, or hiddenFields.fieldIds`,
          code: "dangling_reference",
          identifier: recallId,
          referenceType: "recall",
          missingId: recallId,
        });
      }
    }

    return;
  }

  if (Array.isArray(value)) {
    value.forEach((entry, index) => addRecallReferenceIssues(entry, `${path}.${index}`, references, issues));
    return;
  }

  if (!isPlainObject(value)) {
    return;
  }

  Object.entries(value).forEach(([key, entry]) => {
    addRecallReferenceIssues(entry, path ? `${path}.${key}` : key, references, issues);
  });
}

function addMetadataRecallReferenceIssues(
  metadata: unknown,
  references: TReferenceLookup,
  issues: InvalidParam[]
): void {
  if (!isPlainObject(metadata)) {
    return;
  }

  addRecallReferenceIssues(metadata.title, "metadata.title", references, issues);
  addRecallReferenceIssues(metadata.description, "metadata.description", references, issues);
}

function validateDynamicOperand(
  operand: TDynamicLogicFieldValue,
  path: string,
  references: TReferenceLookup,
  issues: InvalidParam[]
): void {
  if (operand.type === "element" && !references.elementIds.has(operand.value)) {
    issues.push({
      name: `${path}.value`,
      reason: `Element id '${operand.value}' is not defined in blocks`,
      code: "dangling_reference",
      identifier: operand.value,
      referenceType: "element",
      missingId: operand.value,
    });
  }

  if (operand.type === "variable" && !references.variableIds.has(operand.value)) {
    issues.push({
      name: `${path}.value`,
      reason: `Variable id '${operand.value}' is not defined in variables`,
      code: "dangling_reference",
      identifier: operand.value,
      referenceType: "variable",
      missingId: operand.value,
    });
  }

  if (operand.type === "hiddenField" && !references.hiddenFieldIds.has(operand.value)) {
    issues.push({
      name: `${path}.value`,
      reason: `Hidden field id '${operand.value}' is not defined in hiddenFields.fieldIds`,
      code: "dangling_reference",
      identifier: operand.value,
      referenceType: "hiddenField",
      missingId: operand.value,
    });
  }

  // `reserved` has no arm on purpose, and it is checked by a test rather than left to be inferred
  // from the absence of code (ENG-2538). A reserved operand names a `RESERVED_FIELD_CATALOG` entry,
  // which is a static list in code rather than anything declared on the survey — so there are no
  // references to dangle against. Validating it against the catalog would also be actively wrong:
  // `ZDynamicReservedField` deliberately checks the name as non-empty only, so that a survey
  // authored against a newer catalog still round-trips through an older self-hosted deployment.
  // An operand naming an entry that does not exist resolves as unset, exactly like a stale variable.
}

/**
 * A Set value expression (ENG-6935): every reference leaf is checked like a condition operand, so a
 * dangling one is named by its exact path into the tree; once they all resolve, the shared type check
 * (`getSetValueExpressionIssues`, the one `surveyRefinement` runs) names text in arithmetic or a result
 * the target field can't hold, so the dry-run validate catches what a save would refuse.
 */
function validateExpressionValue(
  expression: TExpression,
  targetVariableId: string,
  path: string,
  input: TReferenceValidationInput,
  references: TReferenceLookup,
  issues: InvalidParam[]
): void {
  const before = issues.length;
  const walk = (node: TExpression, nodePath: string): void => {
    if (node.type === "call") {
      node.args.forEach((arg, idx) => walk(arg, `${nodePath}.args.${String(idx)}`));
    } else if (node.type !== "static") {
      validateDynamicOperand(node, nodePath, references, issues);
    }
  };
  walk(expression, path);

  const targetDataType = getComputedFieldDataTypes(input).get(targetVariableId);
  if (issues.length > before || targetDataType === undefined) return;

  for (const issue of getSetValueExpressionIssues(expression, targetDataType, getTypeContext(input))) {
    issues.push({ name: [path, ...issue.path].join("."), reason: issue.message });
  }
}

/**
 * The value of a calculate action: a Set value expression, a reference, or (ENG-6973) a value the
 * true/false rules refuse, as the save's refinement does. A dangling reference is named as one rather
 * than as a refused true/false value.
 */
function validateCalculateActionValue(
  action: Extract<TSurveyBlockLogicAction, { objective: "calculate" }>,
  actionPath: string,
  input: TReferenceValidationInput,
  typeContext: TExpressionTypeContext,
  references: TReferenceLookup,
  issues: InvalidParam[]
): void {
  const booleanIssue = getBooleanCalculateIssue(action, `${actionPath}.value`, typeContext);
  const before = issues.length;
  if (action.value.type === "expression") {
    // A true/false field takes no expression, so a refused one is not type-checked as well.
    if (!booleanIssue) {
      validateExpressionValue(
        action.value.value,
        action.variableId,
        `${actionPath}.value.value`,
        input,
        references,
        issues
      );
    }
  } else if (action.value.type !== "static") {
    validateDynamicOperand(action.value, `${actionPath}.value`, references, issues);
  }
  if (booleanIssue && issues.length === before) issues.push(booleanIssue);
}

/** The typed fields of one source, by storage key; a `dataType` left out is the default `string`. */
function getTypedFields(
  embeddedFields: NonNullable<TReferenceValidationInput["embeddedFields"]>,
  source: "computed" | "ingested"
): [string, TEmbeddedDataType][] {
  return embeddedFields.flatMap((field) =>
    field.source === source && field.storageKey !== undefined
      ? [[field.storageKey, field.dataType ?? "string"] as [string, TEmbeddedDataType]]
      : []
  );
}

/** Computed fields by storage key: the typed rows when sent (a computed date lives only there), else `variables`. */
function getComputedFieldDataTypes(input: TReferenceValidationInput): Map<string, TEmbeddedDataType> {
  if (input.embeddedFields !== undefined) {
    return new Map(getTypedFields(input.embeddedFields, "computed"));
  }
  return new Map(
    input.variables.map((variable) => [variable.id, variable.type === "number" ? "number" : "string"])
  );
}

function getTypeContext(input: TReferenceValidationInput): TExpressionTypeContext {
  const elements = new Map(
    input.blocks.flatMap((block) => block.elements).map((element) => [element.id, element])
  );
  const computed = getComputedFieldDataTypes(input);
  const ingested = new Map<string, TEmbeddedDataType>(
    input.embeddedFields !== undefined
      ? getTypedFields(input.embeddedFields, "ingested")
      : (input.hiddenFields.fieldIds ?? []).map((id) => [id, "string"])
  );

  return {
    getElement: (elementId) => {
      const element = elements.get(elementId);
      if (!element) return undefined;
      return { type: element.type, inputType: "inputType" in element ? element.inputType : undefined };
    },
    getComputedFieldType: (storageKey) => computed.get(storageKey),
    getIngestedFieldType: (storageKey) => ingested.get(storageKey),
    getReservedFieldType: (name) => RESERVED_FIELD_CATALOG.find((entry) => entry.name === name)?.dataType,
  };
}

type TSurveyBlock = TSurveyBlocks[number];
type TSurveyBlockElement = TSurveyBlock["elements"][number];

/** Whose show-if a visit is: the block's, an element's, or one of an element's options, rows or columns. */
type TShowIfOwner =
  | { kind: "block" }
  | { kind: "element"; element: TSurveyBlockElement; elementIndex: number }
  | {
      kind: "option";
      element: TSurveyBlockElement;
      elementIndex: number;
      listKey: TOptionListKey;
      itemId: string;
    };

/**
 * Every show-if of a block, in document order, with its path and owner: the block's own (ENG-6931), its
 * elements' and their options', rows' and columns' (ENG-6937). The one walk the reference and the
 * precedence checks share.
 */
function forEachShowIf(
  block: TSurveyBlock,
  blockIndex: number,
  visit: (showIf: TConditionGroup, path: string, owner: TShowIfOwner) => void
): void {
  if (block.showIf) visit(block.showIf, `blocks.${blockIndex}.showIf`, { kind: "block" });
  block.elements.forEach((element, elementIndex) => {
    const elementPath = `blocks.${blockIndex}.elements.${elementIndex}`;
    if (element.showIf) {
      visit(element.showIf, `${elementPath}.showIf`, { kind: "element", element, elementIndex });
    }
    for (const { listKey, items } of getOptionLists(element)) {
      items.forEach((item, itemIndex) => {
        if (!item.showIf) return;
        visit(item.showIf, `${elementPath}.${listKey}.${itemIndex}.showIf`, {
          kind: "option",
          element,
          elementIndex,
          listKey,
          itemId: item.id,
        });
      });
    }
  });
}

function validateConditionGroup(
  conditionGroup: TConditionGroup,
  path: string,
  references: TReferenceLookup,
  issues: InvalidParam[],
  isRoot = true
): void {
  // ENG-6934: a matrix row or column id the matrix doesn't have. That walk covers nested groups.
  if (isRoot) {
    for (const issue of findUnknownMatrixIds(conditionGroup, references.findMatrix, [])) {
      issues.push({
        name: [path, ...issue.path].join("."),
        reason: issue.message.replace("Conditional Logic: ", ""),
        code: "dangling_reference",
        identifier: issue.id,
        referenceType: "element",
        missingId: issue.id,
      });
    }
  }

  conditionGroup.conditions.forEach((condition, index) => {
    const conditionPath = `${path}.conditions.${index}`;

    if ("conditions" in condition) {
      validateConditionGroup(condition, conditionPath, references, issues, false);
      return;
    }

    validateDynamicOperand(condition.leftOperand, `${conditionPath}.leftOperand`, references, issues);

    if (condition.rightOperand?.type && condition.rightOperand.type !== "static") {
      validateDynamicOperand(condition.rightOperand, `${conditionPath}.rightOperand`, references, issues);
    }
  });
}

export function getV3SurveyReferenceInvalidParams(input: TReferenceValidationInput): InvalidParam[] {
  const issues: InvalidParam[] = [];
  // Built once: every calculate action reads its fields' types from it (ENG-6973).
  const typeContext = getTypeContext(input);
  const blockIds = input.blocks.map((block) => block.id);
  const blockEntries = input.blocks.map((block, index) => ({
    id: block.id,
    path: `blocks.${index}.id`,
  }));
  const endingIds = input.endings.map((ending) => ending.id);
  const endingEntries = input.endings.map((ending, index) => ({
    id: ending.id,
    path: `endings.${index}.id`,
  }));
  const elementEntries = input.blocks.flatMap((block, blockIndex) =>
    block.elements.map((element, elementIndex) => ({
      id: element.id,
      path: `blocks.${blockIndex}.elements.${elementIndex}.id`,
    }))
  );
  const elementIds = elementEntries.map((element) => element.id);
  const hiddenFieldIds = input.hiddenFields.fieldIds ?? [];
  const hiddenFieldEntries = hiddenFieldIds.map((id, index) => ({
    id,
    path: `hiddenFields.fieldIds.${index}`,
  }));
  const variableIds = input.variables.map((variable) => variable.id);
  // A computed date (ENG-6935) is declared only in the typed `embeddedFields`, never in `variables`.
  const computedOnlyIds = getTypedFields(input.embeddedFields ?? [], "computed")
    .map(([storageKey]) => storageKey)
    .filter((storageKey) => !variableIds.includes(storageKey));
  const variableIdEntries = variableIds.map((id, index) => ({
    id,
    path: `variables.${index}.id`,
  }));
  const variableNames = input.variables.map((variable) => variable.name);
  const variableNameEntries = variableNames.map((id, index) => ({
    id,
    path: `variables.${index}.name`,
  }));
  const navigationTargetIds = new Set([...blockIds, ...endingIds]);
  const navigationTargetReferenceTypes = new Map<string, "block" | "ending">([
    ...blockIds.map((id) => [id, "block"] as const),
    ...endingIds.map((id) => [id, "ending"] as const),
  ]);
  const references = {
    elementIds: new Set(elementIds),
    variableIds: new Set([...variableIds, ...computedOnlyIds]),
    hiddenFieldIds: new Set(hiddenFieldIds),
    findMatrix: getMatrixLookup(input.blocks),
  };

  addDuplicateIdIssues(blockEntries, "Block", "block", issues);
  addDuplicateIdIssues(endingEntries, "Ending", "ending", issues);
  addDuplicateIdIssues(elementEntries, "Element", "element", issues);
  addDuplicateIdIssues(variableIdEntries, "Variable", "variable", issues);
  addDuplicateValueIssues(
    hiddenFieldIds,
    (index) => `hiddenFields.fieldIds.${index}`,
    "Hidden field id",
    "hiddenField",
    issues
  );
  addDuplicateValueIssues(
    variableNames,
    (index) => `variables.${index}.name`,
    "Variable name",
    "variableName",
    issues
  );
  addCrossNamespaceCollisionIssues(
    [
      ...blockEntries.map((entry) => ({ ...entry, namespace: "block" as const })),
      ...elementEntries.map((entry) => ({ ...entry, namespace: "element" as const })),
      ...endingEntries.map((entry) => ({ ...entry, namespace: "ending" as const })),
      ...hiddenFieldEntries.map((entry) => ({ ...entry, namespace: "hiddenField" as const })),
      ...variableIdEntries.map((entry) => ({ ...entry, namespace: "variable" as const })),
      ...variableNameEntries.map((entry) => ({ ...entry, namespace: "variableName" as const })),
    ],
    issues
  );

  input.blocks.forEach((block, blockIndex) => {
    // A local so the narrowing survives into the deferred builders below.
    const logicFallback = block.logicFallback;

    if (logicFallback && !block.logic?.length) {
      issues.push({
        name: `blocks.${blockIndex}.logicFallback`,
        reason:
          "logicFallback requires at least one logic rule on the same block; omit logicFallback for normal sequential flow or add blocks[].logic",
        code: "invalid_reference",
        identifier: logicFallback,
        referenceType: navigationTargetReferenceTypes.get(logicFallback) ?? "block",
      });
    }

    if (logicFallback && logicFallback === block.id) {
      issues.push({
        name: `blocks.${blockIndex}.logicFallback`,
        reason: "logicFallback cannot target the same block",
        code: "invalid_reference",
        identifier: logicFallback,
        referenceType: "block",
      });
    }

    if (logicFallback && !navigationTargetIds.has(logicFallback)) {
      issues.push({
        name: `blocks.${blockIndex}.logicFallback`,
        reason: `Logic fallback target '${logicFallback}' is not defined in blocks or endings`,
        code: "dangling_reference",
        identifier: logicFallback,
        referenceType: "block",
        missingId: logicFallback,
      });
    }

    // ENG-6931 / ENG-6937: block, element, option, row and column show-if reference answers, fields and
    // variables like logic conditions.
    forEachShowIf(block, blockIndex, (showIf, path) => {
      validateConditionGroup(showIf, path, references, issues);
    });

    block.logic?.forEach((logic, logicIndex) => {
      const logicPath = `blocks.${blockIndex}.logic.${logicIndex}`;
      validateConditionGroup(logic.conditions, `${logicPath}.conditions`, references, issues);

      logic.actions.forEach((action, actionIndex) => {
        const actionPath = `${logicPath}.actions.${actionIndex}`;

        if (action.objective === "calculate") {
          if (!references.variableIds.has(action.variableId)) {
            issues.push({
              name: `${actionPath}.variableId`,
              reason: `Variable id '${action.variableId}' is not defined in variables`,
              code: "dangling_reference",
              identifier: action.variableId,
              referenceType: "variable",
              missingId: action.variableId,
            });
          }

          validateCalculateActionValue(action, actionPath, input, typeContext, references, issues);
        }

        if (action.objective === "requireAnswer" && !references.elementIds.has(action.target)) {
          issues.push({
            name: `${actionPath}.target`,
            reason: `Element id '${action.target}' is not defined in blocks`,
            code: "dangling_reference",
            identifier: action.target,
            referenceType: "element",
            missingId: action.target,
          });
        }

        if (action.objective === "jumpToBlock" && !navigationTargetIds.has(action.target)) {
          issues.push({
            name: `${actionPath}.target`,
            reason: `Jump target '${action.target}' is not defined in blocks or endings`,
            code: "dangling_reference",
            identifier: action.target,
            referenceType: "block",
            missingId: action.target,
          });
        }
      });
    });
  });

  // ENG-6938: the question `optionsCopiedFrom` names must exist and have options of the same kind. A
  // source below the question is an ordering rule, reported with the others below.
  for (const issue of getCopiedOptionsIssues(input.blocks)) {
    if (issue.kind === "later_source") continue;
    const isMissing = issue.kind === "missing_source";
    issues.push({
      name: issue.path.join("."),
      reason: issue.message.replace("Copied options: ", ""),
      code: isMissing ? "dangling_reference" : "invalid_reference",
      identifier: issue.sourceId,
      referenceType: "element",
      ...(isMissing ? { missingId: issue.sourceId } : {}),
    });
  }

  addRecallReferenceIssues(input.blocks, "blocks", references, issues);
  addRecallReferenceIssues(input.endings, "endings", references, issues);
  addRecallReferenceIssues(input.welcomeCard, "welcomeCard", references, issues);
  addMetadataRecallReferenceIssues(input.metadata, references, issues);

  return issues;
}

export function validateV3SurveyReferences(
  input: TReferenceValidationInput
): TV3SurveyReferenceValidationResult {
  const invalidParams = getV3SurveyReferenceInvalidParams(input);

  if (invalidParams.length > 0) {
    return { ok: false, invalidParams };
  }

  return { ok: true, invalidParams: [] };
}

export function assertValidV3SurveyReferences(input: TReferenceValidationInput): void {
  const result = validateV3SurveyReferences(input);

  if (!result.ok) {
    throw new V3SurveyReferenceValidationError(result.invalidParams);
  }
}

/**
 * Ordering rules (ENG-3069).
 *
 * The existing checks above verify that a reference *resolves*; none of them cares where the target
 * sits in the flow. That gap only mattered while reordering meant hand-rewriting the whole `blocks`
 * array — rare enough that nobody hit it. A one-call reorder makes it routine, so a survey that
 * recalls an answer the respondent has not given yet becomes easy to create, and it passes every
 * other server check.
 *
 * The rules, each mirroring what the editor or the shared refinement already enforces:
 *
 *  - a recall of an element must point strictly backwards in flat element order
 *    (`recall-item-select.tsx` filters the picker the same way);
 *  - a logic condition's element left operand must not sit in a later block, same block allowed
 *    (mirrors `validateBlockConditions` in `packages/types/surveys/types.ts`);
 *  - a `requireAnswer` target must sit in a *later* block (mirrors `validateBlockActions`);
 *  - a show-if may use only what comes before it (ENG-6931, mirrors `validateShowIf`): a block's
 *    show-if earlier blocks only, an element's show-if earlier blocks plus elements above it on the
 *    same block. Both operands of a condition are checked.
 *  - `optionsCopiedFrom` names an element before it (ENG-6938, mirrors `getCopiedOptionsIssues`).
 *
 * `jumpToBlock` and `logicFallback` deliberately have no ordering rule — jumping backwards is a
 * legitimate survey design, and only cycles are policed.
 *
 * Violations carry a stable key so the patch path can report only the ones a request *introduces*.
 * The key never contains an array index: a reorder shifts every index, and diffing on those would
 * report the whole survey as newly broken.
 */
type TPrecedenceViolation = { key: string; issue: InvalidParam };

type TElementPosition = { blockIndex: number; flatIndex: number; path: string };

function buildElementPositions(blocks: TSurveyBlocks): Map<string, TElementPosition> {
  const positions = new Map<string, TElementPosition>();
  let flatIndex = 0;

  blocks.forEach((block, blockIndex) => {
    block.elements.forEach((element, elementIndex) => {
      // First occurrence wins; duplicates are already reported as duplicate_identifier.
      if (!positions.has(element.id)) {
        positions.set(element.id, {
          blockIndex,
          flatIndex,
          path: `blocks.${blockIndex}.elements.${elementIndex}`,
        });
      }
      flatIndex += 1;
    });
  });

  return positions;
}

function misorderedIssue(
  name: string,
  reason: string,
  identifier: string,
  referenceType: TInvalidParamReferenceType
): InvalidParam {
  return { name, reason, code: "misordered_reference", identifier, referenceType };
}

/**
 * First-wins collector for precedence violations, deduping at insert rather than at the end.
 *
 * `build` is a thunk on purpose. The issue carries a sentence of a hundred-odd characters, and a
 * single field can repeat one `#recall:` token as many times as the 2 MB body allows — tens of
 * thousands of occurrences that all collapse to one report. Building each issue and then discarding
 * it bounded the response while leaving the allocation unbounded, which is the same half-fix the
 * order diagnostics needed (ENG-1652). Deferring construction makes the cost proportional to the
 * distinct violations, which the document's own structure bounds.
 */
function addViolation(
  violations: Map<string, TPrecedenceViolation>,
  key: string,
  build: () => InvalidParam
): void {
  if (violations.has(key)) {
    return;
  }

  violations.set(key, { key, issue: build() });
}

/** Report every `#recall:` token in one string that points at or after `position`. */
function addRecallViolationsInText(
  text: string,
  path: string,
  position: number,
  scopeKey: string,
  positions: Map<string, TElementPosition>,
  violations: Map<string, TPrecedenceViolation>
): void {
  for (const match of text.matchAll(/#recall:([A-Za-z0-9_-]+)/g)) {
    const recallId = match[1];
    const target = positions.get(recallId);
    // Unknown ids, variables and hidden fields are not position-checked: the first is a dangling
    // reference (reported elsewhere) and the other two are available from the start.
    if (!target || target.flatIndex < position) {
      continue;
    }

    addViolation(violations, `recall|${scopeKey}|${recallId}`, () =>
      misorderedIssue(
        path,
        position < 0
          ? `Recall reference '${recallId}' cannot be used here because no element has been answered yet; only hidden fields and variables can be recalled before the first block`
          : `Recall reference '${recallId}' points at an element that appears later in the survey (${target.path}); a recall can only use elements shown before it`,
        recallId,
        "recall"
      )
    );
  }
}

/** Walk any nested value for `#recall:` tokens, reporting those that point at or after `position`. */
function addRecallPrecedenceViolations(
  value: unknown,
  path: string,
  position: number,
  scopeKey: string,
  positions: Map<string, TElementPosition>,
  violations: Map<string, TPrecedenceViolation>
): void {
  if (typeof value === "string") {
    addRecallViolationsInText(value, path, position, scopeKey, positions, violations);
    return;
  }

  if (Array.isArray(value)) {
    value.forEach((entry, index) =>
      addRecallPrecedenceViolations(entry, `${path}.${index}`, position, scopeKey, positions, violations)
    );
    return;
  }

  if (!isPlainObject(value)) {
    return;
  }

  for (const [key, entry] of Object.entries(value)) {
    // Logic runs at block submit, by which point the block's own answers exist — walking it here
    // would flag a same-block recall that is actually fine.
    if (key === "logic") continue;
    addRecallPrecedenceViolations(
      entry,
      path ? `${path}.${key}` : key,
      position,
      scopeKey,
      positions,
      violations
    );
  }
}

function forEachSingleCondition(
  group: TConditionGroup,
  path: string,
  visit: (
    condition: { leftOperand: TDynamicLogicFieldValue; rightOperand?: { type: string; value?: unknown } },
    conditionPath: string
  ) => void
): void {
  group.conditions.forEach((condition, index) => {
    const conditionPath = `${path}.conditions.${index}`;
    if ("conditions" in condition) {
      forEachSingleCondition(condition, conditionPath, visit);
      return;
    }
    visit(condition, conditionPath);
  });
}

function getV3SurveyPrecedenceViolations(input: TReferenceValidationInput): TPrecedenceViolation[] {
  const positions = buildElementPositions(input.blocks);
  const violations = new Map<string, TPrecedenceViolation>();

  // Before the first element: an element recall here can never resolve to an answer.
  addRecallPrecedenceViolations(input.welcomeCard, "welcomeCard", -1, "welcomeCard", positions, violations);
  if (isPlainObject(input.metadata)) {
    for (const key of ["title", "description"] as const) {
      addRecallPrecedenceViolations(
        input.metadata[key],
        `metadata.${key}`,
        -1,
        `metadata.${key}`,
        positions,
        violations
      );
    }
  }

  input.blocks.forEach((block, blockIndex) => {
    const firstElementFlatIndex = positions.get(block.elements[0]?.id ?? "")?.flatIndex ?? 0;

    // Block-level labels render with the block, so they may only recall earlier blocks' answers.
    for (const key of ["name", "buttonLabel", "backButtonLabel"] as const) {
      addRecallPrecedenceViolations(
        block[key],
        `blocks.${blockIndex}.${key}`,
        firstElementFlatIndex,
        `block:${block.id}`,
        positions,
        violations
      );
    }

    block.elements.forEach((element, elementIndex) => {
      const position = positions.get(element.id);
      addRecallPrecedenceViolations(
        element,
        `blocks.${blockIndex}.elements.${elementIndex}`,
        position?.flatIndex ?? 0,
        `element:${element.id}`,
        positions,
        violations
      );
    });

    // Show-if: what the respondent has answered before this block (or this element) is shown.
    const addShowIfViolations = (
      group: TConditionGroup,
      path: string,
      scopeKey: string,
      canUse: (target: TElementPosition) => boolean,
      rule: string
    ) =>
      forEachSingleCondition(group, path, (condition, conditionPath) => {
        for (const [side, operand] of [
          ["leftOperand", condition.leftOperand],
          ["rightOperand", condition.rightOperand],
        ] as const) {
          if (operand?.type !== "element" || typeof operand.value !== "string") continue;
          const elementId = operand.value;
          const target = positions.get(elementId);
          if (!target || canUse(target)) continue;

          // eslint-disable-next-line sonarjs/no-nested-functions -- a thunk on purpose, so a repeated violation builds no issue (see addViolation)
          addViolation(violations, `showIf|${scopeKey}|${elementId}`, () =>
            misorderedIssue(
              `${conditionPath}.${side}.value`,
              `Show-if references element '${elementId}' (${target.path}), which is not before it; ${rule}`,
              elementId,
              "element"
            )
          );
        }
      });

    forEachShowIf(block, blockIndex, (showIf, path, owner) => {
      if (owner.kind === "block") {
        addShowIfViolations(
          showIf,
          path,
          `block:${block.id}`,
          (target) => target.blockIndex < blockIndex,
          "a block's show-if can only use elements from earlier blocks"
        );
        return;
      }
      const { element, elementIndex } = owner;
      const ownFlatIndex = positions.get(element.id)?.flatIndex ?? firstElementFlatIndex + elementIndex;
      // Earlier blocks, or above it on the same block: strictly before it in flat order. ENG-6937: an
      // option, a row or a column follows its element's rule.
      const isBefore = (target: TElementPosition) => target.flatIndex < ownFlatIndex;
      if (owner.kind === "element") {
        addShowIfViolations(
          showIf,
          path,
          `element:${element.id}`,
          isBefore,
          "an element's show-if can only use elements from earlier blocks or above it on the same block"
        );
        return;
      }
      addShowIfViolations(
        showIf,
        path,
        `${owner.listKey}:${element.id}:${owner.itemId}`,
        isBefore,
        "an option's show-if can only use elements from earlier blocks or above its element on the same block"
      );
    });

    block.logic?.forEach((logic, logicIndex) => {
      const logicPath = `blocks.${blockIndex}.logic.${logicIndex}`;

      forEachSingleCondition(logic.conditions, logicPath, (condition, conditionPath) => {
        if (condition.leftOperand.type !== "element") return;
        const target = positions.get(condition.leftOperand.value);
        if (!target || target.blockIndex <= blockIndex) return;

        // eslint-disable-next-line sonarjs/no-nested-functions -- a thunk on purpose, so a repeated violation builds no issue (see addViolation)
        addViolation(violations, `condition|${block.id}|${condition.leftOperand.value}`, () =>
          misorderedIssue(
            `${conditionPath}.leftOperand.value`,
            `Condition references element '${condition.leftOperand.value}' in a later block (blocks.${target.blockIndex}); logic in blocks.${blockIndex} can only evaluate elements from the same or an earlier block`,
            condition.leftOperand.value,
            "element"
          )
        );
      });

      logic.actions.forEach((action, actionIndex) => {
        if (action.objective !== "requireAnswer") return;
        const target = positions.get(action.target);
        if (!target || target.blockIndex > blockIndex) return;

        // eslint-disable-next-line sonarjs/no-nested-functions -- a thunk on purpose, so a repeated violation builds no issue (see addViolation)
        addViolation(violations, `requireAnswer|${block.id}|${action.target}`, () =>
          misorderedIssue(
            `${logicPath}.actions.${actionIndex}.target`,
            target.blockIndex === blockIndex
              ? `requireAnswer target '${action.target}' is in the same block (blocks.${blockIndex}); requireAnswer must target an element in a later block`
              : `requireAnswer target '${action.target}' is in an earlier block (blocks.${target.blockIndex}); requireAnswer must target an element in a later block`,
            action.target,
            "element"
          )
        );
      });
    });
  });

  // ENG-6938: options may be copied only from a question above (earlier blocks, or above it on its page).
  for (const issue of getCopiedOptionsIssues(input.blocks)) {
    if (issue.kind !== "later_source") continue;
    const [, blockIndex, , elementIndex] = issue.path;
    const elementId = input.blocks[blockIndex as number]?.elements[elementIndex as number]?.id ?? "";
    addViolation(violations, `optionsCopiedFrom|${elementId}|${issue.sourceId}`, () =>
      misorderedIssue(
        issue.path.join("."),
        `optionsCopiedFrom references element '${issue.sourceId}' (${positions.get(issue.sourceId)?.path ?? "?"}), which is not before it; options can only be copied from elements in earlier blocks or above it on the same block`,
        issue.sourceId,
        "element"
      )
    );
  }

  // One report per key, and the map has held that invariant since insert — see `addViolation`. The key
  // is also the dedupe unit the delta filter below relies on.
  return [...violations.values()];
}

/** Every ordering violation in the document — the `enforce` policy, kept for the create rollout. */
export function getV3SurveyPrecedenceInvalidParams(input: TReferenceValidationInput): InvalidParam[] {
  return getV3SurveyPrecedenceViolations(input).map((violation) => violation.issue);
}

/**
 * Only the ordering violations this change *introduces*.
 *
 * Enforcing the full set on a patch would brick every survey that already contains one — including a
 * patch that never touches the offending block. That is the ENG-3070 failure class, and it is the
 * reason this rule is a delta rather than an absolute.
 */
export function getV3SurveyIntroducedPrecedenceInvalidParams(
  baseline: TReferenceValidationInput,
  input: TReferenceValidationInput
): InvalidParam[] {
  const existing = new Set(getV3SurveyPrecedenceViolations(baseline).map((violation) => violation.key));

  return getV3SurveyPrecedenceViolations(input)
    .filter((violation) => !existing.has(violation.key))
    .map((violation) => violation.issue);
}
