/**
 * Qatari Dialect Translation Service
 * ===================================
 * Translates English text to authentic Qatari Arabic dialect.
 *
 * Translation priority:
 *   1. Pre-computed common phrases (instant, 0ms)
 *   2. LRU response cache (2000 entries)
 *   3. Anthropic API (claude-haiku-4-5 for speed)
 *
 * Extracted from standalone qatari_api.ts into an embedded service module.
 */

import Anthropic from '@anthropic-ai/sdk';
import * as fs from 'fs';
import * as path from 'path';
import * as crypto from 'crypto';
import { logger } from '@/lib/logger';

// ============================================
// INTERFACES
// ============================================

export interface VocabularyEntry {
  word: string;
  transliteration: string;
  meaning_en: string;
  sentence_simple: string;
  sentence_qatari: string;
  usage: string;
}

export interface TranslationResult {
  translation: string;
  source: 'common_phrases' | 'cache' | 'api';
  cached: boolean;
}

// ============================================
// PRE-COMPUTED COMMON PHRASES
// ============================================

const COMMON_PHRASES: Record<string, string> = {
  // === GREETINGS & BASICS ===
  'hello': 'هلا',
  'hi': 'هلا',
  'hey': 'هلا',
  'hi there': 'هلا والله',
  'hello there': 'هلا والله',
  'good morning': 'صباح الخير',
  'good afternoon': 'مساء الخير',
  'good evening': 'مساء الخير',
  'good night': 'تصبح على خير',
  'how are you': 'شلونك؟',
  'how are you?': 'شلونك؟',
  'how are you doing': 'شلونك؟ شخبارك؟',
  'how are you doing?': 'شلونك؟ شخبارك؟',
  "what's up": 'شخبارك؟',
  "what's up?": 'شخبارك؟',
  "i'm fine": 'أنا زين',
  'i am fine': 'أنا زين',
  "i'm good": 'أنا زين',
  "i'm doing well": 'أنا زين الحمدلله',
  "i'm great": 'أنا وايد زين',
  'not bad': 'مو سيئ',
  'goodbye': 'مع السلامة',
  'bye': 'مع السلامة',
  'bye bye': 'مع السلامة',
  'see you': 'أشوفك',
  'see you later': 'أشوفك بعدين',
  'see you tomorrow': 'أشوفك باجر',
  'see you soon': 'أشوفك قريب',
  'take care': 'الله يحفظك',
  'have a nice day': 'يومك سعيد',

  // === BASIC RESPONSES ===
  'yes': 'ايه',
  'no': 'لا',
  'ok': 'تمام',
  'okay': 'تمام',
  'alright': 'تمام',
  'good': 'زين',
  'very good': 'وايد زين',
  'excellent': 'ممتاز',
  'perfect': 'تمام',
  'of course': 'طبعاً',
  'sure': 'أكيد',
  'maybe': 'يمكن',
  'i think so': 'أعتقد ايه',
  "i don't think so": 'ما أعتقد',
  'i agree': 'موافق',
  'i disagree': 'ما أوافق',

  // === POLITENESS ===
  'thank you': 'مشكور',
  'thanks': 'مشكور',
  'thanks a lot': 'مشكور وايد',
  'thank you very much': 'مشكور وايد',
  'thank you so much': 'الله يعطيك العافية',
  "you're welcome": 'العفو',
  'no problem': 'ما في مشكلة',
  "don't mention it": 'ما سوينا شي',
  'please': 'لو سمحت',
  'sorry': 'آسف',
  "i'm sorry": 'أنا آسف',
  'excuse me': 'لو سمحت',
  'pardon me': 'سامحني',
  'forgive me': 'سامحني',

  // === QUESTIONS ===
  'what': 'شنو',
  'what?': 'شنو؟',
  'what is this': 'شنو هذا؟',
  'what is this?': 'شنو هذا؟',
  'what is that': 'شنو ذاك؟',
  'what happened': 'شنو صار؟',
  'what happened?': 'شنو صار؟',
  'what do you mean': 'شنو تقصد؟',
  'what do you mean?': 'شنو تقصد؟',
  'what time is it': 'الساعة جم؟',
  'what time is it?': 'الساعة جم؟',
  'where': 'وين',
  'where?': 'وين؟',
  'where is it': 'وين هو؟',
  'where is it?': 'وين هو؟',
  'where are you': 'وينك؟',
  'where are you?': 'وينك؟',
  'where are you going': 'وين رايح؟',
  'where are you going?': 'وين رايح؟',
  'where are you from': 'من وين أنت؟',
  'where are you from?': 'من وين أنت؟',
  'why': 'ليش',
  'why?': 'ليش؟',
  'why not': 'ليش لا؟',
  'why not?': 'ليش لا؟',
  'when': 'متى',
  'when?': 'متى؟',
  'when will you come': 'متى بتيي؟',
  'when will you come?': 'متى بتيي؟',
  'how': 'شلون',
  'how?': 'شلون؟',
  'how much': 'بجم',
  'how much?': 'بجم؟',
  'how much is this': 'بجم هذا؟',
  'how much is this?': 'بجم هذا؟',
  'how much does it cost': 'بجم السعر؟',
  'how much does it cost?': 'بجم السعر؟',
  'how many': 'جم',
  'how many?': 'جم؟',
  'how long': 'جم يوم؟',
  'how long?': 'جم يوم؟',
  'who': 'منو',
  'who?': 'منو؟',
  'who is this': 'منو هذا؟',
  'who is this?': 'منو هذا؟',
  'who are you': 'منو أنت؟',
  'who are you?': 'منو أنت؟',
  "what's your name": 'شنو اسمك؟',
  "what's your name?": 'شنو اسمك؟',
  'what is your name': 'شنو اسمك؟',
  'how old are you': 'جم عمرك؟',
  'how old are you?': 'جم عمرك؟',

  // === WANTS & NEEDS ===
  'i want': 'أبي',
  "i don't want": 'ما أبي',
  'i need': 'أحتاج',
  'i need help': 'أبي مساعدة',
  'i need your help': 'أبي مساعدتك',
  'can you help me': 'تقدر تساعدني؟',
  'can you help me?': 'تقدر تساعدني؟',
  'i want to go': 'أبي أروح',
  'i want to eat': 'أبي آكل',
  'i want to sleep': 'أبي أنام',
  'i want to buy': 'أبي أشتري',
  'i want water': 'أبي ماي',
  'i want coffee': 'أبي قهوة',
  'i want tea': 'أبي شاي',
  'i want food': 'أبي أكل',
  'what do you want': 'شنو تبي؟',
  'what do you want?': 'شنو تبي؟',
  'what would you like': 'شنو تبي؟',
  'what would you like?': 'شنو تبي؟',

  // === STATES & FEELINGS ===
  "i'm hungry": 'أنا يوعان',
  "i'm thirsty": 'أنا عطشان',
  "i'm tired": 'أنا تعبان',
  "i'm sleepy": 'أنا نعسان',
  "i'm sick": 'أنا مريض',
  "i'm busy": 'أنا مشغول',
  "i'm free": 'أنا فاضي',
  "i'm late": 'أنا متأخر',
  "i'm lost": 'أنا ضايع',
  "i'm happy": 'أنا مبسوط',
  "i'm sad": 'أنا زعلان',
  "i'm angry": 'أنا معصب',
  "i'm bored": 'أنا ملان',
  "i'm cold": 'أنا بردان',
  "i'm hot": 'أنا حران',
  'are you okay': 'أنت زين؟',
  'are you okay?': 'أنت زين؟',
  'are you sure': 'أنت متأكد؟',
  'are you sure?': 'أنت متأكد؟',
  'are you ready': 'أنت جاهز؟',
  'are you ready?': 'أنت جاهز؟',

  // === UNDERSTANDING ===
  'i understand': 'فاهم',
  "i don't understand": 'ما فاهم',
  "i didn't understand": 'ما فهمت',
  'do you understand': 'فاهم؟',
  'do you understand?': 'فاهم؟',
  'can you repeat that': 'تقدر تعيد؟',
  'can you repeat that?': 'تقدر تعيد؟',
  'say it again': 'قولها مرة ثانية',
  'speak slowly': 'تكلم على مهلك',
  "i don't know": 'ما أدري',
  "i don't remember": 'ما أتذكر',
  'i forgot': 'نسيت',

  // === ACTIONS & COMMANDS ===
  'wait': 'استنى',
  'wait a moment': 'استنى شوي',
  'wait a minute': 'استنى دقيقة',
  'hurry': 'بسرعة',
  'hurry up': 'بسرعة',
  'slowly': 'على مهلك',
  'come': 'تعال',
  'come here': 'تعال هني',
  'go': 'روح',
  'go away': 'روح بعيد',
  "let's go": 'يالله',
  "let's go now": 'يالله الحين',
  'sit down': 'اقعد',
  'stand up': 'قوم',
  'stop': 'وقف',
  'look': 'شوف',
  'look at this': 'شوف هذا',
  'listen': 'اسمع',
  'listen to me': 'اسمعني',
  'give me': 'عطني',
  'show me': 'ورني',
  'tell me': 'قولي',
  'help me': 'ساعدني',
  'call me': 'كلمني',
  'done': 'خلاص',
  'finished': 'خلاص',
  "it's done": 'خلاص انتهى',
  "i'm done": 'أنا خلصت',
  'now': 'الحين',
  'later': 'بعدين',
  'tomorrow': 'باجر',
  'yesterday': 'أمس',

  // === RESTAURANT & FOOD ===
  'i want to order': 'أبي أطلب',
  'can i have the menu': 'ممكن المنيو؟',
  'can i have the menu?': 'ممكن المنيو؟',
  'what do you recommend': 'شنو تنصح فيه؟',
  'what do you recommend?': 'شنو تنصح فيه؟',
  "i'll have this": 'أبي هذا',
  'the bill please': 'الحساب لو سمحت',
  'can i have the bill': 'ممكن الحساب؟',
  'can i have the bill?': 'ممكن الحساب؟',
  'is this spicy': 'هذا حار؟',
  'is this spicy?': 'هذا حار؟',
  'not spicy please': 'بدون حار لو سمحت',
  'the food is delicious': 'الأكل لذيذ',
  "it's delicious": 'لذيذ',
  "i'm full": 'شبعت',
  'more water please': 'ماي زيادة لو سمحت',
  'can i have more': 'ممكن زيادة؟',
  'can i have more?': 'ممكن زيادة؟',

  // === SHOPPING ===
  "i'm just looking": 'بس أتفرج',
  'do you have this in another size': 'عندكم مقاس ثاني؟',
  'do you have this in another size?': 'عندكم مقاس ثاني؟',
  'do you have this in another color': 'عندكم لون ثاني؟',
  'do you have this in another color?': 'عندكم لون ثاني؟',
  'can i try this on': 'ممكن أجربه؟',
  'can i try this on?': 'ممكن أجربه؟',
  "it's too expensive": 'غالي وايد',
  'is there a discount': 'في خصم؟',
  'is there a discount?': 'في خصم؟',
  'can you give me a discount': 'تقدر تنزل السعر؟',
  'can you give me a discount?': 'تقدر تنزل السعر؟',
  "i'll take it": 'بأخذه',
  "i don't want it": 'ما أبيه',
  'where is the fitting room': 'وين غرفة القياس؟',
  'where is the fitting room?': 'وين غرفة القياس؟',
  'do you accept card': 'تاخذون كارد؟',
  'do you accept card?': 'تاخذون كارد؟',
  'cash only': 'كاش بس',

  // === TRANSPORTATION & DIRECTIONS ===
  'where is the bathroom': 'وين الحمام؟',
  'where is the bathroom?': 'وين الحمام؟',
  'where is the exit': 'وين المخرج؟',
  'where is the exit?': 'وين المخرج؟',
  'where is the entrance': 'وين المدخل؟',
  'where is the entrance?': 'وين المدخل؟',
  'turn right': 'لف يمين',
  'turn left': 'لف يسار',
  'go straight': 'روح سيدا',
  "it's here": 'هني',
  "it's there": 'هناك',
  "it's far": 'بعيد',
  "it's near": 'قريب',
  "it's close": 'قريب',
  'how far is it': 'جم بعيد؟',
  'how far is it?': 'جم بعيد؟',
  'can you take me to': 'تقدر توديني؟',
  'can you take me there': 'تقدر توديني هناك؟',
  'can you take me there?': 'تقدر توديني هناك؟',
  'i want to go to': 'أبي أروح',
  'stop here': 'وقف هني',
  'stop here please': 'وقف هني لو سمحت',
  'how much to go there': 'بجم توديني هناك؟',
  'how much to go there?': 'بجم توديني هناك؟',

  // === HOTEL & BOOKING ===
  'i have a reservation': 'عندي حجز',
  'i want to book a room': 'أبي أحجز غرفة',
  'do you have any rooms available': 'عندكم غرف فاضية؟',
  'do you have any rooms available?': 'عندكم غرف فاضية؟',
  'for how many nights': 'لجم ليلة؟',
  'for how many nights?': 'لجم ليلة؟',
  'what time is check in': 'متى وقت الدخول؟',
  'what time is check in?': 'متى وقت الدخول؟',
  'what time is check out': 'متى وقت الخروج؟',
  'what time is check out?': 'متى وقت الخروج؟',
  'i want to check out': 'أبي أسوي تشيك آوت',
  'is breakfast included': 'الفطور داخل؟',
  'is breakfast included?': 'الفطور داخل؟',
  'where is the wifi password': 'وين باسورد الواي فاي؟',
  'where is the wifi password?': 'وين باسورد الواي فاي؟',
  'what is the wifi password': 'شنو باسورد الواي فاي؟',
  'what is the wifi password?': 'شنو باسورد الواي فاي؟',

  // === APPOINTMENTS & TIME ===
  'i want to make an appointment': 'أبي أحجز موعد',
  'i have an appointment': 'عندي موعد',
  'what time': 'الساعة جم؟',
  'what time?': 'الساعة جم؟',
  'at what time': 'الساعة جم؟',
  'at what time?': 'الساعة جم؟',
  'is it open': 'مفتوح؟',
  'is it open?': 'مفتوح؟',
  'is it closed': 'مسكر؟',
  'is it closed?': 'مسكر؟',
  'when does it open': 'متى يفتح؟',
  'when does it open?': 'متى يفتح؟',
  'when does it close': 'متى يسكر؟',
  'when does it close?': 'متى يسكر؟',
  "i'm early": 'أنا بدري',
  "i'm on time": 'أنا على الوقت',
  "i'll be there soon": 'بوصل الحين',
  "i'm on my way": 'أنا في الطريق',
  "i'm almost there": 'قربت أوصل',

  // === PHONE & COMMUNICATION ===
  'can i call you': 'أقدر أكلمك؟',
  'can i call you?': 'أقدر أكلمك؟',
  'call me later': 'كلمني بعدين',
  "i'll call you back": 'برد عليك',
  "i'll call you later": 'بكلمك بعدين',
  'send me a message': 'أرسلي رسالة',
  'i sent you a message': 'أرسلتلك رسالة',
  'did you get my message': 'وصلتك رسالتي؟',
  'did you get my message?': 'وصلتك رسالتي؟',
  "what's your number": 'شنو رقمك؟',
  "what's your number?": 'شنو رقمك؟',
  'my number is': 'رقمي',

  // === COMMON EXPRESSIONS ===
  'god willing': 'إن شاء الله',
  'hopefully': 'إن شاء الله',
  'praise god': 'الحمدلله',
  'thank god': 'الحمدلله',
  'bless you': 'يعطيك العافية',
  'congratulations': 'مبروك',
  'happy birthday': 'عيد ميلاد سعيد',
  'happy eid': 'عيد مبارك',
  'welcome': 'أهلاً وسهلاً',
  'my pleasure': 'هذا واجب',
  'nice to meet you': 'تشرفنا',
  'same to you': 'وأنت بعد',
  'me too': 'وأنا بعد',
  'really': 'صدق؟',
  'really?': 'صدق؟',
  'seriously': 'بالجد؟',
  'seriously?': 'بالجد؟',
  'are you serious': 'أنت بالجد؟',
  'are you serious?': 'أنت بالجد؟',
  'i swear': 'والله',
  'i promise': 'أوعدك',
  "don't worry": 'لا تشيل هم',
  "it's okay": 'ما عليه',
  'never mind': 'ما عليه',
  "it doesn't matter": 'ما يفرق',
  'what a pity': 'حرام',
  'too bad': 'حرام',
  "that's great": 'هذا وايد حلو',
  "that's good": 'هذا زين',
  "that's bad": 'هذا سيئ',
  "that's wrong": 'هذا غلط',
  "that's right": 'هذا صح',
  "that's true": 'هذا صحيح',
  "that's enough": 'هذا يكفي',
  'enough': 'يكفي',
  'stop it': 'خلاص',
  'be quiet': 'اسكت',
  'shut up': 'اسكت',
  'be careful': 'انتبه',
  'watch out': 'انتبه',
  'take your time': 'على كيفك',
  'no rush': 'ما في استعجال',
  'in a hurry': 'مستعجل',
  'what a shame': 'عيب',
  "that's embarrassing": 'هذا محرج',

  // === MISCELLANEOUS CONVERSATIONS ===
  'what are you doing': 'شنو تسوي؟',
  'what are you doing?': 'شنو تسوي؟',
  'nothing much': 'ما في شي',
  'just relaxing': 'بس مرتاح',
  "i'm working": 'أنا أشتغل',
  "i'm eating": 'أنا آكل',
  "i'm sleeping": 'أنا نايم',
  'where have you been': 'وين كنت؟',
  'where have you been?': 'وين كنت؟',
  'i was busy': 'كنت مشغول',
  'long time no see': 'من زمان ما شفتك',
  'i missed you': 'اشتقتلك',
  "how's your family": 'شلون العيلة؟',
  "how's your family?": 'شلون العيلة؟',
  "they're fine": 'زينين الحمدلله',
  'say hi to them': 'سلم عليهم',
  'give my regards': 'سلامي لهم',
  'have a safe trip': 'رحلة سعيدة',
  'bon voyage': 'رحلة سعيدة',
  'good luck': 'بالتوفيق',
  'best wishes': 'أتمنى لك التوفيق',
  'get well soon': 'سلامتك',
  "that's interesting": 'هذا مثير',
  "i'm interested": 'أنا مهتم',
  "i'm not interested": 'أنا مو مهتم',
  'leave me alone': 'خلني لحالي',
  'mind your own business': 'شغلك شغلك',
  "it's none of your business": 'مو شغلك',
  "i don't care": 'ما يهمني',
  'whatever': 'أي شي',
  'as you wish': 'على كيفك',
  'up to you': 'عليك',
  'your choice': 'اختيارك',
};

// ============================================
// VOCABULARY CLASS
// ============================================

class QatariVocabulary {
  public entries: VocabularyEntry[] = [];
  private wordIndex: Map<string, VocabularyEntry> = new Map();
  private usageIndex: Map<string, VocabularyEntry[]> = new Map();

  load(vocabPath: string): void {
    if (!fs.existsSync(vocabPath)) {
      throw new Error(`Vocabulary file not found: ${vocabPath}`);
    }

    const data = JSON.parse(fs.readFileSync(vocabPath, 'utf-8')) as VocabularyEntry[];

    for (const item of data) {
      const entry: VocabularyEntry = {
        word: item.word || '',
        transliteration: item.transliteration || '',
        meaning_en: item.meaning_en || '',
        sentence_simple: item.sentence_simple || '',
        sentence_qatari: item.sentence_qatari || '',
        usage: item.usage || '',
      };
      this.entries.push(entry);
      this.wordIndex.set(entry.word, entry);

      if (!this.usageIndex.has(entry.usage)) {
        this.usageIndex.set(entry.usage, []);
      }
      this.usageIndex.get(entry.usage)!.push(entry);
    }
  }

  getAllWords(): Set<string> {
    return new Set(this.wordIndex.keys());
  }

  getUsageCategories(): string[] {
    return Array.from(this.usageIndex.keys());
  }

  findByUsage(usage: string): VocabularyEntry[] {
    return this.usageIndex.get(usage) || [];
  }
}

// ============================================
// TRANSLATION CACHE (LRU)
// ============================================

class TranslationCache {
  private maxSize: number;
  private cache: Map<string, [string, number]> = new Map();
  private accessOrder: string[] = [];

  constructor(maxSize: number = 2000) {
    this.maxSize = maxSize;
  }

  private normalizeKey(text: string): string {
    return crypto.createHash('md5').update(text.toLowerCase().trim()).digest('hex');
  }

  get(text: string): string | null {
    const key = this.normalizeKey(text);
    if (this.cache.has(key)) {
      const idx = this.accessOrder.indexOf(key);
      if (idx !== -1) {
        this.accessOrder.splice(idx, 1);
      }
      this.accessOrder.push(key);
      return this.cache.get(key)![0];
    }
    return null;
  }

  set(text: string, translation: string): void {
    const key = this.normalizeKey(text);

    while (this.cache.size >= this.maxSize && this.accessOrder.length > 0) {
      const oldest = this.accessOrder.shift()!;
      this.cache.delete(oldest);
    }

    this.cache.set(key, [translation, Date.now()]);
    this.accessOrder.push(key);
  }

  stats(): { cached_entries: number; max_size: number } {
    return { cached_entries: this.cache.size, max_size: this.maxSize };
  }

  clear(): void {
    this.cache.clear();
    this.accessOrder = [];
  }
}

// ============================================
// QATARI DIALECT SERVICE
// ============================================

class QatariDialectService {
  private static readonly MODEL = 'claude-haiku-4-5-20251001';

  private vocabulary: QatariVocabulary;
  private client: Anthropic | null = null;
  private systemPrompt: string = '';
  private cache: TranslationCache;
  private initialized = false;

  constructor() {
    this.vocabulary = new QatariVocabulary();
    this.cache = new TranslationCache(2000);
  }

  private ensureInitialized(): void {
    if (this.initialized) return;

    const vocabPath = path.join(process.cwd(), 'lib/data/qatari-vocabulary.json');

    try {
      this.vocabulary.load(vocabPath);
      logger.info('Qatari dialect vocabulary loaded', {
        entries: this.vocabulary.entries.length,
        commonPhrases: Object.keys(COMMON_PHRASES).length,
      });
    } catch (error) {
      logger.warn('Qatari vocabulary file not found, proceeding without vocabulary', {
        path: vocabPath,
        error: String(error),
      });
    }

    this.client = new Anthropic({
      apiKey: process.env.ANTHROPIC_API_KEY,
    });

    this.systemPrompt = this.buildSystemPrompt();
    this.initialized = true;
  }

  private buildSystemPrompt(): string {
    const usageSamples: Record<string, Array<{ word: string; meaning: string }>> = {};
    const categories = this.vocabulary.getUsageCategories().slice(0, 15);

    for (const usage of categories) {
      const entries = this.vocabulary.findByUsage(usage).slice(0, 3);
      usageSamples[usage] = entries.map((e) => ({
        word: e.word,
        meaning: e.meaning_en,
      }));
    }

    const allWordsList = Array.from(this.vocabulary.getAllWords()).slice(0, 80);

    return `You are an expert in professional Gulf Arabic (اللهجة الخليجية) with Qatari flavor.

## CRITICAL RULES

### Context: Business Customer Service Bot
You are translating for a professional real estate / appointment booking bot.
The Arabic must be:
1. **Professional and polite** — suitable for a business context
2. **Universally readable** by ALL Arabic speakers (GCC, Levant, North Africa)
3. **Gulf-flavored** but never so dialectal that it becomes ambiguous or confusing

### Words to NEVER USE (ambiguous or too informal):
| AVOID | USE INSTEAD | WHY |
|-------|-------------|-----|
| أبيك | تبي / تودّ / تحب | أبيك reads as "your father" to non-Gulf speakers |
| ولا (for "or") | أو / ولّا | ولا reads as "and not" in MSA — always use أو for "or" |
| شو | شنو | شو is LEVANTINE, NOT Gulf |
| إيش | شنو | إيش is HIJAZI, NOT Gulf |

### Preferred Gulf Arabic Words (USE THESE):
- **تبي** (tabi) = you want (clear, unambiguous)
- **أبغى / أبي** (abgha/abi) = I want (first person only, never with suffix ك)
- **شنو** (shinu) = what
- **شلونك** = how are you
- **الحين** = now
- **زين** = good/ok
- **أو** = or (ALWAYS use أو, never ولا for "or")
- **وين** = where
- **ليش** = why
- **هلا** = hello
- **وايد** = very
- **تمام** = OK/done
- **إن شاء الله** = God willing

## Sample Vocabulary:
${allWordsList.join(', ')}

## Sample by Category:
${JSON.stringify(usageSamples, null, 2)}
`;
  }

  isInitialized(): boolean {
    return this.initialized;
  }

  async translateToQatari(text: string): Promise<TranslationResult> {
    this.ensureInitialized();

    const normalizedText = text.toLowerCase().trim();

    // 1. Check pre-computed common phrases (instant)
    if (COMMON_PHRASES[normalizedText]) {
      return {
        translation: COMMON_PHRASES[normalizedText],
        source: 'common_phrases',
        cached: true,
      };
    }

    // 2. Check translation cache
    const cached = this.cache.get(text);
    if (cached) {
      return {
        translation: cached,
        source: 'cache',
        cached: true,
      };
    }

    // 3. Call Anthropic API
    const prompt = `Translate the following English text to professional Gulf Arabic with Qatari flavor.

IMPORTANT RULES:
1. Use professional, polite Gulf Arabic suitable for a business customer service bot
2. NEVER use "أبيك" — it reads as "your father" to many Arabic speakers. Use "تبي" for "do you want"
3. ALWAYS use "أو" for "or" — NEVER use "ولا" for "or" as it reads as "and not" in standard Arabic
4. Keep it universally readable by all Arabic speakers, not just Qataris
5. NEVER use Levantine words like "شو" — use "شنو" instead
6. Use Gulf greetings like "هلا وغلا" but keep the rest professional
7. Preserve all numbers, dates, prices, property names, and technical details exactly as-is

English text to translate:
${text}

Provide ONLY the Arabic translation, nothing else.`;

    const response = await this.client!.messages.create({
      model: QatariDialectService.MODEL,
      max_tokens: 500,
      system: [
        {
          type: 'text',
          text: this.systemPrompt,
          cache_control: { type: 'ephemeral' },
        },
      ],
      messages: [{ role: 'user', content: prompt }],
    });

    const translation = (response.content[0] as { type: 'text'; text: string }).text.trim();

    // Cache the result
    this.cache.set(text, translation);

    logger.debug('Qatari dialect API translation', {
      input: text.substring(0, 100),
      source: 'api',
      model: QatariDialectService.MODEL,
    });

    return {
      translation,
      source: 'api',
      cached: false,
    };
  }

  getCacheStats(): { cached_entries: number; max_size: number; common_phrases_count: number } {
    return {
      ...this.cache.stats(),
      common_phrases_count: Object.keys(COMMON_PHRASES).length,
    };
  }

  clearCache(): void {
    this.cache.clear();
  }
}

// Singleton export
export const qatariDialectService = new QatariDialectService();
