/**
 * AI বন্ধু "তারা" — a safe, child-friendly chat tutor.
 * Moderates input and output, keeps replies short, and falls back to a warm
 * rule-based responder in DEMO_MODE / without an AI key.
 * Server-only.
 */
import { canUseAi } from '../env';
import type { AgeBand } from '../types';
import { callModel } from './provider';
import { buddySystemPrompt } from './prompts';
import { moderateInput, moderateOutput } from './moderation';

export interface ChatTurn {
  role: 'child' | 'ai';
  content: string;
}

export interface BuddyReply {
  reply: string;
  flagged: boolean; // input was deflected / unsafe
}

const GREETINGS = ['হাই', 'হ্যালো', 'হেই', 'hi', 'hello', 'আসসালাম', 'নমস্কার'];
const THANKS = ['ধন্যবাদ', 'thanks', 'thank', 'থ্যাংক'];

/** Warm, safe canned reply for demo mode / no AI key. */
function demoReply(message: string): string {
  const t = message.toLowerCase();
  if (GREETINGS.some((g) => t.includes(g))) {
    return 'হ্যালো বন্ধু! 🌟 আমি তারা। তুমি কেমন আছো? চলো আজ মজার কিছু শিখি!';
  }
  if (THANKS.some((g) => t.includes(g))) {
    return 'তোমাকেও ধন্যবাদ! 😊 তুমি খুব ভালো করছ।';
  }
  if (t.includes('নাম')) {
    return 'আমার নাম তারা! আমি তোমার শেখার বন্ধু। ✨';
  }
  if (t.includes('গল্প')) {
    return 'গল্প শুনতে চাও? "গল্পকার" খেলাটায় গিয়ে আমাকে একটা বিষয় বলো, আমি গল্প বানিয়ে দেব! 📖';
  }
  if (t.includes('?') || t.includes('কেন') || t.includes('কি') || t.includes('কী')) {
    return 'দারুণ প্রশ্ন! 😊 এটা নিয়ে আরও জানতে চাইলে বড় কাউকেও জিজ্ঞেস করতে পারো। চলো একসাথে শিখি!';
  }
  return 'বাহ, মজার তো! 🌟 তুমি কি বর্ণমালা, গণিত, নাকি বিজ্ঞান নিয়ে কিছু শিখতে চাও?';
}

export async function generateReply(
  band: AgeBand,
  history: ChatTurn[],
  message: string,
): Promise<BuddyReply> {
  const clean = (message || '').trim().slice(0, 500);
  if (!clean) return { reply: 'কিছু একটা লিখো তো, বন্ধু! 😊', flagged: false };

  const mod = moderateInput(clean);
  if (!mod.safe) {
    return { reply: mod.message ?? 'চলো অন্য কিছু নিয়ে কথা বলি! 😊', flagged: true };
  }

  if (!canUseAi()) {
    return { reply: demoReply(clean), flagged: false };
  }

  try {
    // Compact recent history into the prompt for lightweight context.
    const recent = history.slice(-6);
    const convo = recent
      .map((t) => `${t.role === 'child' ? 'বাচ্চা' : 'তারা'}: ${t.content}`)
      .join('\n');
    const prompt = `${convo ? convo + '\n' : ''}বাচ্চা: ${clean}\nতারা:`;
    const text = await callModel(prompt, {
      system: buddySystemPrompt(band),
      maxTokens: 300,
      temperature: 0.8,
    });
    const out = moderateOutput(text.trim());
    if (out.safe && out.message) return { reply: out.message, flagged: false };
    return { reply: 'দুঃখিত, চলো অন্য মজার কিছু শিখি! ✨', flagged: true };
  } catch (err) {
    console.error('[ai/buddy] failed, using demo reply:', err);
    return { reply: demoReply(clean), flagged: false };
  }
}
