/**
 * Plural-canonical envelope tests for the code-map tool.
 * See companion: memoryTool.pluralCanonical.test.js.
 */
import { describe, test, expect } from '@jest/globals';
import CodeMapTool from '../codeMapTool.js';

const SILENT_LOGGER = { info() {}, warn() {}, error() {}, debug() {} };
const makeTool = () => new CodeMapTool({}, SILENT_LOGGER);

describe('_normalizeToActions — code-map', () => {
  test('promotes singular {action: "skeleton", path}', () => {
    const r = makeTool()._normalizeToActions({ action: 'skeleton', path: 'src/' });
    expect(r).toEqual([{ type: 'skeleton', path: 'src/' }]);
  });

  test('flattens singular {action, parameters: {...}}', () => {
    const r = makeTool()._normalizeToActions({
      action: 'read-range',
      parameters: { filePath: 'src/x.js', startLine: 1, endLine: 50 },
    });
    expect(r).toEqual([{ type: 'read-range', filePath: 'src/x.js', startLine: 1, endLine: 50 }]);
  });

  test('canonical plural unchanged', () => {
    const r = makeTool()._normalizeToActions({
      actions: [
        { type: 'skeleton', path: 'src/' },
        { type: 'read-range', filePath: 'src/x.js', startLine: 1, endLine: 50 },
      ],
    });
    expect(r).toHaveLength(2);
    expect(r[0].type).toBe('skeleton');
  });

  test('renames {actions: [{action: "X"}]} to type', () => {
    const r = makeTool()._normalizeToActions({
      actions: [{ action: 'skeleton', path: 'src/' }],
    });
    expect(r).toEqual([{ type: 'skeleton', path: 'src/' }]);
  });
});

describe('customValidateParameters — code-map plural', () => {
  test('singular {action: "skeleton", path} validates', () => {
    const v = makeTool().customValidateParameters({ action: 'skeleton', path: 'src/' });
    expect(v.valid).toBe(true);
  });

  test('plural with two valid actions validates', () => {
    const v = makeTool().customValidateParameters({
      actions: [
        { type: 'skeleton', path: 'src/' },
        { type: 'read-range', filePath: 'src/x.js', startLine: 1, endLine: 50 },
      ],
    });
    expect(v.valid).toBe(true);
  });

  test('plural with bad action[1] reports by index', () => {
    const v = makeTool().customValidateParameters({
      actions: [
        { type: 'skeleton', path: 'src/' },
        { type: 'read-range' /* missing filePath/startLine/endLine */ },
      ],
    });
    expect(v.valid).toBe(false);
    expect(v.errors.join(' ')).toMatch(/actions\[1\]/);
  });

  test('invalid type still gets the right-tool hint', () => {
    const v = makeTool().customValidateParameters({
      actions: [{ type: 'search', query: 'foo' }],
    });
    expect(v.valid).toBe(false);
    expect(v.errors.join(' ').toLowerCase()).toContain('seek');
  });

  test('empty params rejected', () => {
    const v = makeTool().customValidateParameters({});
    expect(v.valid).toBe(false);
  });
});
