import {
  stateRuleExamples as generatedStateRuleExamples,
  type RuleWordExample,
} from "./generated-rule-examples.ts";
import { manualStateRuleExamples } from "./manual-rule-examples.ts";
import { Rule, State } from "../../../../src/adapters/syllabs/state-machine.ts";

type StateModule = Record<string, unknown>;
type RuleWordExampleWithSelection = RuleWordExample & {
  assertSelected?: boolean;
  expectedIsValid?: boolean;
};

const stateRuleExamples: Record<
  string,
  Record<string, RuleWordExampleWithSelection>
> = Object.fromEntries(
  Object.entries(generatedStateRuleExamples).map(([stateName, examples]) => [
    stateName,
    {
      ...examples,
      ...(manualStateRuleExamples[stateName] || {}),
    },
  ]),
);

function getRulesMap(state: State): Map<string, Rule> {
  return (state as unknown as { _rules: Map<string, Rule> })._rules;
}

function normalizeRule(rule: Rule) {
  if (rule.schema === null) {
    return {
      schema: null,
      phonem: rule.phonem,
      step: rule.step,
    };
  }

  if (rule.schema.type === "function") {
    return {
      schema: {
        type: "function",
        name: rule.schema.name,
      },
      phonem: rule.phonem,
      step: rule.step,
    };
  }

  return {
    schema: {
      type: "regExp",
      regExps: rule.schema.regExps.map((regExpSchema) => ({
        direction: regExpSchema.direction,
        source: regExpSchema.regExp.source,
        flags: regExpSchema.regExp.flags,
      })),
    },
    phonem: rule.phonem,
    step: rule.step,
  };
}

function getExportedState(module: StateModule): State {
  const exportedState = Object.values(module).find(
    (value): value is State =>
      value instanceof State ||
      (typeof value === "object" &&
        value !== null &&
        "execute" in value &&
        "ruleOrder" in value),
  );

  if (exportedState === undefined) {
    throw new Error("No State export found in test module.");
  }

  return exportedState;
}

function getSelectedRule(state: State, word: string, position: number) {
  for (const ruleName of state.ruleOrder) {
    if (state.execute(ruleName, word, position).isValid) {
      return ruleName;
    }
  }

  if (position === word.length && state.getLast() !== undefined) {
    return "$";
  }

  if (state.getDefault() !== undefined) {
    return "*";
  }

  return null;
}

export function describeExportedStateRules(
  label: string,
  module: StateModule,
) {
  const state = getExportedState(module);
  const rulesMap = getRulesMap(state);
  const examples = stateRuleExamples[label] || stateRuleExamples[state.name] || {};

  describe(`${label} state rules`, () => {
    it("keeps the expected ordered rule list", () => {
      expect(state.ruleOrder).toMatchSnapshot();
    });

    it("has one example for each rule", () => {
      expect(Object.keys(examples).sort()).toEqual(
        [...rulesMap.keys()].sort(),
      );
    });

    for (const [ruleName, rule] of rulesMap.entries()) {
      it(`matches "${ruleName}"`, () => {
        expect(normalizeRule(rule)).toMatchSnapshot();
      });

      it(`matches "${ruleName}" on a French example`, () => {
        const example = examples[ruleName];

        expect(example).toBeDefined();
        if (example === undefined) {
          return;
        }

        const executeWord = example.executeWord || example.word.toLowerCase();
        const result = state.execute(ruleName, executeWord, example.position);
        const expectedIsValid = example.expectedIsValid ?? true;

        expect(result.isValid).toBe(expectedIsValid);
        expect(result.phonem).toBe(rule.phonem);
        expect(result.step).toBe(rule.step);

        if (expectedIsValid && example.assertSelected !== false) {
          expect(getSelectedRule(state, executeWord, example.position)).toBe(
            ruleName,
          );
        }
      });
    }
  });
}
