import fs from "node:fs";
import path from "node:path";
import { createRequire } from "node:module";
import { pathToFileURL } from "node:url";

import { State } from "../../../../src/adapters/syllabs/state-machine.ts";

type ExampleSource = "raw" | "end-marker" | "apostrophe-coded";

interface RuleExample {
  executeWord?: string;
  position: number;
  source: ExampleSource;
  word: string;
}

type StateRuleExamples = Record<string, Record<string, RuleExample>>;

const require = createRequire(import.meta.url);
const frenchWords = require("an-array-of-french-words") as string[];

function getExportedState(moduleValue: Record<string, unknown>): State {
  const exportedState = Object.values(moduleValue).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.");
  }

  return exportedState;
}

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

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;
}

function getWordVariants(word: string) {
  const lowerWord = word.toLowerCase();
  const variants: { executeWord: string; source: ExampleSource }[] = [
    { executeWord: lowerWord, source: "raw" },
    { executeWord: `${lowerWord}$`, source: "end-marker" },
  ];

  if (lowerWord.includes("'")) {
    variants.push({
      executeWord: `${lowerWord.replaceAll("'", "@")}$`,
      source: "apostrophe-coded",
    });
  }

  return variants;
}

function getPositions(executeWord: string, stateName: string) {
  const positions: number[] = [];

  if (stateName === "$" || stateName === "_") {
    return positions;
  }

  for (let index = 0; index < executeWord.length; index++) {
    if (executeWord.slice(index, index + stateName.length) === stateName) {
      positions.push(index + 1);
    }
  }

  return positions;
}

function serializeExamples(examples: StateRuleExamples) {
  return `export interface RuleWordExample {\n  word: string;\n  position: number;\n  source: "raw" | "end-marker" | "apostrophe-coded";\n  executeWord?: string;\n}\n\nexport const stateRuleExamples = ${JSON.stringify(examples, null, 2)} as const;\n`;
}

async function main() {
  const statesDir = path.join(process.cwd(), "src/adapters/syllabs/fr/states");
  const files = fs.readdirSync(statesDir).sort((a, b) => a.localeCompare(b));
  const examples: StateRuleExamples = {};
  const missing: { state: string; rule: string }[] = [];

  for (const file of files) {
    const stateModule = (await import(
      pathToFileURL(path.join(statesDir, file)).href
    )) as Record<
      string,
      unknown
    >;
    const state = getExportedState(stateModule);
    const stateRules = [...getStateRulesMap(state).keys()];
    examples[state.name] = {};

    for (const ruleName of stateRules) {
      if (stateNameNeedsManualExample(state.name, ruleName)) {
        continue;
      }

      let found: RuleExample | undefined;

      for (const word of frenchWords) {
        for (const variant of getWordVariants(word)) {
          for (const position of getPositions(variant.executeWord, state.name)) {
            if (getSelectedRule(state, variant.executeWord, position) === ruleName) {
              found = {
                executeWord:
                  variant.executeWord === word.toLowerCase()
                    ? undefined
                    : variant.executeWord,
                position,
                source: variant.source,
                word,
              };
              break;
            }
          }

          if (found !== undefined) {
            break;
          }
        }

        if (found !== undefined) {
          break;
        }
      }

      if (found === undefined) {
        missing.push({ state: file, rule: ruleName });
      } else {
        examples[state.name][ruleName] = found;
      }
    }
  }

  const outputPath = path.join(
    process.cwd(),
    "tests/adapters/syllabs/fr/generated-rule-examples.ts",
  );
  fs.writeFileSync(outputPath, serializeExamples(examples));

  console.log(`Generated examples at ${outputPath}`);
  console.log(`Missing examples: ${missing.length}`);
  for (const entry of missing) {
    console.log(`${entry.state} :: ${entry.rule}`);
  }
}

function stateNameNeedsManualExample(stateName: string, ruleName: string) {
  return (
    stateName === "$" ||
    stateName === "_" ||
    (stateName === "'" && (ruleName === "*" || ruleName === "$"))
  );
}

main().catch((error) => {
  console.error(error);
  process.exitCode = 1;
});
