import {
  RESERVED_FIELD_CATALOG,
  getSurveyEmbeddedFields,
  listMidSurveyReservedEntries,
  listShadowingNames,
} from "@formbricks/types/embedded-data-resolver";
import type { TSurveyElement } from "@formbricks/types/surveys/elements";
import {
  type TExpressionTypeContext,
  type TExpressionTypeIssue,
  type TExpressionValueType,
  checkExpressionTypes,
  getElementExpressionType,
  getSetValueExpressionIssues,
} from "@formbricks/types/surveys/expression-types";
import {
  EXPRESSION_FUNCTIONS,
  EXPRESSION_FUNCTION_ARITY,
  type TExpression,
  type TExpressionCall,
  type TExpressionFunction,
  type TExpressionLeaf,
} from "@formbricks/types/surveys/expressions";
import type { TSurvey } from "@formbricks/types/surveys/types";
import { getElementsFromBlocks } from "@/modules/survey/lib/client-utils";

/**
 * The formula box's text form of a Set value expression (ENG-6935, ADR 0030): parses what people type
 * into the same tree AI writes through v3 and MCP, and renders a stored tree back as text.
 *
 * This parser lives in the web app only, never in the survey bundle, which just walks the tree.
 *
 * The text form:
 * - numbers (`2`, `1.5`), text in quotes (`"gold"`), and references with `@`: a question by its code
 *   (or id when it has none), an Embedded Data field by name, a reserved field by name. A name that
 *   isn't a plain identifier is braced: `@{Plan tier}`.
 * - `+ - * /` (also `× ÷ −`) with the usual precedence and brackets; `a + b + c` is one `add`, and a
 *   leading minus on a number is a negative number.
 * - functions by name: `round(x, 1)`, `min(a, b)`, `ifEmpty(@q1, 0)`, `now()`, … (any case).
 */

/** The most characters a formula has. Generous; it also bounds the parser's recursion. */
export const FORMULA_MAX_LENGTH = 5000;

/**
 * The most characters the formula box holds, well past FORMULA_MAX_LENGTH: a longer paste stays in the
 * box and says it is too long, rather than being cut to the limit and failing on wherever the cut fell
 * (ENG-7028). Text clipped here is still over FORMULA_MAX_LENGTH, so it says too long too; the cap only
 * keeps the per-keystroke work fast: the chips read the whole text, the slot check the text before the caret.
 */
export const FORMULA_BOX_MAX_LENGTH = FORMULA_MAX_LENGTH * 4;

export type TFormulaReferenceGroup = "question" | "field" | "reserved";

export interface TFormulaReference {
  /** What follows `@` in the text. */
  token: string;
  leaf: Exclude<TExpressionLeaf, { type: "static" }>;
  group: TFormulaReferenceGroup;
  /** For a question: whether a formula can use its answer. */
  usable: boolean;
  /** For a question: the block it is on, to offer only answers given by the time the step runs. */
  blockIdx?: number;
  /** For a usable question: what its answer is in a formula. */
  valueType?: TExpressionValueType;
}

const PLAIN_TOKEN = /^\w+$/;

/** How a token reads after `@`: bare when it is a plain identifier, braced otherwise. */
export const formatReferenceToken = (token: string): string =>
  PLAIN_TOKEN.test(token) ? `@${token}` : `@{${token}}`;

const leafKey = (leaf: { type: string; value: string }) => `${leaf.type}:${leaf.value}`;

/**
 * Everything a formula can name in this survey: its questions (by code), its Embedded Data fields and
 * the reserved fields a running survey can read. Earlier entries win a token, in that order; question
 * codes are unique across Embedded Data names already (codes.ts), so a clash needs a stale survey.
 */
export const getFormulaReferences = (survey: TSurvey): TFormulaReference[] => {
  const references: TFormulaReference[] = [];
  const taken = new Set<string>();
  const add = (reference: TFormulaReference) => {
    if (taken.has(reference.token)) return;
    taken.add(reference.token);
    references.push(reference);
  };

  survey.blocks.forEach((block, blockIdx) => {
    block.elements.forEach((element: TSurveyElement) => {
      const valueType = getElementExpressionType(element);
      add({
        token: ("code" in element && element.code) || element.id,
        leaf: { type: "element", value: element.id },
        group: "question",
        usable: valueType !== undefined,
        blockIdx,
        ...(valueType ? { valueType } : {}),
      });
    });
  });

  const fields = getSurveyEmbeddedFields(survey);
  for (const { field, link } of fields) {
    add({
      token: field.name.trim() === "" ? link.storageKey : field.name,
      leaf: { type: field.source === "computed" ? "variable" : "hiddenField", value: link.storageKey },
      group: "field",
      usable: field.dataType !== "boolean" || field.source === "ingested",
    });
  }

  const declared = listShadowingNames(
    fields,
    getElementsFromBlocks(survey.blocks).map((element) => element.id)
  );
  for (const entry of listMidSurveyReservedEntries(RESERVED_FIELD_CATALOG, declared)) {
    add({
      token: entry.name,
      leaf: { type: "reserved", value: entry.name },
      group: "reserved",
      usable: true,
    });
  }

  return references;
};

/**
 * The shared save-time check (`getSetValueExpressionIssues`, the one `surveyRefinement` and v3 run),
 * against the editor's working copy, so the formula box says what a save would refuse while typing.
 */
export const getFormulaIssues = (
  expression: TExpression,
  variableId: string,
  survey: TSurvey
): TExpressionTypeIssue[] => {
  const target = getSurveyEmbeddedFields(survey).find(
    ({ field, link }) => field.source === "computed" && link.storageKey === variableId
  )?.field;
  if (!target) return [];
  return getSetValueExpressionIssues(expression, target.dataType, getFormulaTypeContext(survey));
};

/** How the shared type rules look up this survey's questions and fields. */
export const getFormulaTypeContext = (survey: TSurvey): TExpressionTypeContext => {
  const fields = getSurveyEmbeddedFields(survey);
  const elements = new Map(getElementsFromBlocks(survey.blocks).map((element) => [element.id, element]));
  const fieldType = (storageKey: string, source: "computed" | "ingested") =>
    fields.find(({ field, link }) => field.source === source && link.storageKey === storageKey)?.field
      .dataType;
  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) => fieldType(storageKey, "computed"),
    getIngestedFieldType: (storageKey) => fieldType(storageKey, "ingested"),
    getReservedFieldType: (name) => RESERVED_FIELD_CATALOG.find((entry) => entry.name === name)?.dataType,
  };
};

// ---- One-step calculations ----------------------------------------------------------------------

/**
 * A one-step calculation as the formula that computes the same thing, for turning the Set value
 * row's formula toggle on: `score + 1` becomes `ifEmpty(@score, 0) + 1`, keeping the field's "empty counts as
 * 0". An empty operand now gives an empty result instead of leaving the field alone (grill P3).
 */
export const oneStepToFormula = (action: {
  variableId: string;
  operator: string;
  value: { type: string; value: string | number };
}): TExpression => {
  const operand: TExpression =
    action.value.type === "static"
      ? { type: "static", value: action.value.value }
      : ({ type: action.value.type, value: String(action.value.value) } as TExpression);

  const current = (fallback: number | string): TExpression => ({
    type: "call",
    fn: "ifEmpty",
    args: [
      { type: "variable", value: action.variableId },
      { type: "static", value: fallback },
    ],
  });

  switch (action.operator) {
    case "add":
    case "subtract":
    case "multiply":
    case "divide":
      return { type: "call", fn: action.operator, args: [current(0), operand] };
    case "concat":
      return { type: "call", fn: "concat", args: [current(""), operand] };
    default:
      return operand;
  }
};

/** A one-step calculation's operator and value, what the formula toggle turned off writes back. */
export interface TOneStepCalculation {
  operator: "assign" | "add" | "subtract" | "multiply" | "divide" | "concat";
  value:
    | { type: "static"; value: string | number }
    | { type: "element" | "variable" | "hiddenField"; value: string };
}

const ONE_STEP_OPERAND_TYPES = new Set(["static", "element", "variable", "hiddenField"]);

const toOneStepOperand = (expression: TExpression | undefined): TOneStepCalculation["value"] | null =>
  expression && ONE_STEP_OPERAND_TYPES.has(expression.type) && expression.type !== "call"
    ? (expression as TOneStepCalculation["value"])
    : null;

/** Whether the expression is `ifEmpty(@field, fallback)`: the field's current value, empty as the fallback. */
const isCurrentValue = (expression: TExpression | undefined, variableId: string, fallback: number | string) =>
  expression?.type === "call" &&
  expression.fn === "ifEmpty" &&
  expression.args.length === 2 &&
  expression.args[0].type === "variable" &&
  expression.args[0].value === variableId &&
  expression.args[1].type === "static" &&
  expression.args[1].value === fallback;

/**
 * The reverse of {@link oneStepToFormula}, for turning the formula toggle off: the one-step
 * calculation that computes the same thing, or `null` when the formula is more than one step and
 * turning it off would lose it. An empty formula assigns an empty value.
 */
export const formulaToOneStep = (expression: TExpression, variableId: string): TOneStepCalculation | null => {
  if (expression.type !== "call") {
    const value = toOneStepOperand(expression);
    return value ? { operator: "assign", value } : null;
  }
  if (expression.args.length !== 2) return null;
  const [current, operand] = expression.args;
  const value = toOneStepOperand(operand);
  if (!value) return null;
  switch (expression.fn) {
    case "add":
    case "subtract":
    case "multiply":
    case "divide":
      return isCurrentValue(current, variableId, 0) ? { operator: expression.fn, value } : null;
    case "concat":
      return isCurrentValue(current, variableId, "") ? { operator: "concat", value } : null;
    default:
      return null;
  }
};

// ---- Help -----------------------------------------------------------------------------------------

/** The functions the box offers as chips: the four arithmetic ones are written with `+ - * /`. */
export const FORMULA_CHIP_FUNCTIONS = EXPRESSION_FUNCTIONS.filter(
  (fn): fn is Exclude<TExpressionFunction, "add" | "subtract" | "multiply" | "divide"> =>
    !["add", "subtract", "multiply", "divide"].includes(fn)
);
export type TFormulaChipFunction = (typeof FORMULA_CHIP_FUNCTIONS)[number];

/** Each chip's example in its tooltip. Formula text, so the same in every language. */
export const FORMULA_FUNCTION_EXAMPLES: Record<TFormulaChipFunction, string> = {
  round: "round(@q1 * 20)",
  min: "min(@q1, @q2)",
  max: "max(@q1, @q2)",
  abs: "abs(@q1 - @q2)",
  ifEmpty: "ifEmpty(@q1, 0)",
  concat: 'concat("segment-", @q1)',
  now: "now()",
  daysBetween: "daysBetween(@q1, now())",
};

/**
 * The example in the empty box's placeholder: a score from the first number question answered by the
 * time the step runs, so it reads as this survey's own formula, or a generic one when there is none.
 */
export const getFormulaExample = (references: TFormulaReference[], scopeBlockIdx: number): string => {
  const numberQuestion = references.find(
    (reference) =>
      reference.group === "question" &&
      reference.valueType === "number" &&
      (reference.blockIdx ?? 0) <= scopeBlockIdx
  );
  return `round(${formatReferenceToken(numberQuestion?.token ?? "q1")} * 20)`;
};

// ---- Insertion ----------------------------------------------------------------------------------

/** What a function chip inserts, and where the cursor goes: inside the brackets, or after `now()`. */
export const getFunctionSnippet = (fn: TExpressionFunction): { text: string; cursorOffset: number } =>
  fn === "now" ? { text: "now()", cursorOffset: 5 } : { text: `${fn}()`, cursorOffset: fn.length + 1 };

/**
 * Inserts `insert` over the selection, returning the new text and where the cursor goes. A reference
 * picked right after typing `@` replaces that `@`, so `@` then a pick gives `@score`, not `@@score`.
 */
export const insertIntoFormula = (
  text: string,
  selection: { start: number; end: number },
  insert: string,
  options: { cursorOffset?: number; replaceTypedAt?: boolean } = {}
): { text: string; cursor: number } => {
  let start = Math.max(0, Math.min(selection.start, text.length));
  const end = Math.max(start, Math.min(selection.end, text.length));
  if (options.replaceTypedAt && start > 0 && text[start - 1] === "@") start -= 1;
  return {
    text: `${text.slice(0, start)}${insert}${text.slice(end)}`,
    cursor: start + (options.cursorOffset ?? insert.length),
  };
};

// ---- Formatting ---------------------------------------------------------------------------------

const INFIX: Partial<Record<TExpressionFunction, { symbol: string; precedence: number; flat: boolean }>> = {
  add: { symbol: "+", precedence: 1, flat: true },
  subtract: { symbol: "-", precedence: 1, flat: false },
  multiply: { symbol: "*", precedence: 2, flat: true },
  divide: { symbol: "/", precedence: 2, flat: false },
};

const ATOM_PRECEDENCE = 3;

/** Whether a call reads as an operator (`a + b`) rather than a function (`add(a)`, a malformed tree). */
const getInfix = (node: TExpressionCall) => {
  const infix = INFIX[node.fn];
  if (!infix) return undefined;
  const readsAsOperator = infix.flat ? node.args.length >= 2 : node.args.length === 2;
  return readsAsOperator ? infix : undefined;
};

const precedenceOf = (node: TExpression): number =>
  node.type === "call" ? (getInfix(node)?.precedence ?? ATOM_PRECEDENCE) : ATOM_PRECEDENCE;

const ESCAPED_BACKSLASH = String.raw`\\`;
const ESCAPED_QUOTE = String.raw`\"`;

const quoteText = (text: string): string => {
  const escaped = text.replaceAll("\\", ESCAPED_BACKSLASH).replaceAll('"', ESCAPED_QUOTE);
  return `"${escaped}"`;
};

/**
 * A tree as the text the formula box shows. Parsing the result gives the same tree back, brackets
 * included where the tree nests the same operation (`(a + b) + c` stays two `add`s).
 */
export const formatFormula = (expression: TExpression, references: TFormulaReference[]): string => {
  const tokens = new Map(references.map((reference) => [leafKey(reference.leaf), reference.token]));

  const format = (node: TExpression): string => {
    switch (node.type) {
      case "static":
        return typeof node.value === "number" ? String(node.value) : quoteText(node.value);
      case "call":
        return formatCall(node);
      default:
        return formatReferenceToken(tokens.get(leafKey(node)) ?? node.value);
    }
  };

  const wrap = (node: TExpression, needsBrackets: boolean) =>
    needsBrackets ? `(${format(node)})` : format(node);

  const formatCall = (node: TExpressionCall): string => {
    const infix = getInfix(node);
    if (infix) {
      const parts = node.args.map((arg, idx) => {
        const argPrecedence = precedenceOf(arg);
        if (infix.flat) {
          const sameOperation = arg.type === "call" && arg.fn === node.fn;
          return wrap(
            arg,
            argPrecedence < infix.precedence ||
              (argPrecedence === infix.precedence && (idx > 0 || sameOperation))
          );
        }
        return wrap(arg, idx === 0 ? argPrecedence < infix.precedence : argPrecedence <= infix.precedence);
      });
      return parts.join(` ${infix.symbol} `);
    }
    return `${node.fn}(${node.args.map((arg) => format(arg)).join(", ")})`;
  };

  return format(expression);
};

// ---- Parsing ------------------------------------------------------------------------------------

export type TFormulaErrorCode =
  | "empty"
  | "too_long"
  | "unexpected_character"
  | "unexpected_token"
  | "unexpected_end"
  | "unclosed_text"
  | "unknown_function"
  | "unknown_reference"
  | "incomplete_reference";

export interface TFormulaError {
  code: TFormulaErrorCode;
  /** Character offset the problem starts at. */
  position: number;
  /** The function name, reference or token the problem is about. */
  detail?: string;
}

export type TFormulaParseResult = { ok: true; expression: TExpression } | { ok: false; error: TFormulaError };

type TToken =
  | { kind: "number"; value: number; position: number }
  | { kind: "text"; value: string; position: number }
  | { kind: "reference"; value: string; position: number }
  | { kind: "name"; value: string; position: number }
  | { kind: "operator"; value: "+" | "-" | "*" | "/" | "(" | ")" | ","; position: number };

class FormulaError extends Error {
  constructor(readonly error: TFormulaError) {
    super(error.code);
  }
}

const OPERATOR_ALIASES: Record<string, "+" | "-" | "*" | "/" | "(" | ")" | ","> = {
  "+": "+",
  "-": "-",
  "−": "-",
  "*": "*",
  "×": "*",
  "/": "/",
  "÷": "/",
  "(": "(",
  ")": ")",
  ",": ",",
};

const QUOTES: Record<string, string> = { '"': '"', "'": "'", "“": "”" };

/** One token read at a position: the token, and where the next one starts. */
type TTokenRead = { token: TToken; next: number };
type TTokenReader = (text: string, idx: number) => TTokenRead | undefined;

const readOperator: TTokenReader = (text, idx) => {
  const operator = OPERATOR_ALIASES[text[idx]];
  if (!operator) return undefined;
  return { token: { kind: "operator", value: operator, position: idx }, next: idx + 1 };
};

const readNumber: TTokenReader = (text, idx) => {
  const number = /^(\d+(\.\d+)?|\.\d+)/.exec(text.slice(idx));
  if (!number) return undefined;
  return { token: { kind: "number", value: Number(number[0]), position: idx }, next: idx + number[0].length };
};

/** Quoted text, with `\` escaping the next character. */
const readText: TTokenReader = (text, idx) => {
  const closingQuote = QUOTES[text[idx]];
  if (!closingQuote) return undefined;
  let value = "";
  let end = idx + 1;
  while (end < text.length && text[end] !== closingQuote) {
    if (text[end] === "\\" && end + 1 < text.length) end += 1;
    value += text[end];
    end += 1;
  }
  if (end >= text.length) throw new FormulaError({ code: "unclosed_text", position: idx });
  // No length check: parseFormula refuses text over FORMULA_MAX_LENGTH before tokenizing, which keeps any
  // quoted text within EXPRESSION_MAX_STATIC_TEXT_LENGTH.
  return { token: { kind: "text", value, position: idx }, next: end + 1 };
};

/** `@name`, or `@{a name with spaces}`. */
const readReference: TTokenReader = (text, idx) => {
  if (text[idx] !== "@") return undefined;
  if (text[idx + 1] === "{") {
    const end = text.indexOf("}", idx + 2);
    if (end === -1) throw new FormulaError({ code: "unexpected_end", position: idx });
    return {
      token: { kind: "reference", value: text.slice(idx + 2, end).trim(), position: idx },
      next: end + 1,
    };
  }
  const reference = /^\w+/.exec(text.slice(idx + 1));
  // An `@` with no name after it: one being picked from the menu, or left behind.
  if (!reference) throw new FormulaError({ code: "incomplete_reference", position: idx });
  return {
    token: { kind: "reference", value: reference[0], position: idx },
    next: idx + 1 + reference[0].length,
  };
};

const readName: TTokenReader = (text, idx) => {
  const name = /^[A-Za-z_]\w*/.exec(text.slice(idx));
  if (!name) return undefined;
  return { token: { kind: "name", value: name[0], position: idx }, next: idx + name[0].length };
};

/** Tried in order at each position; the first that reads a token wins. */
const TOKEN_READERS: TTokenReader[] = [readOperator, readNumber, readText, readReference, readName];

const readToken = (text: string, idx: number): TTokenRead | undefined => {
  for (const reader of TOKEN_READERS) {
    const read = reader(text, idx);
    if (read) return read;
  }
  return undefined;
};

const tokenize = (text: string): TToken[] => {
  const tokens: TToken[] = [];
  let idx = 0;

  while (idx < text.length) {
    if (/\s/.test(text[idx])) {
      idx += 1;
      continue;
    }
    const read = readToken(text, idx);
    if (!read) throw new FormulaError({ code: "unexpected_character", position: idx, detail: text[idx] });
    tokens.push(read.token);
    idx = read.next;
  }

  return tokens;
};

const FUNCTION_BY_LOWERCASE = new Map(EXPRESSION_FUNCTIONS.map((fn) => [fn.toLowerCase(), fn]));

/**
 * Parses the formula box's text into an expression tree. Arity and types are not judged here: the
 * shared validator does that for the editor, v3 and MCP alike, with paths into the tree.
 */
export const parseFormula = (text: string, references: TFormulaReference[]): TFormulaParseResult => {
  if (text.trim() === "") return { ok: false, error: { code: "empty", position: 0 } };
  if (text.length > FORMULA_MAX_LENGTH) {
    return { ok: false, error: { code: "too_long", position: FORMULA_MAX_LENGTH } };
  }

  const leaves = new Map(references.map((reference) => [reference.token, reference.leaf]));

  try {
    const tokens = tokenize(text);
    let cursor = 0;
    const peek = (): TToken | undefined => tokens[cursor];
    const fail = (token: TToken | undefined): never => {
      throw new FormulaError(
        token
          ? { code: "unexpected_token", position: token.position, detail: String(token.value) }
          : { code: "unexpected_end", position: text.length }
      );
    };
    const isOperator = (token: TToken | undefined, value: string): boolean =>
      token?.kind === "operator" && token.value === value;
    const expectOperator = (value: string) => {
      const token = peek();
      if (!isOperator(token, value)) fail(token);
      cursor += 1;
    };

    // Nodes an operator chain built itself, so `a + b + c` grows one `add` while `(a + b) + c` nests.
    const chainNodes = new WeakSet<TExpressionCall>();
    const combine = (fn: TExpressionFunction, left: TExpression, right: TExpression): TExpression => {
      if (
        (fn === "add" || fn === "multiply") &&
        left.type === "call" &&
        left.fn === fn &&
        chainNodes.has(left)
      ) {
        left.args.push(right);
        return left;
      }
      const node: TExpressionCall = { type: "call", fn, args: [left, right] };
      chainNodes.add(node);
      return node;
    };

    const parseExpression = (): TExpression => {
      let left = parseTerm();
      while (isOperator(peek(), "+") || isOperator(peek(), "-")) {
        const fn = isOperator(peek(), "+") ? "add" : "subtract";
        cursor += 1;
        left = combine(fn, left, parseTerm());
      }
      return left;
    };

    const parseTerm = (): TExpression => {
      let left = parseUnary();
      while (isOperator(peek(), "*") || isOperator(peek(), "/")) {
        const fn = isOperator(peek(), "*") ? "multiply" : "divide";
        cursor += 1;
        left = combine(fn, left, parseUnary());
      }
      return left;
    };

    const parseUnary = (): TExpression => {
      if (!isOperator(peek(), "-")) return parsePrimary();
      cursor += 1;
      const operand = parseUnary();
      if (operand.type === "static" && typeof operand.value === "number") {
        return { type: "static", value: -operand.value };
      }
      return { type: "call", fn: "multiply", args: [{ type: "static", value: -1 }, operand] };
    };

    const parsePrimary = (): TExpression => {
      const token = peek();
      if (!token) return fail(token);
      cursor += 1;

      switch (token.kind) {
        case "number":
          return { type: "static", value: token.value };
        case "text":
          return { type: "static", value: token.value };
        case "reference": {
          const leaf = leaves.get(token.value);
          if (!leaf) {
            throw new FormulaError({
              code: "unknown_reference",
              position: token.position,
              detail: token.value,
            });
          }
          return { ...leaf };
        }
        case "name": {
          const fn = FUNCTION_BY_LOWERCASE.get(token.value.toLowerCase());
          if (!fn) {
            throw new FormulaError({
              code: "unknown_function",
              position: token.position,
              detail: token.value,
            });
          }
          expectOperator("(");
          const args: TExpression[] = [];
          if (!isOperator(peek(), ")")) {
            args.push(parseExpression());
            while (isOperator(peek(), ",")) {
              cursor += 1;
              args.push(parseExpression());
            }
          }
          expectOperator(")");
          return { type: "call", fn, args };
        }
        case "operator": {
          if (token.value !== "(") return fail(token);
          const inner = parseExpression();
          expectOperator(")");
          // Brackets close a chain: `(a + b) + c` keeps the inner `add` as its own node.
          if (inner.type === "call") chainNodes.delete(inner);
          return inner;
        }
      }
    };

    const expression = parseExpression();
    if (cursor < tokens.length) fail(peek());
    return { ok: true, expression };
  } catch (error) {
    if (error instanceof FormulaError) return { ok: false, error: error.error };
    throw error;
  }
};

/** The formula a Set value step holds when nothing is typed; a save refuses it at the step. */
export const EMPTY_FORMULA: TExpression = { type: "static", value: "" };

/**
 * What the formula box writes when it loses focus. Typing writes each formula that parses, so a
 * half-typed one would leave the last good formula in place, and Publish would ship it while the box
 * shows something else. Text that doesn't parse therefore writes the empty formula, which blocks Save
 * and Publish and flags the step; the box keeps the author's text to fix. `null` when typing already
 * wrote what the box shows.
 */
export const getFormulaToWriteOnBlur = (
  text: string,
  references: TFormulaReference[]
): TExpression | null => {
  const parsed = parseFormula(text, references);
  if (parsed.ok || parsed.error.code === "empty") return null;
  return EMPTY_FORMULA;
};

/**
 * The parse error the formula box shows while it is typed in, or none. Nothing is shown while the
 * reference menu is open, nor for an `@` that ends the text: both are a reference being picked.
 */
export const getShownFormulaError = (
  error: TFormulaError,
  context: { text: string; isReferenceMenuOpen: boolean; isTyping?: boolean }
): TFormulaError | null => {
  // Mid-typing, a half-written formula is not a mistake yet: shown after a pause or on blur.
  if (context.isTyping || context.isReferenceMenuOpen || error.code === "empty") return null;
  if (error.code === "incomplete_reference" && context.text.slice(error.position + 1).trim() === "") {
    return null;
  }
  return error;
};

// ---- Reference chips (ENG-6950) ---------------------------------------------------------------------

/**
 * A stretch of the formula box's text: plain text, or a reference the box draws as a chip. A reference
 * no survey entry answers to (deleted, or mistyped) carries no `reference`, and draws as a broken chip.
 */
export type TFormulaSegment =
  | { kind: "text"; text: string; start: number }
  | { kind: "reference"; text: string; start: number; token: string; reference?: TFormulaReference };

/**
 * Where quoted text that opens at `idx` ends (just after its closing quote), `\` escaping the next
 * character; `undefined` while the quote is still open.
 */
const findQuotedTextEnd = (text: string, idx: number, closingQuote: string): number | undefined => {
  let end = idx + 1;
  while (end < text.length && text[end] !== closingQuote) end += text[end] === "\\" ? 2 : 1;
  return end < text.length ? end + 1 : undefined;
};

/** The reference that starts with the `@` at `idx`: its token and where it ends, or none. */
const readReferenceAt = (text: string, idx: number): { token: string; end: number } | undefined => {
  if (text[idx + 1] === "{") {
    const close = text.indexOf("}", idx + 2);
    return close === -1 ? undefined : { token: text.slice(idx + 2, close).trim(), end: close + 1 };
  }
  const name = /^\w+/.exec(text.slice(idx + 1))?.[0];
  return name ? { token: name, end: idx + 1 + name.length } : undefined;
};

/**
 * Splits the formula box's text into text and references, for drawing the references as chips. The
 * text is never changed: the segments join back into it, so the chips are only a way of showing the
 * text form, which still parses into the stored tree. An `@` inside quotes is text; an `@` with no name
 * after it is text until one is picked.
 */
export const segmentFormulaText = (text: string, references: TFormulaReference[]): TFormulaSegment[] => {
  const byToken = new Map(references.map((reference) => [reference.token, reference]));
  const segments: TFormulaSegment[] = [];
  let textStart = 0;
  let idx = 0;
  while (idx < text.length) {
    const closingQuote = QUOTES[text[idx]];
    if (closingQuote) {
      idx = findQuotedTextEnd(text, idx, closingQuote) ?? text.length;
      continue;
    }
    const read = text[idx] === "@" ? readReferenceAt(text, idx) : undefined;
    if (!read) {
      idx += 1;
      continue;
    }
    if (idx > textStart) segments.push({ kind: "text", text: text.slice(textStart, idx), start: textStart });
    const reference = byToken.get(read.token);
    segments.push({
      kind: "reference",
      text: text.slice(idx, read.end),
      start: idx,
      token: read.token,
      ...(reference ? { reference } : {}),
    });
    textStart = read.end;
    idx = read.end;
  }
  if (text.length > textStart) {
    segments.push({ kind: "text", text: text.slice(textStart), start: textStart });
  }
  return segments;
};

// ---- What fits at the cursor (ENG-6950) -------------------------------------------------------------

/** A type a slot of the formula takes, or `"any"` where every type fits (inside `concat()`). */
export type TFormulaSlotType = TExpressionValueType | "any";

/** What decides the type at the cursor: the target field, a function's argument, or an operator. */
export type TFormulaSlotContext =
  | { kind: "field" }
  | { kind: "function"; fn: TExpressionFunction }
  | { kind: "operator"; symbol: string };

export interface TFormulaSlot {
  wanted: TFormulaSlotType;
  context: TFormulaSlotContext;
}

const PROBE_TYPES = ["number", "text", "date"] as const;

/** One fixed value of each type, for asking the shared type rules what a function takes and gives. */
const PROBE_VALUES: Record<(typeof PROBE_TYPES)[number], TExpression> = {
  number: { type: "static", value: 1 },
  text: { type: "static", value: "a" },
  date: { type: "call", fn: "now", args: [] },
};

const PROBE_CONTEXT: TExpressionTypeContext = {
  getElement: () => undefined,
  getComputedFieldType: () => undefined,
  getIngestedFieldType: () => undefined,
  getReservedFieldType: () => undefined,
};

const probeCall = (fn: TExpressionFunction, argCount: number, value: TExpression) =>
  checkExpressionTypes(
    { type: "call", fn, args: Array.from({ length: argCount }, () => value) },
    PROBE_CONTEXT
  );

/**
 * What a function returns, asked of the shared type rules (`checkExpressionTypes`) rather than kept in
 * a second list here: `"any"` for one whose result follows its arguments (`ifEmpty()`).
 */
export const getFunctionResultType = (fn: TExpressionFunction): TFormulaSlotType | undefined => {
  const argCount = EXPRESSION_FUNCTION_ARITY[fn].min;
  const results = new Set<TExpressionValueType>();
  for (const probeType of PROBE_TYPES) {
    const checked = probeCall(fn, argCount, PROBE_VALUES[probeType]);
    if (checked.issues.length === 0 && checked.type) results.add(checked.type);
  }
  if (results.size > 1) return "any";
  return results.values().next().value;
};

/** The type a function's argument at `argIdx` takes, asked of the shared type rules the same way. */
const getArgumentType = (fn: TExpressionFunction, argIdx: number): TFormulaSlotType => {
  const argCount = Math.max(EXPRESSION_FUNCTION_ARITY[fn].min, argIdx + 1);
  const accepted = PROBE_TYPES.filter((probeType) => {
    const checked = probeCall(fn, argCount, PROBE_VALUES[probeType]);
    return !checked.issues.some((issue) => issue.path[0] === "args" && issue.path[1] === argIdx);
  });
  return accepted.length === 1 ? accepted[0] : "any";
};

const ARITHMETIC = new Set(["+", "-", "*", "/"]);

type TSlotToken = { kind: "operator"; value: string } | { kind: "name"; value: string } | { kind: "value" };

/** One lenient token of a formula being typed, which rarely parses: what it is, and where the next starts. */
const readSlotToken = (prefix: string, idx: number): { token: TSlotToken; next: number } => {
  const char = prefix[idx];
  const operator = OPERATOR_ALIASES[char];
  if (operator) return { token: { kind: "operator", value: operator }, next: idx + 1 };
  if (char === "@") {
    const read = readReferenceAt(prefix, idx);
    return { token: { kind: "value" }, next: read?.end ?? idx + 1 };
  }
  const name = /^[A-Za-z_]\w*/.exec(prefix.slice(idx))?.[0];
  if (name) return { token: { kind: "name", value: name }, next: idx + name.length };
  const number = /^\d*\.?\d+/.exec(prefix.slice(idx))?.[0];
  return { token: { kind: "value" }, next: idx + (number?.length || 1) };
};

/** The tokens before the cursor, or `insideText` when the cursor sits in quoted text. */
const readSlotTokens = (prefix: string): { tokens: TSlotToken[]; insideText: boolean } => {
  const tokens: TSlotToken[] = [];
  let idx = 0;
  while (idx < prefix.length) {
    if (/\s/.test(prefix[idx])) {
      idx += 1;
      continue;
    }
    const closingQuote = QUOTES[prefix[idx]];
    if (closingQuote) {
      const end = findQuotedTextEnd(prefix, idx, closingQuote);
      if (end === undefined) return { tokens, insideText: true };
      tokens.push({ kind: "value" });
      idx = end;
      continue;
    }
    const read = readSlotToken(prefix, idx);
    tokens.push(read.token);
    idx = read.next;
  }
  return { tokens, insideText: false };
};

/** The brackets open at the cursor, innermost last, each with its function (if any) and argument. */
const getOpenFrames = (tokens: TSlotToken[]) => {
  const frames: { fn: TExpressionFunction | null; argIdx: number }[] = [];
  tokens.forEach((token, idx) => {
    if (token.kind !== "operator") return;
    if (token.value === "(") {
      const before = tokens[idx - 1];
      const fn = before?.kind === "name" ? FUNCTION_BY_LOWERCASE.get(before.value.toLowerCase()) : undefined;
      frames.push({ fn: fn ?? null, argIdx: 0 });
    } else if (token.value === ")") {
      frames.pop();
    } else if (token.value === ",") {
      const innermost = frames.at(-1);
      if (innermost) innermost.argIdx += 1;
    }
  });
  return frames;
};

/**
 * What type fits at the cursor of the formula box: next to `+ - * /` a number; inside a function's
 * brackets what that argument takes (a date inside `daysBetween()`); through plain brackets and
 * `ifEmpty()` whatever fits outside them; at the top the target field's type. Read from the text
 * around the selection, so a half-typed formula still answers.
 */
export const getFormulaSlot = (
  text: string,
  selection: { start: number; end: number },
  targetType: TExpressionValueType | undefined
): TFormulaSlot => {
  const start = Math.max(0, Math.min(selection.start, text.length));
  const end = Math.max(start, Math.min(selection.end, text.length));
  const { tokens, insideText } = readSlotTokens(text.slice(0, start));
  if (insideText) return { wanted: "any", context: { kind: "field" } };

  const previous = tokens.at(-1);
  if (previous?.kind === "operator" && ARITHMETIC.has(previous.value)) {
    return { wanted: "number", context: { kind: "operator", symbol: previous.value } };
  }
  const next = OPERATOR_ALIASES[text.slice(end).trimStart().charAt(0)];
  if (next && ARITHMETIC.has(next)) {
    return { wanted: "number", context: { kind: "operator", symbol: next } };
  }

  const frames = getOpenFrames(tokens);
  for (let idx = frames.length - 1; idx >= 0; idx -= 1) {
    const { fn, argIdx } = frames[idx];
    // Plain brackets, and a function whose result follows its arguments, pass the outer type through.
    if (!fn || getFunctionResultType(fn) === "any") continue;
    return { wanted: getArgumentType(fn, argIdx), context: { kind: "function", fn } };
  }
  return { wanted: targetType ?? "any", context: { kind: "field" } };
};

/** Whether a function chip's result fits the slot at the cursor, and what it returns when it doesn't. */
export const getFunctionFit = (
  fn: TExpressionFunction,
  slot: TFormulaSlot
): { fits: true } | { fits: false; returns: TExpressionValueType } => {
  const returns = getFunctionResultType(fn);
  if (slot.wanted === "any" || returns === undefined || returns === "any" || returns === slot.wanted) {
    return { fits: true };
  }
  return { fits: false, returns };
};
