import assert from 'node:assert/strict';
import test from 'node:test';
import {
  normalizeCflintParserCompatMode,
  rewriteStrictEqualityForCflint
} from '../src/linters/cflint-compat.js';

test('rewrites strict equality operators without changing source length or lines', () => {
  const source = [
    'if (arguments.value === "inoltra" and',
    '    local.owner !== arguments.owner) {',
    '  return true;',
    '}'
  ].join('\n');

  const result = rewriteStrictEqualityForCflint(source);

  assert.equal(result.replacementCount, 2);
  assert.equal(result.content.length, source.length);
  assert.equal(result.content.split('\n').length, source.split('\n').length);
  assert.match(result.content, /arguments\.value ==  "inoltra"/);
  assert.match(result.content, /local\.owner !=  arguments\.owner/);
  assert.doesNotMatch(result.content, /===|!==/);
});

test('returns unchanged content when compatibility is not required', () => {
  const source = 'writeDump(1 == 2);';
  const result = rewriteStrictEqualityForCflint(source);

  assert.equal(result.replacementCount, 0);
  assert.equal(result.content, source);
});

test('does not rewrite strict operator text inside strings or comments', () => {
  const source = [
    'local.operator = "===";',
    "local.otherOperator = '!==';",
    '// arguments.left === arguments.right',
    '/* arguments.left !== arguments.right */',
    '<!--- arguments.left === arguments.right --->',
    'return arguments.left === arguments.right;'
  ].join('\n');
  const result = rewriteStrictEqualityForCflint(source);

  assert.equal(result.replacementCount, 1);
  assert.match(result.content, /local\.operator = "==="/);
  assert.match(result.content, /local\.otherOperator = '!=='/);
  assert.match(result.content, /\/\/ arguments\.left === arguments\.right/);
  assert.match(result.content, /\/\* arguments\.left !== arguments\.right \*\//);
  assert.match(result.content, /<!--- arguments\.left === arguments\.right --->/);
  assert.match(result.content, /return arguments\.left ==  arguments\.right/);
});

test('normalizes parser compatibility configuration with auto as safe default', () => {
  assert.equal(normalizeCflintParserCompatMode(undefined), 'auto');
  assert.equal(normalizeCflintParserCompatMode('AUTO'), 'auto');
  assert.equal(normalizeCflintParserCompatMode(' off '), 'off');
  assert.equal(normalizeCflintParserCompatMode('unexpected'), 'auto');
});
