/**
 * i18n MCP Server - Translation
 *
 * Provides translation management operations for Mawidi's 5,979 lines of content.
 * Token savings: 15,000+ per operation (avoids loading all translations)
 *
 * Translation Structure:
 * - lib/config/translations/ar.ts - Arabic translations aggregator
 * - lib/config/translations/en.ts - English translations aggregator
 * - lib/config/translations/modules/ - Modular translation files
 */

import { callMCPTool } from "../../client.js";

export interface Translation {
  key: string;
  ar: string;
  en: string;
  module: string;
}

export interface SearchTranslationsInput {
  query: string;
  language?: "ar" | "en" | "both";
  module?: string;
}

export interface AddTranslationInput {
  key: string;
  ar: string;
  en: string;
  module: string; // e.g., 'pages/signup', 'common/nav', 'industries/healthcare'
}

export interface TranslationStats {
  total: number;
  byModule: Record<string, number>;
  byLanguage: {
    ar: number;
    en: number;
  };
  missing: Array<{
    key: string;
    missingIn: "ar" | "en";
  }>;
}

/**
 * Get a specific translation by key.
 *
 * @param key - Translation key (dot notation)
 * @param language - Language to retrieve
 * @returns Translation text
 *
 * @example
 * ```typescript
 * const text = await getTranslation('nav.home', 'ar');
 * console.log(text); // "الرئيسية"
 *
 * const both = await getTranslation('nav.home', 'both');
 * console.log(both); // { ar: "الرئيسية", en: "Home" }
 * ```
 */
export async function getTranslation(
  key: string,
  language: "ar" | "en" | "both" = "both",
): Promise<string | { ar: string; en: string }> {
  return callMCPTool("i18n__get_translation", { key, language });
}

/**
 * Search translations by text or key.
 *
 * @param input - Search parameters
 * @returns Array of matching translations
 *
 * @example
 * ```typescript
 * // Search for booking-related translations
 * const results = await searchTranslations({
 *   query: 'booking',
 *   language: 'both'
 * });
 *
 * console.log(`Found ${results.length} translations:`);
 * results.slice(0, 5).forEach(t => {
 *   console.log(`  ${t.key}: ${t.en} / ${t.ar}`);
 * });
 * ```
 */
export async function searchTranslations(
  input: SearchTranslationsInput,
): Promise<Translation[]> {
  return callMCPTool<Translation[]>("i18n__search_translations", input);
}

/**
 * Add a new translation to the appropriate module.
 *
 * @param input - Translation data
 * @returns Success confirmation
 *
 * @example
 * ```typescript
 * await addTranslation({
 *   key: 'booking.cancelSuccess',
 *   ar: 'تم إلغاء الحجز بنجاح',
 *   en: 'Booking cancelled successfully',
 *   module: 'pages/booking'
 * });
 *
 * console.log('✓ Translation added to both language files');
 * ```
 */
export async function addTranslation(
  input: AddTranslationInput,
): Promise<{ success: boolean; filesUpdated: string[] }> {
  return callMCPTool("i18n__add_translation", input);
}

/**
 * Get translation statistics and completeness.
 *
 * @returns Translation stats with missing entries
 *
 * @example
 * ```typescript
 * const stats = await getTranslationStats();
 *
 * console.log(`Total translations: ${stats.total}`);
 * console.log(`By module:`, Object.entries(stats.byModule).slice(0, 5));
 *
 * if (stats.missing.length > 0) {
 *   console.log(`Missing translations: ${stats.missing.length}`);
 *   stats.missing.forEach(m => {
 *     console.log(`  ${m.key} (missing ${m.missingIn})`);
 *   });
 * }
 * ```
 */
export async function getTranslationStats(): Promise<TranslationStats> {
  return callMCPTool<TranslationStats>("i18n__get_translation_stats", {});
}

/**
 * List all translation modules.
 *
 * @returns Array of module paths
 *
 * @example
 * ```typescript
 * const modules = await listTranslationModules();
 * console.log('Translation modules:', modules);
 * // ['pages/signup', 'pages/login', 'common/nav', 'industries/healthcare', ...]
 * ```
 */
export async function listTranslationModules(): Promise<string[]> {
  return callMCPTool<string[]>("i18n__list_modules", {});
}

/**
 * Get all translations from a specific module.
 *
 * @param module - Module path
 * @returns Translations from that module
 *
 * @example
 * ```typescript
 * const navTranslations = await getModuleTranslations('common/nav');
 *
 * console.log('Navigation translations:');
 * navTranslations.forEach(t => {
 *   console.log(`  ${t.key}: ${t.en}`);
 * });
 * ```
 */
export async function getModuleTranslations(
  module: string,
): Promise<Translation[]> {
  return callMCPTool<Translation[]>("i18n__get_module_translations", {
    module,
  });
}

/**
 * Validate translation completeness (both languages present).
 *
 * @returns Validation report with missing translations
 *
 * @example
 * ```typescript
 * const validation = await validateTranslations();
 *
 * if (validation.valid) {
 *   console.log('✓ All translations complete');
 * } else {
 *   console.log(`✗ ${validation.errors.length} missing translations:`);
 *   validation.errors.forEach(err => console.log(`  - ${err}`));
 * }
 * ```
 */
export async function validateTranslations(): Promise<{
  valid: boolean;
  errors: string[];
  warnings: string[];
}> {
  return callMCPTool("i18n__validate_translations", {});
}

export default {
  getTranslation,
  searchTranslations,
  addTranslation,
  getTranslationStats,
  listTranslationModules,
  getModuleTranslations,
  validateTranslations,
};
