import Detector from "./Detector.js";
import compromise from 'fr-compromise';
import conj from 'conjugation-fr';
import { toInfinitive } from "../data/index.js"; 
import { cleanMessageContent } from "../utils/strings.js";

/*check the pronoun / subject of the question to answer properly by conjugating
exemple : tu fais quoi ? je fais feur
*/

const suffixes = [
  ', mon gars',
  ', mec',
  ", je crois",
  '', '', ''
];

export default class withPronounDetector extends Detector {
  async createSpecificReply(message) {
    const reference = await message.fetchReference().catch(() => null);
    const isSelfTarget = (reference && reference.author.id === message.client.user?.id) ?? false;

    const text = cleanMessageContent(message).toLowerCase();
    const compromiseMatch = compromise(text).match('(#Pronoun|ça|ca|tu) (#Verb|fait) #Infinitive? quoi [<suffix>!Verb{0,3}]$');

    if (compromiseMatch == null || compromiseMatch.length === 0) {
      // console.log("DEBUG: Pas de structure 'Sujet + Verbe + Quoi' détectée.");
      return null;
    }

    return this.conjugateResponse(compromiseMatch, isSelfTarget);
  }

  conjugateResponse(compromiseMatch, isSelfTarget = false) {
    const parsed = compromiseMatch.json();
    const result = parsed[0];

    const replySuffix = compromiseMatch.groups('suffix')?.text().trim() ?? '';

    if (result == null) return '';

    const verbTerm = result.terms[1];
    if (!verbTerm) {
      console.log("DEBUG: Structure détectée mais verbe introuvable.");
      return '';
    }

    const verbText = verbTerm.text.toLowerCase(); 
    
    // Debug: On vérifie ce qu'il cherche
    const verbInfinitive = toInfinitive[verbText];
    
    if (!verbInfinitive) {
      console.log(`DEBUG: ÉCHEC - Le verbe '${verbText}' n'est pas dans toInfinitive.json`);
      return ''; //drop et initialise perroquet (suffixDetector ou basicDetector)
    }

    let conjugated = '';
    const tenseTag = verbTerm.tags.find(t => t.endsWith('Tense')) ?? 'Present';

    const getConjugation = (pronoun) => {
        try {
          const tenseData = conj.findTense(verbInfinitive, tenseTag);
          return tenseData.find(c => c.pronoun === pronoun)?.verb;
        } catch (e) {
          console.error(`DEBUG: Erreur conjugation-fr pour ${verbInfinitive}:`, e);
          return null;
        }
    };

    // Logique d'inversion des pronoms
    const subjectText = result.terms[0].text.toLowerCase();
    
    switch (subjectText) {
      case 'je':
      case "j'":
        conjugated = `tu ${getConjugation('tu')}`;
        break;
      case 'tu':
      case "t'":
        if (isSelfTarget) {
          conjugated = `je ${getConjugation('je')}`;
        } else {
          conjugated = `il ${getConjugation('il')}`;
        }
        break;
      case 'il':
      case 'on':
      case 'ça':
      case 'ca':
        conjugated = `${subjectText} ${getConjugation('il')}`;
        break;
      case 'elle':
        conjugated = `elle ${getConjugation('il')}`;
        break;
      case 'nous':
        conjugated = `nous ${getConjugation('nous')}`;
        break;
      case 'vous':
        conjugated = `on ${getConjugation('il')}`;
        break;
      case 'ils':
        conjugated = `ils ${getConjugation('ils')}`;
        break;
      case 'elles':
        conjugated = `elles ${getConjugation('ils')}`;
        break;
      default:
        console.log(`DEBUG: Pronom '${subjectText}' non géré.`);
        return '';
    }

    if (!conjugated || conjugated.includes('undefined')) {
       console.log(`DEBUG: Échec conjugaison finale.`);
       return '';
    }

    const infinitiveVerb = result.terms.find(t => t.tags.includes('Infinitive'))?.text ?? '';

    return (`${conjugated} ${infinitiveVerb} feur ${replySuffix}${suffixes[Math.floor(Math.random() * suffixes.length)]}`).trim().replaceAll('  ', ' ').replace(' ,', ',');
  }
}