import fc from "fast-check";
import { RE2JS } from "re2js";
import { describe, expect, test, vi } from "vitest";
import { validateBlockResponses } from "@formbricks/surveys/validation";
import { TSurveyElement, TSurveyElementTypeEnum } from "@formbricks/types/surveys/elements";
import { MAX_PATTERN_WORK_PER_RUN, createLinearPatternMatcher } from "./linear-pattern-matcher";

vi.mock("server-only", () => ({}));

const native = (pattern: string, flags: string | undefined, value: string): boolean =>
  new RegExp(pattern, flags).test(value);

// A fresh run per call, so the work budget never carries over between assertions.
const match = (pattern: string, flags: string | undefined, value: string) =>
  createLinearPatternMatcher()(pattern, flags, value);

/**
 * Runs `fn` and returns its result, failing if the backtracking engine executed `pattern` meanwhile.
 * The matcher may parse the pattern with `RegExp` (to refuse what the browser refuses) but never run it.
 */
const withoutBacktracking = <T>(pattern: string, fn: () => T): T => {
  // Compared as a string: the test patterns hold no `/` or line break, which `source` would escape.
  const exec = vi.spyOn(RegExp.prototype, "exec");
  try {
    const result = fn();
    const ranPattern = exec.mock.contexts.some((regex) => (regex as RegExp).source === pattern);
    expect(ranPattern).toBe(false);
    return result;
  } finally {
    exec.mockRestore();
  }
};

// Each takes the backtracking engine exponential (or high-polynomial) time on a short non-matching
// input; ^(a+)+$ alone blocked a request for 13 s at 28 characters. The last two are linear but slow per
// character in re2js (lookbehinds on its NFA; a huge compiled program), which the budget bounds.
const CATASTROPHIC_PATTERNS = [
  String.raw`^(a+)+$`,
  String.raw`^(a|aa)+$`,
  String.raw`^(a|a?)+$`,
  String.raw`^(\w+\s?)*$`,
  String.raw`^([a-zA-Z0-9]+\.?)+@example\.com$`,
  String.raw`(.*a){12}`,
  "(?:(?<=a)a|(?<=b)b){1000}".repeat(20),
  "(?:a|b){1000}".repeat(39),
];

// Patterns survey authors actually write, plus the syntax the translation and `\s`/`\S` rewrite touch.
const COMMON_PATTERNS: Array<[string, string | undefined]> = [
  [String.raw`^\d{5}$`, undefined],
  [String.raw`^[A-Z]{2}\d{6}$`, undefined],
  [String.raw`^[a-z]+$`, "i"],
  [String.raw`^\+?\d[\d\s-]{6,}$`, undefined],
  [String.raw`^[\w.+-]+@[\w-]+\.[\w.]+$`, undefined],
  [String.raw`^\s*$`, undefined],
  [String.raw`^\S+$`, undefined],
  [String.raw`^\d{3}\s?\d{3}$`, undefined],
  [String.raw`^[^\s]+$`, undefined],
  [String.raw`^[^\S\r\n]+$`, undefined],
  [String.raw`^a[^\S]b$`, undefined],
  [String.raw`[\s,;]`, undefined],
  [String.raw`\\s`, undefined],
  [String.raw`^a.b$`, "s"],
  [String.raw`^a.b$`, undefined],
  [String.raw`^b`, "m"],
  [String.raw`a$`, "m"],
  [String.raw`^(?<word>\w+)$`, undefined],
  [String.raw`\u00e9`, undefined],
  [String.raw`^\p{L}+$`, "u"],
  [String.raw`^.{3}$`, "u"],
  [String.raw`[]a]`, undefined],
  [String.raw`[^]`, undefined],
];

// Patterns whose answer depends on counting or classing UTF-16 code units.
const CODE_UNIT_PATTERNS: Array<[string, string | undefined]> = [
  ["^.{2}$", undefined],
  ["^.{1,3}$", undefined],
  ["^[^x]{2}$", undefined],
  [String.raw`^\S{2}$`, undefined],
  [String.raw`^\W+$`, undefined],
  [String.raw`^[\u0000-\uFFFF]+$`, undefined],
  [String.raw`^[\u0080-\uFFFF]+$`, undefined],
  [String.raw`^[\uD800-\uDBFF][\uDC00-\uDFFF]$`, undefined],
  [String.raw`^\uD83D\uDE00$`, undefined],
  [String.raw`^\uD83D`, undefined],
  // A literal emoji in the pattern: two code units, and `+` repeats only the second.
  ["^\u{1F600}+$", undefined],
  ["[\u{1F600}]", undefined],
  [String.raw`^[a\uD83D]+$`, undefined],
  ["^.{2}$", "u"],
  [String.raw`^\p{Extended_Pictographic}$`, "u"],
];

describe("createLinearPatternMatcher", () => {
  test.each(CATASTROPHIC_PATTERNS)("never backtracks on a 4096-character answer to %s", (pattern) => {
    const result = withoutBacktracking(pattern, () => match(pattern, undefined, `${"ab".repeat(2047)}a!`));

    expect(result === undefined || typeof result === "boolean").toBe(true);
  });

  test("skips rules once a run has spent its budget, instead of running or failing them", () => {
    const run = createLinearPatternMatcher(10_000);
    const value = "b".repeat(100);

    // Each call costs well over 1% of this budget, so 100 calls must exhaust it.
    const results = Array.from({ length: 100 }, () => run("^a+$", undefined, value));

    expect(results[0]).toBe(false);
    expect(results.at(-1)).toBeUndefined();
    // Once the budget is spent, every later rule in the run is skipped, never failed.
    expect(results.slice(results.indexOf(undefined))).toEqual(
      Array.from({ length: 100 - results.indexOf(undefined) }, () => undefined)
    );
    // A new run starts with a full budget.
    expect(createLinearPatternMatcher(10_000)("^a+$", undefined, value)).toBe(false);
  });

  test("never runs more work than the budget, however many pathological rules a survey carries", () => {
    const run = createLinearPatternMatcher();
    // ~2,000 instructions: under the program cap, so each rule would run if the budget allowed.
    const pattern = "(?:a|b){1000}".repeat(2);
    const value = `${"ab".repeat(2047)}c!`;

    // Counts the `test` path only; a `y` rule runs through `lookingAt()`, under the same budget check.
    let work = 0;
    const test = vi.spyOn(RE2JS.prototype, "test");
    test.mockImplementation(function (this: RE2JS, input: Parameters<RE2JS["test"]>[0]) {
      work += this.programSize() * input.length;
      return false;
    });
    try {
      const results = Array.from({ length: 50 }, () => run(pattern, undefined, value));
      expect(test).toHaveBeenCalled();
      expect(results).toContain(undefined);
    } finally {
      test.mockRestore();
    }
    expect(work).toBeLessThanOrEqual(MAX_PATTERN_WORK_PER_RUN);
  });

  test("does not run a pattern that compiles past the program cap, and remembers it", () => {
    const pattern = ".{1000}".repeat(72);

    const compileSpy = vi.spyOn(RE2JS, "compile");
    try {
      expect(match(pattern, undefined, "a")).toBeUndefined();
      expect(match(pattern, undefined, "a")).toBeUndefined();
      // Compiled (~60 ms) for the first response only.
      expect(compileSpy).toHaveBeenCalledTimes(1);
    } finally {
      compileSpy.mockRestore();
    }
  });

  test("keeps a long but realistic pattern under the program cap", () => {
    expect(match("^.{1,1000}$", undefined, "a".repeat(1000))).toBe(true);
  });

  test("leaves real surveys far inside the budget", () => {
    const run = createLinearPatternMatcher();
    const answer = "someone.name+tag@example-company.com";
    for (let i = 0; i < 500; i++) {
      expect(run(String.raw`^[\w.+-]+@[\w-]+\.[\w.]+$`, undefined, answer)).toBe(true);
    }
  });

  test.each([
    ["^\\d{5}$", undefined, "12345", true],
    ["^\\d{5}$", undefined, "1234a", false],
    ["^[a-z]+$", "i", "ABC", true],
    ["^b", "m", "a\nb", true],
    ["^b", undefined, "a\nb", false],
    ["a.b", "s", "a\nb", true],
    ["a.b", undefined, "a\nb", false],
  ] as const)("matches %s (flags %s) against %j like RegExp", (pattern, flags, value, expected) => {
    expect(match(pattern, flags, value)).toBe(expected);
    expect(native(pattern, flags, value)).toBe(expected);
  });

  test("splits whitespace from non-whitespace where the browser does", () => {
    for (const space of ["\u00a0", "\u2007", "\u202f", "\u3000", "\ufeff", "\u000b"]) {
      expect(match(String.raw`^\d{3}\s\d{3}$`, undefined, `123${space}456`)).toBe(true);
      expect(match(String.raw`^[\s]+$`, undefined, space)).toBe(true);
      expect(match(String.raw`^[^\s]+$`, undefined, space)).toBe(false);
      expect(match(String.raw`^\S$`, undefined, space)).toBe(false);
      expect(match(String.raw`^[^\S\r\n]$`, undefined, space)).toBe(true);
    }
  });

  test("leaves an escaped backslash followed by s alone", () => {
    expect(match(String.raw`^\\s$`, undefined, String.raw`\s`)).toBe(true);
    expect(match(String.raw`^\\s$`, undefined, " ")).toBe(false);
  });

  test.each<[pattern: string, flags: string | undefined, reason: string]>([
    ["(?=a)a", undefined, "lookahead"],
    ["(?!a)b", undefined, "negative lookahead"],
    ["(?<=a)b", undefined, "lookbehind"],
    ["(a)\\1", undefined, "backreference"],
    ["^(?<n>a)\\k<n>$", undefined, "named backreference"],
    ["^(?<n>a)\\k<n>$", "u", "named backreference with u"],
    ["\\Aa", undefined, "\\A is the letter A without u"],
    ["a\\z", undefined, "\\z is the letter z without u"],
    ["\\Qa\\E", undefined, "\\Q and \\E are letters without u"],
    ["\\p{L}", undefined, "\\p is the letter p without u"],
    ["[invalid", undefined, "invalid pattern"],
    ["a", "q", "invalid flag"],
  ])("does not evaluate %s (flags %s): %s", (pattern, flags) => {
    expect(match(pattern, flags, "a")).toBeUndefined();
  });

  test.each<[pattern: string, flags: string | undefined, reason: string]>([
    ["^[\\01-\\uDFFF]$", undefined, "legacy octal escape"],
    ["^\\12$", undefined, "octal or backreference"],
    ["^[\\u{41}]$", undefined, "\\u{41} is u repeated 41 times without u"],
    ["^\\x{41}$", undefined, "\\x{41} is x repeated 41 times without u"],
    ["^(?m:^b)$", undefined, "a (?m: modifier group sees CR as a line break"],
    ["^(?-s:.)$", "s", "a (?-s: modifier group changes what . matches"],
    ["^\\uD83D\\uDE00$", "u", "with u, a surrogate pair escape is one code point"],
    ["^\\u{D83D}$", "u", "with u, a lone surrogate escape"],
    ["^[a]$", "v", "v flag"],
  ])("does not evaluate %s (flags %s): %s", (pattern, flags) => {
    expect(match(pattern, flags, "a")).toBeUndefined();
  });

  test.each([
    // JavaScript reads `[[:alpha:]` as a class holding "[", ":", "a", "l", "p", "h", then a literal "]".
    ["^[[:alpha:]]$", "a]", true],
    ["^[[:alpha:]]$", "b]", false],
    ["^[[:alpha:]]$", "[]", true],
    ["^a\\0$", "a\u0000", true],
    ["^[\\0-\\x1F]$", "\u001f", true],
  ])("reads %s against %j as RegExp does (%s)", (pattern, value, expected) => {
    expect(native(pattern, undefined, value)).toBe(expected);
    expect(match(pattern, undefined, value)).toBe(expected);
  });

  test("does not evaluate a multiline pattern against an answer with a line break RE2 does not see", () => {
    for (const lineBreak of ["\r", "\u2028", "\u2029"]) {
      expect(match("^b", "m", `a${lineBreak}b`)).toBeUndefined();
    }
    expect(match("^b", "m", "a\nb")).toBe(true);
  });

  test.each<[pattern: string, flags: string | undefined, value: string]>([
    ["^.$", undefined, "\r"],
    ["^.$", undefined, "\u2028"],
    ["^.$", "u", "\u2029"],
    ["^.$", "s", "\r"],
    ["^.{2}$", undefined, "\uD83D\uDE00"],
    ["^.$", "u", "\uD83D\uDE00"],
    ["^[.]$", undefined, "\r"],
    ["^\\.$", undefined, "."],
    ["^(?i:a)$", undefined, "A"],
  ])("matches %s with flags %s as RegExp does on %j", (pattern, flags, value) => {
    expect(match(pattern, flags, value)).toBe(native(pattern, flags, value));
  });

  test.each<[pattern: string, flags: string, value: string]>([
    ["a", "y", "xa"],
    ["a", "y", "ax"],
    ["b|ab", "y", "ab"],
    ["\\B", "y", "xx"],
    ["^a", "my", "x\na"],
    ["x", "uy", "\u{1F600}x"],
    ["x", "y", "\u{1F600}x"],
  ])("matches %s with flags %s only at the start of %j, as a sticky RegExp does", (pattern, flags, value) => {
    expect(match(pattern, flags, value)).toBe(native(pattern, flags, value));
  });

  test("agrees with RegExp on printable ASCII answers", () => {
    const asciiAnswer = fc.string({
      unit: fc.constantFrom(..."aAbBzZ019 -_.@+,;\t\n\\".split("")),
      maxLength: 16,
    });
    fc.assert(
      fc.property(fc.constantFrom(...COMMON_PATTERNS), asciiAnswer, ([pattern, flags], value) => {
        expect(match(pattern, flags, value)).toBe(native(pattern, flags, value));
      }),
      { numRuns: 3000 }
    );
  });

  // The server must never refuse an answer the respondent's browser accepted.
  test("never refuses an answer RegExp accepts, whatever the characters", () => {
    const anyAnswer = fc.string({
      unit: fc.constantFrom(
        ..."aAbB1 \t\n\r\u000b\u00a0\u2028\u2029\u3000\ufeff\u00e9\u017f\u212a-.".split(""),
        "\u{1F600}",
        "\uD83D",
        "\uDE00"
      ),
      maxLength: 12,
    });
    fc.assert(
      fc.property(
        fc.constantFrom(...COMMON_PATTERNS, ...CODE_UNIT_PATTERNS),
        anyAnswer,
        ([pattern, flags], value) => {
          if (native(pattern, flags, value)) {
            expect(match(pattern, flags, value)).not.toBe(false);
          }
        }
      ),
      { numRuns: 5000 }
    );
  });

  // Without `u` the browser matches UTF-16 code units: an emoji is two characters, and a lone
  // surrogate is one.
  test("matches emoji and lone surrogates code unit by code unit, as RegExp does without u", () => {
    const answer = fc.string({
      unit: fc.constantFrom("a", "x", " ", "\u00e9", "\uFFFF", "\u{1F600}", "\u{10FFFF}", "\uD83D", "\uDE00"),
      maxLength: 8,
    });
    fc.assert(
      fc.property(fc.constantFrom(...CODE_UNIT_PATTERNS), answer, ([pattern, flags], value) => {
        expect(match(pattern, flags, value)).toBe(native(pattern, flags, value));
      }),
      { numRuns: 5000 }
    );
  });

  test.each([
    ["^.{2}$", "\u{1F600}", true],
    ["^.{10}$", "\u{1F600}".repeat(5), true],
    ["^.$", "\u{1F600}", false],
    ["^[\u0080-\uFFFF]+$", "\u{1F600}", true],
  ])("without u, %s against %j is %s, as in the browser", (pattern, value, expected) => {
    expect(native(pattern, undefined, value)).toBe(expected);
    expect(match(pattern, undefined, value)).toBe(expected);
  });
});

describe("validateBlockResponses with the linear-time matcher", () => {
  const element = {
    id: "q1",
    type: TSurveyElementTypeEnum.OpenText,
    headline: { default: "Code" },
    required: false,
    inputType: "text",
    charLimit: { enabled: false },
    validation: {
      logic: "and",
      rules: [{ id: "r1", type: "pattern", params: { pattern: "^(a+)+$" } }],
    },
  } as unknown as TSurveyElement;

  test("rejects a non-matching answer to a catastrophic pattern without backtracking", () => {
    const errors = withoutBacktracking("^(a+)+$", () =>
      validateBlockResponses([element], { q1: `${"a".repeat(4095)}!` }, "default", {
        matchPattern: createLinearPatternMatcher(),
      })
    );

    expect(errors.q1?.[0]?.ruleType).toBe("pattern");
  });

  test("passes a rule the run has no budget left for, leaving it to the browser", () => {
    expect(
      validateBlockResponses([element], { q1: `${"a".repeat(4095)}!` }, "default", {
        matchPattern: createLinearPatternMatcher(0),
      })
    ).toEqual({});
  });

  test("accepts a matching answer", () => {
    expect(
      validateBlockResponses([element], { q1: "a".repeat(4096) }, "default", {
        matchPattern: createLinearPatternMatcher(),
      })
    ).toEqual({});
  });
});
