import {
  RESERVED_FIELD_CATALOG,
  type TLinkedEmbeddedField,
  getSurveyEmbeddedFields,
} from "@formbricks/types/embedded-data-resolver";
import { type TI18nString } from "@formbricks/types/i18n";
import { TResponseData, TResponseDataValue, TResponseVariables } from "@formbricks/types/responses";
import { formatFieldNameToTitleCase } from "@formbricks/types/safe-identifier";
import { TSurveyElement } from "@formbricks/types/surveys/elements";
import { TSurvey, TSurveyRecallItem } from "@formbricks/types/surveys/types";
import { getTextContent } from "@formbricks/types/surveys/validation";
import { getLocalizedValue } from "@/lib/i18n/utils";
import { structuredClone } from "@/lib/pollyfills/structuredClone";
import { escapeHtml } from "@/lib/utils/escape-html";
import { getElementsFromBlocks } from "@/modules/survey/lib/client-utils";
import { type TSurveyDateFormatMap, formatStoredDateForDisplay } from "./date-display";

export interface fallbacks {
  [id: string]: string;
}

/**
 * A recall id: a survey element / Embedded Data id, or a workflow Variable path (ADR 0045) —
 * `payload.…`, `steps.…` or `response.…`, dot-separated. Only those three prefixes take dots, so a
 * survey token reads exactly as before. Mirrors `WORKFLOW_VARIABLE_PATH_PATTERN_SOURCE` in
 * `@formbricks/workflows`, kept local so survey bundles don't pull in the workflows package.
 */
const RECALL_ID_SOURCE = String.raw`(?:payload|steps|response)(?:\.[A-Za-z0-9_-]+)+|[A-Za-z0-9_-]+`;

// Extracts the ID of recall question from a string containing the "recall" pattern.
export const extractId = (text: string): string | null => {
  const pattern = new RegExp(`#recall:(${RECALL_ID_SOURCE})`);
  const match = text.match(pattern);
  if (match && match[1]) {
    return match[1];
  } else {
    return null;
  }
};

const escapeRegExp = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, String.raw`\$&`);

// If there are multiple recall infos in a string extracts all recall question IDs from that string and construct an array out of it.
// Deliberately lax — it matches an id with no `/fallback:…#` tail, so a half-typed or half-deleted
// token still names the element it points at. Callers that need the id of a token the rest of the
// codebase will actually render want `extractCompleteRecallIds` instead.
export const extractIds = (text: string): string[] => {
  const pattern = new RegExp(`#recall:(${RECALL_ID_SOURCE})`, "g");
  const matches = Array.from(text.matchAll(pattern));
  return matches.map((match) => match[1]).filter((id) => id !== null);
};

/**
 * The ids of the *complete* `#recall:<id>/fallback:<x>#` tokens in a text — the same shape
 * `extractRecallInfo` matches, so what this returns is exactly what `recallToHeadline` will turn
 * into an `@Label`.
 *
 * ENG-2931: `getRecallItems` used to be built on the lax `extractIds`, so a token the operator had
 * broken by one keystroke (deleting the closing `#`) still produced a recall item whose `@Label`
 * `recallToHeadline` had left as raw text. `RecallWrapper` then had an item it could never find in
 * the rendered text and re-entered its own effect without bound.
 */
export const extractCompleteRecallIds = (text: string): string[] => {
  const pattern = new RegExp(`#recall:(${RECALL_ID_SOURCE})/fallback:[^#]*#`, "g");
  return Array.from(text.matchAll(pattern), (match) => match[1]);
};

/**
 * A fresh global pattern for complete `#recall:<id>/fallback:<x>#` tokens, workflow Variable paths
 * included, with no capture groups so `split` returns only the text between tokens. Fresh because a
 * global regex carries `lastIndex` between calls.
 */
export const createRecallTokenPattern = (): RegExp =>
  new RegExp(`#recall:(?:${RECALL_ID_SOURCE})/fallback:[^#]*#`, "g");

// Extracts the fallback value from a string containing the "fallback" pattern.
// An index scan, not `/fallback:([^#]*)#/`: that pattern is O(N^2) on a long run of `fallback:`
// with no `#` after it, because the engine rescans to the end from every occurrence. Identical
// result — `[^#]*` cannot cross a `#`, so the regex ends at the first `#` after the FIRST
// `fallback:`, and if none follows that one none follows a later one either.
const FALLBACK_MARKER = "fallback:";

export const extractFallbackValue = (text: string): string => {
  const markerStart = text.indexOf(FALLBACK_MARKER);
  if (markerStart === -1) return "";

  const valueStart = markerStart + FALLBACK_MARKER.length;
  const valueEnd = text.indexOf("#", valueStart);
  return valueEnd === -1 ? "" : text.slice(valueStart, valueEnd);
};

// Extracts the complete recall information (ID and fallback) from a headline string.
export const extractRecallInfo = (headline: string, id?: string): string | null => {
  const idPattern = id ? escapeRegExp(id) : RECALL_ID_SOURCE;
  const pattern = new RegExp(String.raw`#recall:(${idPattern})\/fallback:([^#]*)#`);
  const match = headline.match(pattern);
  return match ? match[0] : null;
};

// Finds the recall information by a specific recall question ID within a text.
export const findRecallInfoById = (text: string, id: string): string | null => {
  const pattern = new RegExp(String.raw`#recall:${escapeRegExp(id)}\/fallback:([^#]*)#`, "g");
  const match = text.match(pattern);
  return match ? match[0] : null;
};

/**
 * A recall token addresses an Embedded Data field by its storage key. ENG-1837 resolves what that
 * key means through the resolver rather than reading `hiddenFields.fieldIds` / `variables` directly;
 * `source` is what used to be the array a key was found in.
 *
 * `getSurveyEmbeddedFields`, the one read every other reader makes. A token's label is authoring
 * syntax — the recall picker writes `@label` into the text and these functions read it back
 * (`headlineToRecall` matches on the label), so both sides must see the same instant's definitions.
 * Until ENG-2628 that forced a derive here, because the editor's working copy carried rows one save
 * behind its cards; now the cards edit the rows, so the picker and this resolver read the same list
 * in the editor exactly as they already did for a saved survey.
 */
const findEmbeddedField = (
  embeddedFields: TLinkedEmbeddedField[],
  storageKey: string,
  source: "computed" | "ingested"
): TLinkedEmbeddedField | undefined =>
  embeddedFields.find(({ field, link }) => link.storageKey === storageKey && field.source === source);

/**
 * Takes the already-resolved element list and field list rather than a survey, so callers that label
 * several tokens — a headline with nested recalls, a whole text — flatten the blocks and resolve the
 * definitions once instead of once per token. Both are non-trivial (the field lookup re-derives the
 * whole list from the declarations, and flattening walks every block), and these run on every editor
 * render.
 */
const resolveRecallItemLabel = (
  recallItemId: string,
  elements: TSurveyElement[],
  languageCode: string,
  embeddedFields: TLinkedEmbeddedField[]
): string | undefined => {
  // Precedence is load-bearing and unchanged: ingested first, then elements, then computed — so a
  // storage key that also matches an element id keeps resolving the way it does today.
  const ingestedField = findEmbeddedField(embeddedFields, recallItemId, "ingested");
  if (ingestedField) return ingestedField.field.name;

  const surveyQuestion = elements.find((question) => question.id === recallItemId);
  if (surveyQuestion) {
    const headline = getLocalizedValue(surveyQuestion.headline, languageCode);
    // Strip HTML tags to prevent raw HTML from showing in nested recalls
    return headline ? getTextContent(headline) : headline;
  }

  const computedField = findEmbeddedField(embeddedFields, recallItemId, "computed");
  if (computedField) return computedField.field.name;

  // Reserved is checked LAST, which is the grandfather rule in label form: a survey that declares its
  // own `country` has already returned above, so the token keeps showing the declared field's name.
  const reservedEntry = RESERVED_FIELD_CATALOG.find((entry) => entry.name === recallItemId);
  if (reservedEntry) return formatFieldNameToTitleCase(reservedEntry.name);
};

export const getRecallItemLabel = <T extends TSurvey>(
  recallItemId: string,
  survey: T,
  languageCode: string
): string | undefined =>
  resolveRecallItemLabel(
    recallItemId,
    getElementsFromBlocks(survey.blocks),
    languageCode,
    getSurveyEmbeddedFields(survey)
  );

// Converts recall information in a headline to a corresponding recall question headline, with or without a slash.
export const recallToHeadline = <T extends TSurvey>(
  headline: TI18nString,
  survey: T,
  withSlash: boolean,
  languageCode: string
): TI18nString => {
  const newHeadline = structuredClone(headline);
  const localizedHeadline = newHeadline[languageCode];

  if (!localizedHeadline?.includes("#recall:")) return headline;

  const embeddedFields = getSurveyEmbeddedFields(survey);
  const elements = getElementsFromBlocks(survey.blocks);

  const replaceNestedRecalls = (text: string): string => {
    while (text.includes("#recall:")) {
      const recallInfo = extractRecallInfo(text);
      if (!recallInfo) break;

      const recallItemId = extractId(recallInfo);
      if (!recallItemId) break;

      let recallItemLabel =
        resolveRecallItemLabel(recallItemId, elements, languageCode, embeddedFields) || recallItemId;

      while (recallItemLabel.includes("#recall:")) {
        const nestedRecallInfo = extractRecallInfo(recallItemLabel);
        if (nestedRecallInfo) {
          recallItemLabel = recallItemLabel.replace(nestedRecallInfo, "___");
        }
      }

      const replacement = withSlash ? `/${recallItemLabel}\\` : `@${recallItemLabel}`;
      text = text.replace(recallInfo, replacement);
    }
    return text;
  };

  newHeadline[languageCode] = replaceNestedRecalls(localizedHeadline);
  return newHeadline;
};

// Replaces recall information in a survey question's headline with an ___.
export const replaceRecallInfoWithUnderline = (label: string): string => {
  let newLabel = label;
  while (newLabel.includes("#recall:")) {
    const recallInfo = extractRecallInfo(newLabel);
    if (recallInfo) {
      newLabel = newLabel.replace(recallInfo, "___");
    }
  }
  return newLabel;
};

// Checks for survey questions with a "recall" pattern but no fallback value.
export const checkForEmptyFallBackValue = (survey: TSurvey, language: string): TSurveyElement | null => {
  const doesTextHaveRecall = (text: string) => {
    const recalls = text.match(/#recall:[^ ]+/g);
    return recalls?.some((recall) => !extractFallbackValue(recall));
  };

  const questions = getElementsFromBlocks(survey.blocks);
  for (const question of questions) {
    if (
      doesTextHaveRecall(getLocalizedValue(question.headline, language)) ||
      (question.subheader && doesTextHaveRecall(getLocalizedValue(question.subheader, language)))
    ) {
      return question;
    }
  }
  return null;
};

// Processes each question in a survey to ensure headlines are formatted correctly for recall and return the modified survey.
export const replaceHeadlineRecall = <T extends TSurvey>(survey: T, language: string): T => {
  const modifiedSurvey = structuredClone(survey);
  const questions = getElementsFromBlocks(modifiedSurvey.blocks);
  questions.forEach((question) => {
    question.headline = recallToHeadline(question.headline, modifiedSurvey, false, language);
  });
  return modifiedSurvey;
};

// Retrieves an array of survey questions referenced in a text containing recall information.
export const getRecallItems = (text: string, survey: TSurvey, languageCode: string): TSurveyRecallItem[] => {
  if (!text.includes("#recall:")) return [];

  // Complete tokens only, so this agrees with `recallToHeadline`/`getFallbackValues` about what a
  // recall tag is (ENG-2931).
  const ids = extractCompleteRecallIds(text);
  // Both lists are resolved once for the whole text, not once per token.
  const embeddedFields = getSurveyEmbeddedFields(survey);
  const elements = getElementsFromBlocks(survey.blocks);
  const recallItems: TSurveyRecallItem[] = [];
  ids.forEach((recallItemId) => {
    const isHiddenField = findEmbeddedField(embeddedFields, recallItemId, "ingested");
    const isSurveyQuestion = elements.some((question) => question.id === recallItemId);
    const isVariable = findEmbeddedField(embeddedFields, recallItemId, "computed");

    const recallItemLabel = resolveRecallItemLabel(recallItemId, elements, languageCode, embeddedFields);

    const getRecallItemType = () => {
      if (isHiddenField) return "hiddenField";
      if (isSurveyQuestion) return "element";
      if (isVariable) return "variable";
      // Same precedence as the label lookup, and load-bearing for the same reason: without this arm
      // `getRecallItems` drops the id it could not type, and the editor renders the raw
      // `#recall:country/fallback:x#` token as literal text instead of a chip.
      if (RESERVED_FIELD_CATALOG.some((entry) => entry.name === recallItemId)) return "reserved";
    };

    if (recallItemLabel) {
      let recallItemLabelTemp = recallItemLabel;
      recallItemLabelTemp = replaceRecallInfoWithUnderline(recallItemLabelTemp);
      const recallItemType = getRecallItemType();
      if (recallItemType) {
        recallItems.push({
          id: recallItemId,
          label: recallItemLabelTemp,
          type: recallItemType,
        });
      }
    }
  });
  return recallItems;
};

// Constructs a fallbacks object from a text containing multiple recall and fallback patterns.
export const getFallbackValues = (text: string): fallbacks => {
  if (!text.includes("#recall:")) return {};
  const pattern = new RegExp(`#recall:(${RECALL_ID_SOURCE})/fallback:([^#]*)#`, "g");
  let match;
  const fallbacks: fallbacks = {};

  while ((match = pattern.exec(text)) !== null) {
    const id = match[1];
    const fallbackValue = match[2];
    fallbacks[id] = fallbackValue;
  }
  return fallbacks;
};

// Transforms headlines in a text to their corresponding recall information.
export const headlineToRecall = (
  text: string | undefined,
  recallItems: TSurveyRecallItem[],
  fallbacks: fallbacks
): string => {
  if (!text) return "";

  recallItems.forEach((recallItem) => {
    const recallInfo = `#recall:${recallItem.id}/fallback:${fallbacks[recallItem.id]}#`;
    text = text?.replace(`@${recallItem.label}`, recallInfo);
  });
  return text;
};

/** The trailing `\#` a slash-wrapped recall tag ends with. */
const RECALL_SLASH_SUFFIX = String.raw`\#`;

/**
 * A response value is `string | number | string[] | Record<string, string>`. Arrays and dates are
 * already normalized above, but matrix and address answers arrive as records, which would coerce to
 * `[object Object]` if handed to `String()`.
 */
const stringifyRecallValue = (value: TResponseDataValue): string => {
  if (typeof value === "string") return value;
  if (typeof value === "number") return String(value);
  if (Array.isArray(value)) return value.filter(Boolean).join(", ");
  if (value) return Object.values(value).filter(Boolean).join(", ");
  return "";
};

/** A recalled answer for display: a stored date in its display format, a list joined by commas. */
const formatRecalledAnswer = (
  value: TResponseDataValue | undefined,
  dateFormat: TSurveyDateFormatMap[string] | undefined,
  locale: string
): TResponseDataValue | undefined => {
  // Apply formatting for special value types
  if (typeof value === "string") {
    const formattedDate = formatStoredDateForDisplay(value, dateFormat, locale);
    if (formattedDate) return formattedDate;
    return value;
  }
  if (Array.isArray(value)) {
    return value.filter(Boolean).join(", ");
  }
  return value;
};

/**
 * The value a recall id names: a variable first (a true/false field, ENG-6973, reads `true` /
 * `false`), then an answer formatted for display.
 */
const getRecalledValue = (
  recallItemId: string,
  responseData: TResponseData | undefined,
  variables: TResponseVariables | undefined,
  locale: string,
  dateFormats: TSurveyDateFormatMap | undefined
): TResponseDataValue | undefined => {
  // First check if it matches a variable
  if (variables && Object.keys(variables).includes(recallItemId)) {
    const variableValue = variables[recallItemId];
    return typeof variableValue === "boolean" ? String(variableValue) : variableValue;
  }
  // Then check if it matches response data
  if (responseData && Object.keys(responseData).includes(recallItemId)) {
    return formatRecalledAnswer(responseData[recallItemId], dateFormats?.[recallItemId], locale);
  }
  return undefined;
};

/**
 * @param escapeValues HTML-escape each substituted value before splicing it in. Off by default because
 * most callers render the result through React, which escapes for them — escaping here too would show
 * literal `&amp;`. Turn it on when the result goes into raw HTML, e.g. the follow-up email body.
 *
 * The recalled value is a respondent's answer, i.e. data, and must never become markup. Sanitizing the
 * *combined* string afterwards is not a substitute: a sanitizer cannot tell the survey author's
 * intended markup from markup a respondent injected, so an allowlist that legitimately permits
 * `<a href>` in an author-written body will equally pass off an anchor spliced in from an answer.
 */
export const parseRecallInfo = (
  text: string,
  responseData?: TResponseData,
  variables?: TResponseVariables,
  withSlash: boolean = false,
  locale: string = "en-US",
  dateFormats?: TSurveyDateFormatMap,
  escapeValues: boolean = false
) => {
  let modifiedText = text;

  // Process all recall patterns regardless of whether we have matching data
  while (modifiedText.includes("#recall:")) {
    const recallInfo = extractRecallInfo(modifiedText);
    if (!recallInfo) break; // Exit the loop if no recall info is found

    const recallItemId = extractId(recallInfo);
    if (!recallItemId) {
      // If no ID could be extracted, just remove the recall tag
      modifiedText = modifiedText.replace(recallInfo, "");
      continue;
    }

    const fallback = extractFallbackValue(recallInfo).replaceAll("nbsp", " ");
    let value = getRecalledValue(recallItemId, responseData, variables, locale, dateFormats);

    // If no value was found, use the fallback
    if (value === undefined || value === null || value === "") {
      value = fallback;
    }

    // Stringify unconditionally, escape only when asked. Gating the stringify on `escapeValues` left the
    // default path casting a `Record<string, string>` answer (matrix, address) straight to string, which
    // renders as "[object Object]" — the exact bug stringifyRecallValue exists to prevent, still live for
    // every caller outside the follow-up-email flow. Raised by CodeRabbit on #8681.
    const stringifiedValue = stringifyRecallValue(value);
    const substitutedValue = escapeValues ? escapeHtml(stringifiedValue) : stringifiedValue;
    // Replacer functions, not replacement strings: `$&`, `` $` `` and friends are special in a
    // replacement string, so an answer containing them would splice part of the pattern back in.
    if (withSlash) {
      modifiedText = modifiedText.replace(recallInfo, () => `#/${substitutedValue}${RECALL_SLASH_SUFFIX}`);
    } else {
      modifiedText = modifiedText.replace(recallInfo, () => substitutedValue);
    }
  }

  return modifiedText;
};

export const getTextContentWithRecallTruncated = (text: string, maxLength: number = 25): string => {
  const cleanText = getTextContent(text).replaceAll(/\s+/g, " ").trim();

  if (cleanText.length <= maxLength) {
    return replaceRecallInfoWithUnderline(cleanText);
  }

  const recalledCleanText = replaceRecallInfoWithUnderline(cleanText);

  const start = recalledCleanText.slice(0, 10);
  const end = recalledCleanText.slice(-10);

  return `${start}...${end}`;
};
