import { Phoneme, Syllabe } from "./fr/phonem-extractor";
import { postTreatmentOpenCloseE } from "./fr/post-treatment";
import { rules } from "./fr/rules";
import { apostropheCharacters, apostropheRegExpSource } from "./fr/apostrophes";
import { SAMPA } from "./sampa";
import { createLogger } from "../../utils/debug";

const log = createLogger("syllabs");

const apostropheCharacterSet = new Set(apostropheCharacters);
const wordTokenRegExp = new RegExp(
  `[\\p{L}\\p{N}]+(?:[${apostropheRegExpSource}][\\p{L}\\p{N}]+)*|[^\\p{L}\\p{N}\\s]+|\\s+`,
  "gu"
);
const whitespaceOrPunctuationRegExp = /^(?:\s+|[^\p{L}\p{N}]+)$/u;

const liquidConsonants = new Set<string>([SAMPA.FR.consonants.l, SAMPA.FR.consonants.R]);
const plosiveOrFricativeConsonants = new Set<string>([
  SAMPA.FR.consonants.b, SAMPA.FR.consonants.k, SAMPA.FR.consonants.p, SAMPA.FR.consonants.t,
  SAMPA.FR.consonants.g, SAMPA.FR.consonants.d, SAMPA.FR.consonants.f, SAMPA.FR.consonants.v,
]);
const vowelsAfterU = new Set<string>([SAMPA.FR.vowels.i, SAMPA.FR.vowels["e~"], SAMPA.FR.vowels["o~"]]);
const consonantLetters = new Set(["b","c","d","f","g","h","j","k","l","m","n","p","q","r","s","t","v","w","x","z","ç"]);

/** Morceau d'une syllabe à afficher : texte, lettre muette ou apostrophe. */
interface SyllablePart {
  kind: "text" | "mute" | "apos";
  letters: string;
}

// Découpage déjà calculé par mot : les mêmes mots reviennent sans cesse sur une page.
const wordCache = new Map<string, SyllablePart[][]>();
const WORD_CACHE_MAX_SIZE = 10000;

class StateMachine<
  C extends string,
	SC extends string,
  V extends string,
	SV extends string
> {

  private _states: Map<string, State>;

  private _consonants: Record<C, string>;
  private _semiConsonants: Record<SC, string>;
  private _vowels: Record<V, string>;
  private _semiVowels: Record<SV, string>;

  private _isRed: boolean;

  constructor(states: Map<string, State>, consonants: Record<C, string>, semiConsonants: Record<SC, string>, vowels: Record<V, string>, semiVowels: Record<SV, string>) {
    this._states = states;
    this._consonants = consonants;
    this._semiConsonants = semiConsonants;
    this._vowels = vowels;
    this._semiVowels = semiVowels;
    this._isRed = true;
  }

  public extrairePhonemes(word: string, para?: string, p_para?: number): Phoneme<C, SC, V, SV>[] {
    const wordLower = word.toLowerCase();
    para = para ?? word;
    let np_para = p_para ?? 0;
    let pos = 0;
    const codage: Phoneme<C, SC, V, SV>[] = [];

    while (pos < wordLower.length) {
      const letter = wordLower[pos];
      const state = this._states.get(letter)
      let founded = false;
      if (state != undefined) {
        let i = 0;
        while(!founded && i < state.ruleOrder.length){
          const {isValid, phonem, step} = state.execute(state.ruleOrder[i], wordLower, pos + 1);
          if(isValid){
            codage.push(
              new Phoneme<C, SC, V, SV>(
                phonem,
                para.substring(np_para, np_para + step)
              )
            );
            pos += step;
            np_para += step;
            founded = true;
          }
          i++;
        }

        // Dernière letter -> phonème final
        const last = state.getLast();
        if (!founded && (pos == wordLower.length-1) && last != undefined) {
          codage.push(
            new Phoneme<C, SC, V, SV>(
              last.phonem,
              para.substring(np_para, np_para + last.step)
            )
          );
          pos += last.step;
          np_para += last.step;
          founded = true;
        }

        // Default phoneme '*'
        const defaultState = state.getDefault();
        if (!founded && defaultState != undefined) {
          codage.push(
            new Phoneme<C, SC, V, SV>(
              defaultState.phonem,
              para.substring(np_para, np_para + defaultState.step)
            )
          );
          pos += defaultState.step;
          np_para += defaultState.step;
          founded = true;
        }
      }

      if (!founded) {
        codage.push(
          new Phoneme<C, SC, V, SV>(
            null,
            para.substring(np_para, np_para + 1)
          )
        );
        pos++;
        np_para++;
      }
    }

    // Post traitement pour différencier les eu ouverts et fermés
    return postTreatmentOpenCloseE(codage);
  }

  private isSyllabicSemiVowel(phon: Phoneme<C, SC, V, SV>): boolean {
    const letters = phon.letters.toLowerCase();
    // Some written vowel groups are encoded as [w], but still carry a syllable nucleus.
    return (
      phon.phoneme === SAMPA.FR.semiVowels["w"] &&
      (letters === "oi" || letters === "o\u00ee" || letters === "o" || letters === "oy")
    );
  }

  private isApostrophePunctuation(phon: Phoneme<C, SC, V, SV>): boolean {
    return apostropheCharacterSet.has(phon.letters);
  }

extraireSyllabes(
  phonemes: Phoneme<C, SC, V, SV>[],
  std_lc: "std" | "no" = "no",
  oral_ecrit: "oral" | "ecrit" = "ecrit"
): Syllabe<C, SC, V, SV>[] {
  if (phonemes.length < 2) {
    const syll = new Syllabe<C, SC, V, SV>();
    syll.addPhonemes(phonemes);
    return [syll];
  }

  const nphonemes: Phoneme<C, SC, V, SV>[] = [];
  if (std_lc === "std") {
    // for (const phon of phonemes) {
    //   if (phon.isDoubleConsonant && phon.isDoubleConsonant()) {
    //     const cloned = phon.clone();
    //     nphonemes.push(phon, cloned);
    //   } else {
    //     nphonemes.push(phon);
    //   }
    // }
  } else {
    nphonemes.push(...phonemes);
  }

  const sylph: [string, number[]][] = [];
  for (const [i, phon] of nphonemes.entries()) {
    if (phon.isVowel(this._vowels) || phon.isSemiConsonant(this._semiConsonants) || this.isSyllabicSemiVowel(phon)) {
      sylph.push(["v", [i]]);
    } else if (phon.isConsonant(this._consonants)) {
      sylph.push(["c", [i]]);
    } else if (phon.isSemiVowel(this._semiVowels)) {
      sylph.push(["s", [i]]);
    } else {
      sylph.push([SAMPA.specials["#"], [i]]); // muted phoneme
    }
  }

  let i = 0;
  while (i < sylph.length - 1) {
    if (sylph[i][0] === "c" && sylph[i + 1][0] === "c") {
      const phon1 = nphonemes[sylph[i][1][0]];
      const phon2 = nphonemes[sylph[i + 1][1][0]];
      if (
        liquidConsonants.has(phon2.phoneme ?? "") &&
        plosiveOrFricativeConsonants.has(phon1.phoneme ?? "")
      ) {
        sylph[i][1].push(...sylph[i + 1][1]);
        sylph.splice(i + 1, 1);
      }
    }
    i++;
  }

  i = 0;
  while (i < sylph.length - 1) {
    if (sylph[i][0] === "v" && sylph[i + 1][0] === "v") {
      const p1 = nphonemes[sylph[i][1][0]];
      const p2 = nphonemes[sylph[i + 1][1][0]];
      if (
        (p1.phoneme === SAMPA.FR.vowels.y && p2.phoneme === SAMPA.FR.vowels.i) ||
        (p1.phoneme === SAMPA.FR.vowels.u && vowelsAfterU.has(p2.phoneme ?? ""))
      ) {
        sylph[i][1].push(...sylph[i + 1][1]);
        sylph.splice(i + 1, 1);
      }
    }
    i++;
  }

  i = 0;
  while (i < sylph.length - 1) {
    if (sylph[i + 1][0] === SAMPA.specials["#"]) {
      sylph[i][1].push(...sylph[i + 1][1]);
      sylph.splice(i + 1, 1);
    }
    i++;
  }

  const sylls: Syllabe<C, SC, V, SV>[] = [];
  i = 0;
  while (i < sylph.length) {
    let j = i;
    while (i < sylph.length && sylph[i][0] !== "v"){
      i++;
    }
    
    const curSyl = new Syllabe<C, SC, V, SV>();
    if (i < sylph.length && sylph[i][0] === "v") {
      i++;
      for (let k = j; k < i; k++) {
        curSyl.addPhonemes(sylph[k][1], nphonemes);
      }
      j = i;
      sylls.push(curSyl);
    }

    if (i+1 < sylph.length) {
			let letter1 = nphonemes[sylph[i][1][sylph[i][1].length-1]].letters;
			const letter = nphonemes[sylph[i+1][1][0]].letters[0];
			letter1 = letter1[letter1.length-1];
			if (consonantLetters.has(letter1) && consonantLetters.has(letter)) {
				curSyl.addPhonemes(sylph[i][1], nphonemes);
				i += 1;
				j = i;
			}
		}
  }

  if (sylls.length === 0) {
    const syll = new Syllabe<C, SC, V, SV>();
    syll.addPhonemes(nphonemes);
    return [syll];
  }

  const usedIndices = new Set(sylls.flatMap(s => s.phonemes.map(p => nphonemes.indexOf(p))));
  for (const [idx] of sylph.flatMap(s => s[1].map(i => [i]))) {
    if (!usedIndices.has(idx)) {
      sylls[sylls.length - 1].addPhonemes([nphonemes[idx]]);
    }
  }

  if (oral_ecrit === "oral" && sylls.length > 1) {
    const last = sylls[sylls.length - 1];
    const lastPh = last.phonemes[last.phonemes.length - 1];
    if (lastPh.isMutedPhoneme() || lastPh.phoneme === "q_caduc") {
      const prev = sylls[sylls.length - 2];
      prev.addPhonemes(last.phonemes);
      sylls.pop();
    }
  }

  return sylls;
}


  /** Découpage d'un mot en syllabes, mis en cache par mot. */
  private getWordParts(token: string): SyllablePart[][] {
    let parts = wordCache.get(token);
    if (parts === undefined) {
      const phonemes = this.extrairePhonemes(token);
      const syllabes = this.extraireSyllabes(phonemes, "no", "ecrit");
      parts = syllabes.map((syllabe) =>
        syllabe.phonemes.map((phonem): SyllablePart => {
          if (this.isApostrophePunctuation(phonem)) {
            return { kind: "apos", letters: phonem.letters };
          }
          if (phonem.phoneme === SAMPA.specials["#"]) {
            return { kind: "mute", letters: phonem.letters };
          }
          return { kind: "text", letters: phonem.letters };
        })
      );
      if (wordCache.size >= WORD_CACHE_MAX_SIZE) {
        wordCache.clear();
      }
      wordCache.set(token, parts);
    }
    return parts;
  }

  convert(sentence: string, element: HTMLElement) {
    const tokens = sentence.match(wordTokenRegExp) ?? [];
    for (const token of tokens) {
      if (whitespaceOrPunctuationRegExp.test(token)) {
        element.append(document.createTextNode(token));
      } else{
        const wordSpan = document.createElement("lisio-dys");

        for (const syllabe of this.getWordParts(token)) {
          const syllClass = this._isRed ? "red" : "blue";
          this._isRed = !this._isRed;
          let syllSpan = document.createElement("lisio-dys");
          syllSpan.classList.add(syllClass);
          const appendSyllSpan = () => {
            if (syllSpan.childNodes.length > 0) {
              wordSpan.append(syllSpan);
              syllSpan = document.createElement("lisio-dys");
              syllSpan.classList.add(syllClass);
            }
          };

          for (const part of syllabe) {
            if (part.kind === "apos") {
              appendSyllSpan();
              wordSpan.append(document.createTextNode(part.letters));
            } else if (part.kind === "mute") {
              const muteSpan = document.createElement("lisio-dys");
              muteSpan.textContent = part.letters;
              muteSpan.classList.add("mute");
              syllSpan.append(muteSpan);
            } else {
              syllSpan.append(document.createTextNode(part.letters));
            }
          }
          appendSyllSpan();
        }
        element.append(wordSpan);
      }
    }
  }
}

interface RuleSchemaRegExp{
  type : "regExp";
  regExps : {direction : "after" | "before", regExp : RegExp}[];
}

interface RuleSchemaFunction{
  type : "function";
  name : string;
}

type RuleSchema = (RuleSchemaRegExp | RuleSchemaFunction | null);

class Rule {
  private _schema: RuleSchema;

  private _phonem: string;

  private _step: number;

  public get schema(){
    return this._schema;
  }

  public get phonem(){
    return this._phonem;
  }

  public get step(){
    return this._step;
  }

  constructor(schema: RuleSchema, phonem: string, step: number){
    this._schema = schema;
    this._phonem = phonem;
    this._step = step;
  }
}

class State{
  private _name: string;

  private _ruleOrder: string[];

  private _rules: Map<string, Rule>;

  get name(){
    return this._name;
  }

  get ruleOrder(){
    return this._ruleOrder;
  }

  constructor(name: string, ruleOrder: string[], rules: Map<string, Rule>){
    this._name = name;
    this._ruleOrder = ruleOrder;
    this._rules = rules;
  }

  public getLast(){
    return this._rules.get(SAMPA.specials.$);
  }

  public getDefault(){
    return this._rules.get(SAMPA.specials["*"]);
  }

  public execute(ruleName: string, word: string, pos: number) {
    const rule = this._rules.get(ruleName);
    if(rule == undefined){
      log.log("no rule");
      return {isValid: false, phonem: "", step: 0};
    }else{
      if(rule.schema?.type === "function"){
        const func = rules.get(rule.schema.name);
        if(func == undefined){
          log.log("no func");
          return {isValid: false, phonem: "", step: 0};
        }else{
          return {isValid : func(word, pos), phonem: rule.phonem, step: rule.step};
        }
      }else{
        let findNext = true;
        let findPrev = true;

        if(rule.schema == null){
          return {isValid: true, phonem: rule.phonem, step: rule.step};
        }else{
          for(const schema of rule.schema?.regExps || []){
            if(schema.direction === "after"){
              const result = schema.regExp.exec(word.slice(pos));
              findNext = result != null && result.index === 0;
            }else if(schema.direction === "before"){
              findPrev = false;
              const regExpSource = schema.regExp.source;
              if(regExpSource[0] === "^"){
                if(regExpSource.length === 1){
                  findPrev = pos === 1;
                }else{
                  const result = schema.regExp.exec(word.substring(0, pos - 1));
                  findPrev = result !== null && result[0].length === pos - 1;
                }
              }else{
                let k = pos-2;
                while ((k > -1) && (!findPrev)) {
                  // il faut lire les letters qui précèdent
                  // recherche le modèle demandé à la fin du début du mot
                  const result = schema.regExp.exec(word.substring(k, pos-1));
                  if (result !== null) {
                    findPrev = (result[0].length == result.input.length);
                  }
                  k -= 1;
                }
              }
            }
          }
          return {isValid : findPrev && findNext, phonem: rule.phonem, step: rule.step};
        }

      }
    }
  }
}

export {Rule, State, StateMachine};
