import { Phoneme } from "./phonem-extractor";
import { SAMPA, SAMPAFRConsonants, SAMPAFRSemiConsonants, SAMPAFRSemiVowels, SAMPAFRVowels } from "../sampa";

	const osseWord = [
    "cabosse",
    "carabosse",
    "carrosse",
    "colosse",
    "molosse",
    "cosse",
    "crosse",
    "bosse",
    "brosse",
    "rhinocéros",
    "désosse",
    "fosse",
    "gosse",
    "molosse",
    "écosse",
    "rosse",
    "panosse"
];

const sylConClosed = [
  SAMPA.FR.consonants.p,
  SAMPA.FR.consonants.k,
  SAMPA.FR.consonants.b,
  SAMPA.FR.consonants.d,
  SAMPA.FR.consonants.g,
  SAMPA.FR.consonants.f,
  SAMPA.FR.consonants.s,
  SAMPA.FR.consonants.S,
  SAMPA.FR.consonants.l,
  SAMPA.FR.consonants.R,
  SAMPA.FR.consonants.m,
  SAMPA.FR.consonants.n
];

// Next phonemes for yod rules
const nextPhon = [
  SAMPA.FR.vowels.a,
  SAMPA.FR.vowels["a~"],
  SAMPA.FR.vowels.e,
  SAMPA.FR.vowels.E,
  SAMPA.FR.vowels.o,
  SAMPA.FR.vowels["o~"],
  SAMPA.FR.vowels.x,
  SAMPA.FR.vowels["x^"],
  SAMPA.FR.vowels.u,
  SAMPA.FR.vowels.y,
  SAMPA.FR.vowels.i,
  SAMPA.FR.vowels["2"],
  SAMPA.FR.vowels["9"]
];

// Consonants triggering closed eu
const consSoundEuClose = [
  SAMPA.FR.consonants.z,
  SAMPA.FR.consonants.s,
  SAMPA.FR.consonants.t
];

function postTreatmentOpenCloseO(pp: Phoneme<SAMPAFRConsonants, SAMPAFRSemiConsonants, SAMPAFRVowels, SAMPAFRSemiVowels>[]): Phoneme<SAMPAFRConsonants, SAMPAFRSemiConsonants, SAMPAFRVowels, SAMPAFRSemiVowels>[] {
  if (!Array.isArray(pp) || pp.length <= 1) return pp;
  if (!pp.some(p => p.phoneme === SAMPA.FR.vowels["o"])) return pp; // no [o] in word

  // Remove trailing muted phonemes (“#”)
  const npp = [...pp];
  while (npp.length && npp[npp.length - 1].phoneme === SAMPA.specials["#"]){
    npp.pop();
  }

  // Word reconstruction (based on letters)
  const word = npp.map(p => p.letters).join("");

  if (osseWord.includes(word)) {
    // words in “osse” → open o
    for (const p of pp) {
      if (p.phoneme === SAMPA.FR.vowels["o"]){
        p.phoneme = SAMPA.FR.vowels["O"];
      }
    }
    return pp;
  }

  // Determine open/closed 'o'
  for (let i = 0; i < npp.length; i++) {
    const p = npp[i];
    if (p.phoneme === SAMPA.FR.vowels["o"]){
  // open syllable (final position) → closed o
      if (i === npp.length - 1){
        return pp;
      }

      if (p.letters !== "ô") {
        const case1 =
          i === npp.length - 3 &&
          sylConClosed.includes(pp[i + 1].phoneme || "") &&
          pp[i + 2].phoneme === SAMPA.FR.vowels["@"];

        const case2 =
          [SAMPA.FR.consonants["R"], "z^_g", SAMPA.FR.consonants["v"]].includes(pp[i + 1].phoneme || "");

        const case3 =
          i < pp.length - 2 &&
          (pp[i + 1].phoneme || "") in SAMPA.FR.consonants &&
          (pp[i + 2].phoneme || "") in SAMPA.FR.consonants;

        if (case1 || case2 || case3){
          p.phoneme = SAMPA.FR.vowels["O"]
        };
      }
    }
  }
  return pp;
}

/* -------------------------------------------------------------------- */

function postTreatmentYod(pp: Phoneme<SAMPAFRConsonants, SAMPAFRSemiConsonants, SAMPAFRVowels, SAMPAFRSemiVowels>[]): Phoneme<SAMPAFRConsonants, SAMPAFRSemiConsonants, SAMPAFRVowels, SAMPAFRSemiVowels>[] {
  if (!Array.isArray(pp) || pp.length <= 1){
    return pp;
  }
  if (!pp.some(p => p.phoneme === SAMPA.FR.semiVowels["j"])){
    return pp;
  }// no yod

  const result: Phoneme<SAMPAFRConsonants, SAMPAFRSemiConsonants, SAMPAFRVowels, SAMPAFRSemiVowels>[] = [];

  for (let i = 0; i < pp.length; i++) {
    const p = pp[i];
    const next = pp[i + 1];
    if (p.phoneme === SAMPA.FR.semiVowels["j"] && next && nextPhon.includes(next.phoneme || "")) {
      // merge into combined j_...
      p.phoneme = `${SAMPA.FR.semiVowels["j"]}_${next.phoneme}`;
      p.letters = p.letters + next.letters;
      i++; // skip next
    }
    result.push(p);
  }

  return result;
}

/* -------------------------------------------------------------------- */

function postTreatmentOpenCloseE<C extends string, SC extends string, V extends string, SV extends string>(pp: Phoneme<C, SC, V, SV>[]): Phoneme<C, SC, V, SV>[] {
  if (!Array.isArray(pp) || pp.length < 2){
    return pp;
  }
  if (!pp.some(p => p.phoneme === SAMPA.FR.vowels["x"])){
    return pp;
  } // no [ø]/[œ]

  // last pronounced phoneme index
  let lpp = pp.length - 1;
  while (lpp > 0 && pp[lpp].phoneme === SAMPA.specials["#"]){
    lpp--;
  };

  const i_ph = pp.map(p => p.phoneme).lastIndexOf(SAMPA.FR.vowels["x"]);
  if (i_ph < lpp - 2){
    return pp;// too early to decide
  } 

  if (i_ph === lpp) {
    // last phoneme pronounced is 'eu' → closed
    pp[i_ph].phoneme = SAMPA.FR.vowels["x^"];
    return pp;
  }

  // 'eu' before consonant + schwa
  if (
    consSoundEuClose.includes(pp[i_ph + 1].phoneme || "") &&
    pp[pp.length - 1].phoneme === SAMPA.FR.vowels["@"]
  ) {
    pp[i_ph].phoneme = SAMPA.FR.vowels["x^"];
  }

  return pp;
}

function sanitizeString(str: string): string {
  return str
    .normalize("NFD")
    .replace(/[\u0300-\u036f]/g, "") // remove diacritic marks
    .replace(/[_-]/g, "")
    .toLowerCase();
}

export {postTreatmentOpenCloseE, postTreatmentOpenCloseO, postTreatmentYod, sanitizeString};