/**
 * AI Reply Generator — Persona-specific responses
 * Tries OpenAI-compatible LLM first (when configured), falls back to
 * keyword-based rules when no API key is available or the API call fails.
 *
 * Environment variables:
 *   LLM_API_KEY   — OpenAI-compatible API key (optional)
 *   LLM_BASE_URL  — API base URL (default: https://api.openai.com/v1)
 *   LLM_MODEL     — Model name (default: gpt-4o-mini)
 */

type Message = { role: string; content: string };

/* ── Persona intro responses & descriptions ── */

const INTRO_RESPONSES: Record<string, string> = {
  nurbuddy:
    "Assalamualaikum! 🌟 I'm NurBuddy, your friendly Islamic lifestyle companion. How can I help you today? Feel free to ask about daily duas, prayer times, or just have a chat about faith and life.",
  alim:
    "Assalamualaikum warahmatullahi wabarakatuh. I am Alim, a student of Islamic knowledge. I draw upon the Qur'an and authentic hadith to provide scholarly insights. How may I assist you in your search for understanding?",
  hakim:
    "Greetings, seeker of wisdom. I am Hakim, and I offer counsel drawn from the wellspring of Islamic tradition and timeless parables. Tell me what weighs upon your heart, and together we shall find clarity.",
  murabbi:
    "Assalamualaikum, dear soul. I am Murabbi, your spiritual mentor. My role is to help you reflect, grow, and draw closer to the Divine. What aspect of your journey shall we explore today?",
  mufti:
    "Assalamualaikum. I am Mufti, and I provide detailed rulings based on the Qur'an, Sunnah, and the established schools of jurisprudence. Please present your question clearly, and I will respond with evidence and reasoning.",
  daie:
    "Assalamualaikum. I am Daie, and my mission is dawah — calling to the beauty of Islam with wisdom and gentle persuasion. Whether you're curious about Islam or seeking comparative insights, I'm here to help.",
};

/* ── LLM Integration ── */

/** Read LLM config from environment variables. */
function getLLMConfig(): {
  apiKey: string;
  baseUrl: string;
  model: string;
} {
  return {
    apiKey: process.env.LLM_API_KEY || "",
    baseUrl: (process.env.LLM_BASE_URL || "https://api.openai.com/v1").replace(
      /\/+$/,
      "",
    ),
    model: process.env.LLM_MODEL || "gpt-4o-mini",
  };
}

/** Build the system prompt for a given persona by combining its intro and description. */
function buildSystemPrompt(personaId: string): string {
  const intro =
    INTRO_RESPONSES[personaId] || INTRO_RESPONSES.nurbuddy;

  // Extended persona descriptions that define tone, style, and scope
  const descriptions: Record<string, string> = {
    nurbuddy:
      "You are NurBuddy, a friendly and approachable Islamic lifestyle companion. Your tone is warm, encouraging, and supportive. You help users with daily duas, prayer times, and general advice about faith and life. Use emojis occasionally and keep the tone cheerful and uplifting.",
    alim:
      "You are Alim, a dedicated student of Islamic knowledge. You draw upon the Qur'an and authentic hadith to provide scholarly insights. Your tone is knowledgeable, precise, and respectful. Cite sources and evidence when possible. When uncertain, acknowledge differing scholarly opinions.",
    hakim:
      "You are Hakim, a wisdom counselor who draws from the wellspring of Islamic tradition and timeless parables. Your tone is reflective, poetic, and profound. Use metaphors, stories, and analogies to convey deeper truths. Encourage the seeker to reflect inward.",
    murabbi:
      "You are Murabbi, a spiritual mentor guiding souls toward reflection and growth. Your tone is gentle, introspective, and nurturing. Help users connect with their faith on a deeper level. Ask reflective questions and encourage self-accountability (muhasabah).",
    mufti:
      "You are Mufti, a scholar who provides detailed rulings (fatawa) based on the Qur'an, Sunnah, and the established schools of Islamic jurisprudence (madhahib). Your tone is formal, thorough, and evidence-based. Structure responses with: evidence, analysis, and conclusion. Always include 'Wallahu a'lam (Allah knows best)' at the end.",
    daie:
      "You are Daie, a caller to Islam (dawah). Your mission is to present the beauty of Islam with wisdom, gentleness, and persuasive reasoning. Your tone is welcoming, informative, and respectful of other faiths. Focus on common ground while explaining Islamic teachings with clarity and compassion.",
  };

  const desc = descriptions[personaId] || descriptions.nurbuddy;
  return `${intro}\n\n${desc}`;
}

/**
 * Call an OpenAI-compatible LLM chat completion endpoint.
 * Returns the response text on success, or `null` if the call fails
 * (no API key, network error, non-2xx status, malformed response).
 */
async function callLLM(
  personaId: string,
  userMessage: string,
  history: Message[],
): Promise<string | null> {
  const { apiKey, baseUrl, model } = getLLMConfig();

  // No key configured — skip LLM entirely
  if (!apiKey) return null;

  try {
    const systemPrompt = buildSystemPrompt(personaId);

    // Build messages array: system prompt + last 10 history entries + current user message
    const messages: { role: string; content: string }[] = [
      { role: "system", content: systemPrompt },
      ...history.slice(-10).map((m) => ({
        role: m.role === "assistant" ? "assistant" : "user",
        content: m.content,
      })),
      { role: "user", content: userMessage },
    ];

    const response = await fetch(`${baseUrl}/chat/completions`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${apiKey}`,
      },
      body: JSON.stringify({
        model,
        messages,
        max_tokens: 1024,
        temperature: 0.7,
      }),
    });

    if (!response.ok) {
      console.error(
        `[ai-server] LLM API error [${response.status}]: ${response.statusText}`,
      );
      return null; // Fall back to keyword rules
    }

    const data = await response.json();

    // Validate response structure
    const content = data?.choices?.[0]?.message?.content;
    if (!content || typeof content !== "string") {
      console.error("[ai-server] LLM returned unexpected response format");
      return null;
    }

    return content.trim();
  } catch (error) {
    console.error("[ai-server] LLM call failed:", error);
    return null; // Fall back to keyword rules
  }
}

/* ── Utility helpers ── */

function getRandomItem<T>(arr: T[]): T {
  return arr[Math.floor(Math.random() * arr.length)];
}

function getLastMessages(
  history: Message[],
  userMessage: string,
  count: number = 4,
): string {
  const recent = history.slice(-count);
  if (recent.length === 0) return `User asks: "${userMessage}"`;
  const ctx = recent
    .map((m) => `${m.role === "user" ? "User" : "Assistant"}: ${m.content}`)
    .join("\n");
  return `${ctx}\nUser: "${userMessage}"`;
}

/* ── Persona response generators (keyword-based fallbacks) ── */

function nurbuddyReply(userMessage: string, context: string): string {
  const lower = userMessage.toLowerCase();

  if (
    lower.includes("assalamu") ||
    lower.includes("salam") ||
    lower.includes("hello") ||
    lower.includes("hi")
  )
    return "Waalaikumsalam warahmatullahi wabarakatuh! 😊 So happy to chat with you today. What's on your mind?";

  if (
    lower.includes("dua") ||
    lower.includes("prayer") ||
    lower.includes("supplication")
  )
    return "Alhamdulillah, making dua is a beautiful act of worship! Here's a simple yet powerful dua for you:\n\n**رَبَّنَا آتِنَا فِي الدُّنْيَا حَسَنَةً وَفِي الْآخِرَةِ حَسَنَةً وَقِنَا عَذَابَ النَّارِ**\n\n\"Our Lord, give us good in this world and good in the Hereafter, and protect us from the punishment of the Fire.\" (Quran 2:201)\n\nSay it with sincerity and watch how Allah transforms your life! 🌿";

  if (
    lower.includes("stress") ||
    lower.includes("anxious") ||
    lower.includes("worried") ||
    lower.includes("sad")
  )
    return "I hear you, and it's okay to feel this way. Remember what Allah says: **\"Verily, with hardship comes ease\"** (Quran 94:6). \n\nHere are a few things that might help:\n• Take a deep breath and recite *SubhanAllah* 33 times\n• Go for wudu (ablution) — it's surprisingly calming!\n• Talk to someone you trust\n\nYou're not alone, and this too shall pass, insha'Allah. 💛";

  if (lower.includes("thank"))
    return "You're most welcome! 😊 It's always a pleasure to help. Remember, the Prophet ﷺ said: \"He who does not thank people, does not thank Allah.\" So JazakAllah khair for your kind words!";

  return `That's a great question! Here's my friendly advice:\n\n${getRandomItem([
    "In Islam, every small action can become an act of worship if done with the right intention (niyyah). So even your daily tasks can earn you rewards, insha'Allah!",
    "A good rule of thumb is to ask yourself: 'Would this please Allah?' If the answer is yes, go for it with full confidence!",
    "The Prophet ﷺ taught us to seek knowledge from the cradle to the grave. Never stop learning about your faith — it's a journey, not a destination!",
    "Remember that Allah's mercy encompasses everything. No matter what you're going through, His door of repentance is always open. 🌅",
  ])}\n\nIs there anything else I can help you with?`;
}

function alimReply(userMessage: string, context: string): string {
  const lower = userMessage.toLowerCase();

  if (lower.includes("salah") || lower.includes("prayer"))
    return "Regarding the obligation of salah, Allah commands in Surah Al-Baqarah (2:43): **\"And establish prayer and give zakah and bow with those who bow [in worship and obedience].\"**\n\nThe five daily prayers are a fundamental pillar of Islam. The Prophet ﷺ said: \"The covenant between us and them is prayer, so whoever abandons it has committed disbelief\" (Sunan al-Tirmidhi).\n\nIf you have questions about specific rulings related to prayer (like combining prayers during travel or the conditions of valid wudu), please specify and I'll provide detailed evidence.";

  if (lower.includes("zakat") || lower.includes("charity"))
    return "Zakat is one of the five pillars of Islam, mentioned alongside prayer in numerous Qur'anic verses. Allah says: **\"And establish prayer and give zakah, and whatever good you put forward for yourselves — you will find it with Allah\"** (Quran 2:110).\n\nThe general ruling is that 2.5% of one's accumulated wealth (above the nisab threshold) should be given annually to the eight categories specified in Surah At-Tawbah (9:60). The nisab is equivalent to the value of 85 grams of gold or 595 grams of silver.\n\nWould you like me to elaborate on any specific aspect of zakat calculation or distribution?";

  if (
    lower.includes("halal") ||
    lower.includes("haram") ||
    lower.includes("permissible")
  )
    return "The general principle in Islamic jurisprudence is that all things are permissible (halal) unless explicitly prohibited (haram) in the Qur'an or authentic Sunnah. Allah says: **\"O mankind, eat from whatever is on earth [that is] lawful and good\"** (Quran 2:168).\n\nThe categories of haram include: intoxicants, pork and its by-products, carrion, blood, and anything dedicated to other than Allah. For matters where clear texts are absent, scholars use ijtihad (independent reasoning) based on the maqasid (objectives) of Islamic law.\n\nCould you specify which area you're asking about so I can provide a more targeted answer with proper evidence?";

  return `In the name of Allah, the Most Gracious, the Most Merciful.\n\nThank you for your inquiry. Let me draw upon the sources of Islamic knowledge to address this:\n\n${getRandomItem([
    "The Qur'an says: **\"And We have certainly made the Qur'an easy to remember. So is there any who will remember?\"** (Quran 54:17). This reflects the accessibility of divine guidance for those who seek it.",
    "Imam Al-Shafi'i (may Allah have mercy on him) said: \"Knowledge is not what is memorized, but what benefits.\" The ultimate purpose of knowledge is action and taqwa (God-consciousness).",
    "The Prophet ﷺ said: **\"Whoever Allah wishes good for, He grants them understanding of the religion\"** (Sahih al-Bukhari). May Allah grant us all beneficial knowledge.",
    "A principle established by the scholars is that **\"certainty is not removed by doubt\"** — a foundational maxim in Islamic jurisprudence (Qawa'id Fiqhiyyah).",
  ])}\n\nIs there a specific scholarly viewpoint or madhab you'd like me to elaborate on?`;
}

function hakimReply(userMessage: string, context: string): string {
  const lower = userMessage.toLowerCase();

  if (
    lower.includes("decision") ||
    lower.includes("choice") ||
    lower.includes("confused") ||
    lower.includes("dilemma")
  )
    return "A difficult decision, you say? Let me share a parable:\n\nA traveler once came to a crossroads. One path was smooth but led to a barren land; the other was rocky but led to a lush garden. He asked a wise man which to take. The wise man replied: **\"Judge the path not by its comfort, but by its destination.\"**\n\nIn making your choice, consider:\n1️⃣ **Istikhara** — Pray the Salat al-Istikhara and ask Allah for guidance\n2️⃣ **Consultation (Shura)** — Speak with trusted, knowledgeable people\n3️⃣ **Consequences** — Weigh the outcomes against your values and deen\n\nWhat does your heart lean toward after seeking Allah's guidance?";

  if (
    lower.includes("forgive") ||
    lower.includes("anger") ||
    lower.includes("hurt") ||
    lower.includes("grudge")
  )
    return "Ah, the weight of carrying a grudge — it is like drinking poison and expecting the other person to suffer.\n\nAllah reminds us: **\"And let them pardon and overlook. Would you not like that Allah should forgive you? And Allah is Forgiving and Merciful\"** (Quran 24:22).\n\nThe Prophet ﷺ, despite being wronged in countless ways, was the most forgiving of people. When he conquered Mecca, he asked the Quraysh: \"What do you think I will do to you?\" They replied: \"You are a noble brother, son of a noble brother.\" He said: **\"Go, for you are free.\"**\n\nForgiveness is not weakness — it is the strength of a soul that trusts Allah's justice. 🕊️";

  if (
    lower.includes("patience") ||
    lower.includes("sabr") ||
    lower.includes("waiting") ||
    lower.includes("trial")
  )
    return "Patience (sabr) is indeed a light. The trials you face are not punishments — they are opportunities for elevation. \n\nThere's a beautiful story of Prophet Ayyub (Job, peace be upon him), who lost his wealth, children, and health, yet never stopped praising Allah. When asked why, he said: **\"Allah gave, and Allah has taken. Blessed be Allah in both.\"**\n\nAnd what was his reward? Allah says: **\"And We gave him back his family and the like thereof with them — a mercy from Us and a reminder for those who worship\"** (Quran 38:43).\n\nYour patience is not in vain. Every moment of endurance is recorded, and the reward is immense. 🌱";

  return `A profound question. Let me reflect with you:\n\n${getRandomItem([
    "Life is like a river — it flows whether we resist or not. The wise one learns to navigate with the current of divine will, not against it.",
    "There is a Persian saying: 'This too shall pass.' Both joy and sorrow are visitors. Welcome them with grace, for neither stays forever.",
    "The Prophet ﷺ said: **\"How remarkable is the affair of the believer! All of it is good.\"** If you can find the hidden good in your present situation, you've already won half the battle.",
    "Often we search far and wide for answers, when the truth was always within us — like the fish searching for the ocean.",
  ])}\n\nWhat resonates most with your heart right now?`;
}

function murabbiReply(userMessage: string, context: string): string {
  const lower = userMessage.toLowerCase();

  if (
    lower.includes("iman") ||
    lower.includes("faith") ||
    lower.includes("spiritual") ||
    lower.includes("connection")
  )
    return "Masha'Allah, your concern for your iman is itself a sign of its presence. The fact that you're asking tells me your heart is alive. 🌙\n\nLet me ask you some reflective questions:\n• When did you last feel truly connected in your salah?\n• What aspect of Allah's names (Asma'ul Husna) resonates most with you right now?\n• If your iman were a garden, what would it need — water, sunlight, or perhaps the removal of weeds?\n\nTake a moment to sit with these questions. Remember, iman fluctuates — that's natural. The Prophet ﷺ said: **\"Renew your faith!\"** They asked: \"How do we renew it?\" He said: **\"Say La ilaha illallah\"** (Ahmad).";

  if (
    lower.includes("repent") ||
    lower.includes("taubah") ||
    lower.includes("sin") ||
    lower.includes("regret")
  )
    return "Dear soul, let me tell you something beautiful: the fact that you feel remorse is itself a gift from Allah. It means your heart is not sealed, and the door of repentance is wide open for you.\n\nAllah says: **\"Say, O My servants who have transgressed against themselves, do not despair of the mercy of Allah. Indeed, Allah forgives all sins. Indeed, it is He who is the Forgiving, the Merciful\"** (Quran 39:53).\n\nNotice He says \"O My servants\" — even when we sin, He still claims us as His own. That's the depth of His love. ❤️\n\nFor sincere repentance (tawbah an-nasuh), reflect on these three steps:\n1️⃣ Stop the sin immediately\n2️⃣ Feel genuine regret\n3️⃣ Resolve never to return to it\n\nAnd if your sin involves another person's rights, make amends with them too.\n\nYou are not defined by your worst moment. You are defined by your return to Him.";

  if (
    lower.includes("purpose") ||
    lower.includes("meaning") ||
    lower.includes("why") ||
    lower.includes("life")
  )
    return "The question of purpose is perhaps the most profound question a soul can ask. And you're asking it — that's beautiful.\n\nAllah gives us the answer directly: **\"And I did not create the jinn and mankind except to worship Me\"** (Quran 51:56).\n\nBut 'worship' here (ibadah) means far more than rituals. It means living a life of consciousness of Allah in every moment — your work, your relationships, your kindness, even your sleep can be worship with the right intention.\n\nLet me ask you: What makes you feel most alive and most at peace? Often, the answer to that question is connected to your purpose. When your natural talents meet the world's needs, with Allah at the center — that's your purpose in action. 🌟";

  return `Thank you for trusting me with your reflections. Let me offer you some spiritual nourishment:\n\n${getRandomItem([
    "Take a moment right now. Close your eyes, take three deep breaths, and say *Alhamdulillah* for each breath. Gratitude is the key that unlocks more blessings.",
    "The Prophet ﷺ said: **\"The most beloved of deeds to Allah are those that are most consistent, even if they are small.\"** Don't underestimate the power of small, consistent good deeds.",
    "Your relationship with Allah is like a mirror — when you turn toward Him, He turns toward you. When you take one step toward Him, He comes running to you (as mentioned in hadith qudsi).",
    "Every trial is a teacher. Every difficulty carries a divine whisper. The question isn't 'Why me?' but 'What is this teaching me?'",
  ])}\n\nHow does this land on your heart?`;
}

function muftiReply(userMessage: string, context: string): string {
  const lower = userMessage.toLowerCase();

  if (
    lower.includes("interest") ||
    lower.includes("riba") ||
    lower.includes("bank") ||
    lower.includes("loan")
  )
    return "**Issue:** Riba (interest) in financial transactions\n**Ruling:** Riba is categorically prohibited in Islam.\n\n**Evidence:**\n1. Allah says: **\"Those who consume interest will stand on the Day of Resurrection like one driven mad by Satan's touch. That is because they say, 'Trade is like interest.' But Allah has permitted trade and forbidden interest\"** (Quran 2:275).\n\n2. The Prophet ﷺ cursed the one who consumes riba, the one who pays it, the one who writes it, and the one who witnesses it, saying: **\"They are all the same\"** (Sahih Muslim).\n\n**Application:** All forms of conventional interest-based loans, credit cards with interest, and savings accounts that pay interest fall under this prohibition. Muslims should seek Shariah-compliant alternatives such as:\n• Murabahah (cost-plus financing)\n• Musharakah (profit-sharing)\n• Ijara (leasing)\n\n**Note:** In cases of dire necessity (darura), scholars may permit exceptions under strict conditions. Please consult a local scholar for your specific situation.";

  if (
    lower.includes("prayer") ||
    lower.includes("salah") ||
    lower.includes("fajr") ||
    lower.includes("qada") ||
    lower.includes("missed")
  )
    return "**Issue:** Making up missed prayers (Qada' al-Salah)\n\n**Evidence:** The majority of scholars (Hanafi, Shafi'i, Maliki) hold that making up missed obligatory prayers is compulsory (wajib). The Prophet ﷺ said: **\"Whoever forgets a prayer, let him pray it when he remembers it. There is no expiation for it except that\"** (Sahih al-Bukhari).\n\n**Ruling:**\n- **Intentionally missed prayers:** The predominant view (Hanbali, some Malikis) is that one must repent and make them up. Some scholars (particularly the Hanbali school) hold that intentional abandonment of prayer is major kufr — thus one must first repent and renew their shahadah.\n- **Unintentionally missed** (forgetfulness, sleep): Make up as soon as remembered.\n\n**Recommended sequence:** Make up missed prayers alongside your current ones, prioritizing the current prayer time but making up the missed ones as soon as possible.\n\nWallahu a'lam (Allah knows best). I recommend consulting a local scholar of your madhab for personalized guidance.";

  if (
    lower.includes("marriage") ||
    lower.includes("nikah") ||
    lower.includes("divorce") ||
    lower.includes("talaq")
  )
    return "**Issue:** Rules of marriage and divorce in Islam\n\nMarriage (nikah) is a sacred contract (mithaq ghalidh) in Islam. Allah describes it as: **\"And He placed between you affection and mercy\"** (Quran 30:21).\n\n**Essential conditions for a valid nikah:**\n1. Mutual consent of both parties (the bride's consent, through her wali/guardian)\n2. Mahr (dower) — a gift from the husband to the wife\n3. Two upright Muslim witnesses\n4. The marriage contract (ijab and qabul)\n\n**Regarding divorce (talaq):**\n- It is the most disliked permissible act (abghad al-halal ila Allah)\n- A triple talaq uttered in one sitting: the majority view is that this counts as three divorces and the marriage is irrevocably dissolved (the Hanbali position differs, counting it as one)\n- After the first or second talaq, there is a waiting period (iddah) of three menstrual cycles, during which reconciliation is encouraged\n\nPlease provide more specifics about your situation for a detailed ruling. Wallahu a'lam.";

  return `**Request for a Ruling (Ifta')**\n\nThank you for your question. I will address it based on the primary sources of Islamic law and the established methodologies of the four Sunni schools of thought.\n\n**Context:** ${userMessage}\n\n**Analysis:**\n${getRandomItem([
    "The general principle (al-asl) in this matter is permissibility (ibahah), as there is no clear text prohibiting it. Allah says: **\"He has explained to you what He has made unlawful for you\"** (Quran 6:119).",
    "The legal maxim states: 'Harm is to be eliminated' (al-darar yuzal). Any action causing significant harm to oneself or others would be impermissible based on this principle.\n\n**Evidence:** The Prophet ﷺ said: **\"There should be neither harming nor reciprocating harm\"** (Ibn Majah).",
    "The objectives of Islamic law (Maqasid al-Shariah) aim to preserve five essentials: faith, life, intellect, lineage, and property. Any ruling on this matter should be evaluated against these higher objectives.",
  ])}\n\n**Conclusion:**\nTo provide a definitive ruling, I need to consider the specifics more carefully. Could you please clarify:\n1. Your madhab (school of thought)?\n2. Any relevant circumstances?\n\nWallahu a'lam (Allah knows best).`;
}

function daieReply(userMessage: string, context: string): string {
  const lower = userMessage.toLowerCase();

  if (
    lower.includes("jesus") ||
    lower.includes("isa") ||
    lower.includes("christian") ||
    lower.includes("bible")
  )
    return "This is a beautiful area of discussion! 🌿\n\nIn Islam, Prophet Isa (Jesus, peace be upon him) holds a very special position. We love and honor him as one of the greatest messengers of Allah. Here's what Muslims believe:\n\n• He was born miraculously to Maryam (Mary) without a father — **\"And We made the son of Mary and his mother a sign\"** (Quran 23:50)\n• He spoke as a baby in the cradle, defending his mother's honor\n• He performed miracles — healing the blind and leper, raising the dead — all by Allah's permission\n• He preached the worship of One God (Tawheed)\n• He was not crucified but was raised to the heavens (Quran 4:157-158)\n• He will return before the Day of Judgment\n\nThe key difference is that Islam upholds the absolute oneness of God (Tawheed) and considers it the highest sin to associate partners with Allah. Muslims believe Isa was a human prophet, not divine.\n\nWould you like to explore more similarities or differences between Islamic and Christian teachings? ☪️✝️";

  if (
    lower.includes("hindu") ||
    lower.includes("buddhist") ||
    lower.includes("other religion") ||
    lower.includes("jewish") ||
    lower.includes("judaism")
  )
    return "Assalamualaikum. Let me approach this with the wisdom that dawah requires — gentleness and respect. Allah commands: **\"Invite to the way of your Lord with wisdom and good instruction, and argue with them in a way that is best\"** (Quran 16:125).\n\nEvery faith tradition contains elements of truth, and Islam affirms that Allah sent messengers to every nation. The Qur'an says: **\"And We certainly sent into every nation a messenger, [saying], 'Worship Allah and avoid false gods'\"** (Quran 16:36).\n\nWhat makes Islam unique is its:\n• **Finality of revelation** — The Qur'an, preserved in its original language for over 1,400 years\n• **Comprehensive guidance** — Covering spirituality, law, economics, and governance\n• **Universal message** — For all of humanity, not just one people or time\n\nI'd be happy to discuss specific beliefs or answer questions you have. The goal is understanding, not winning arguments. 🤝";

  if (
    lower.includes("convert") ||
    lower.includes("revert") ||
    lower.includes("become muslim") ||
    lower.includes("shahadah")
  )
    return "Masha'Allah! Your interest in Islam fills my heart with joy. 🌟\n\nLet me share what embracing Islam involves:\n\n**The Shahadah (Declaration of Faith):**\n**\"Ashhadu an la ilaha illallah, wa ashhadu anna Muhammadan rasulullah\"**\n(I bear witness that there is no god worthy of worship except Allah, and I bear witness that Muhammad is the Messenger of Allah)\n\nThat's it — utter these words with sincerity and understanding, and you become a Muslim. Everything else (prayer, fasting, etc.) builds on this foundation.\n\n**What changes?**\n• Your past sins are forgiven — you start fresh like a newborn\n• Your relationship with God becomes direct — no intermediaries needed\n• You join the global family of 1.8 billion Muslims\n\nI encourage you to:\n1️⃣ Visit a local mosque — the community will welcome you warmly\n2️⃣ Get a copy of the Qur'an with translation\n3️⃣ Learn how to pray (salat) at your own pace\n\nWould you like to know more about what life as a Muslim looks like day-to-day? 🕌";

  return `Assalamualaikum! Thank you for your question. Let me respond with the spirit of dawah — inviting through wisdom and beauty.\n\n${getRandomItem([
    "The Qur'an challenges us: **\"Do they not reflect upon the Qur'an, or are there locks upon their hearts?\"** (Quran 47:24). Reflection (tadabbur) is key to understanding divine guidance.",
    "One of the most beautiful aspects of Islam is its balance. It teaches us to be spiritual without being monastic, worldly without being materialistic. You can be a successful professional and a devoted servant of Allah.",
    "The Prophet ﷺ said: **\"The best of you are those who are best to their families, and I am the best of you to my family\"** (Sunan al-Tirmidhi). This shows how Islam elevates kindness and family values.",
    "Islam doesn't ask you to abandon the world — it teaches you to engage with it mindfully. Every lawful action, done with the right intention, becomes worship. Imagine that!",
  ])}\n\nIs there a particular aspect of Islam you'd like to explore further? I'm here to help with patience and clarity. ☪️`;
}

/* ── Main entry point ── */

/**
 * Generate an AI reply for the given persona and conversation context.
 *
 * Tries the LLM first if LLM_API_KEY is set. Falls back to the existing
 * keyword-based persona reply functions when the LLM is unavailable or
 * the API call fails.
 *
 * @param personaId - One of: nurbuddy, alim, hakim, murabbi, mufti, daie
 * @param userMessage - The user's current message text
 * @param history - Array of previous messages for conversational context
 * @returns The generated reply text
 */
export async function generateAIReply(
  personaId: string,
  userMessage: string,
  history: { role: string; content: string }[],
): Promise<string> {
  // 1. Attempt LLM-first response (only if API key is configured)
  const llmReply = await callLLM(personaId, userMessage, history);
  if (llmReply !== null) return llmReply;

  // 2. LLM unavailable or failed — fall back to keyword-based rules
  const context = getLastMessages(history, userMessage);

  if (history.length === 0) {
    return INTRO_RESPONSES[personaId] || INTRO_RESPONSES.nurbuddy;
  }

  switch (personaId) {
    case "nurbuddy":
      return nurbuddyReply(userMessage, context);
    case "alim":
      return alimReply(userMessage, context);
    case "hakim":
      return hakimReply(userMessage, context);
    case "murabbi":
      return murabbiReply(userMessage, context);
    case "mufti":
      return muftiReply(userMessage, context);
    case "daie":
      return daieReply(userMessage, context);
    default:
      return nurbuddyReply(userMessage, context);
  }
}
