/**
 * SKILL: Add Translation
 *
 * Add a new translation key to all language files in the correct module.
 * Automatically handles file structure, formatting, and validation.
 *
 * Token Savings: 12,000+ (multiple file operations + formatting → single skill)
 *
 * Use this skill when:
 * - Adding new UI text
 * - Adding error messages
 * - Adding validation messages
 * - Expanding feature copy
 */

import * as i18n from "../servers/i18n";
import * as files from "../servers/files";

export interface AddTranslationInput {
  key: string; // e.g., 'booking.cancelSuccess'
  values: {
    ar: string;
    en: string;
  };
  module?: string; // e.g., 'pages/booking', auto-detect if not provided
}

export interface AddTranslationResult {
  success: boolean;
  filesUpdated: string[];
  key: string;
  module: string;
  error?: string;
}

/**
 * Add a translation to both Arabic and English language files.
 *
 * @param input - Translation key and values
 * @returns Update result with affected files
 *
 * @example
 * ```typescript
 * // Add booking cancellation success message
 * const result = await addTranslation({
 *   key: 'booking.cancelSuccess',
 *   values: {
 *     ar: 'تم إلغاء الحجز بنجاح',
 *     en: 'Booking cancelled successfully'
 *   },
 *   module: 'pages/booking'
 * });
 *
 * console.log(`✓ Translation added to ${result.filesUpdated.length} files`);
 * result.filesUpdated.forEach(file => console.log(`  - ${file}`));
 * ```
 *
 * @example
 * ```typescript
 * // Add error message (auto-detect module from key)
 * await addTranslation({
 *   key: 'errors.invalidPhone',
 *   values: {
 *     ar: 'رقم الهاتف غير صحيح',
 *     en: 'Invalid phone number'
 *   }
 * });
 * ```
 *
 * @example
 * ```typescript
 * // Add multiple related translations
 * const statusMessages = [
 *   { key: 'status.pending', ar: 'قيد الانتظار', en: 'Pending' },
 *   { key: 'status.confirmed', ar: 'مؤكد', en: 'Confirmed' },
 *   { key: 'status.cancelled', ar: 'ملغي', en: 'Cancelled' }
 * ];
 *
 * for (const msg of statusMessages) {
 *   await addTranslation({
 *     key: msg.key,
 *     values: { ar: msg.ar, en: msg.en },
 *     module: 'common/status'
 *   });
 * }
 *
 * console.log('✓ All status messages added');
 * ```
 */
export async function addTranslation(
  input: AddTranslationInput,
): Promise<AddTranslationResult> {
  try {
    // Auto-detect module from key if not provided
    const module = input.module || detectModuleFromKey(input.key);

    // Add translation via i18n server
    const result = await i18n.addTranslation({
      key: input.key,
      ar: input.values.ar,
      en: input.values.en,
      module,
    });

    return {
      success: result.success,
      filesUpdated: result.filesUpdated,
      key: input.key,
      module,
    };
  } catch (error: any) {
    return {
      success: false,
      filesUpdated: [],
      key: input.key,
      module: input.module || "",
      error: error.message,
    };
  }
}

/**
 * Helper: Detect module from translation key.
 */
function detectModuleFromKey(key: string): string {
  const parts = key.split(".");

  // Common patterns
  if (parts[0] === "nav") return "common/nav";
  if (parts[0] === "footer") return "common/footer";
  if (parts[0] === "errors") return "common/errors";
  if (parts[0] === "common") return "common/ui";

  // Page-specific
  if (["signup", "login", "pricing", "about", "contact"].includes(parts[0])) {
    return `pages/${parts[0]}`;
  }

  // Industry-specific
  if (["healthcare", "beauty", "hotels", "food", "events"].includes(parts[0])) {
    return `industries/${parts[0]}`;
  }

  // Default to common
  return "common/ui";
}

/**
 * Batch add multiple translations at once.
 *
 * @param translations - Array of translations to add
 * @returns Batch result
 *
 * @example
 * ```typescript
 * const batch = await addTranslationBatch([
 *   { key: 'booking.create', ar: 'إنشاء حجز', en: 'Create Booking' },
 *   { key: 'booking.cancel', ar: 'إلغاء الحجز', en: 'Cancel Booking' },
 *   { key: 'booking.confirm', ar: 'تأكيد الحجز', en: 'Confirm Booking' }
 * ]);
 *
 * console.log(`✓ Added ${batch.successful} translations`);
 * if (batch.failed > 0) {
 *   console.log(`✗ Failed ${batch.failed} translations`);
 * }
 * ```
 */
export async function addTranslationBatch(
  translations: Array<{ key: string; ar: string; en: string; module?: string }>,
): Promise<{
  successful: number;
  failed: number;
  results: AddTranslationResult[];
}> {
  const results = await Promise.all(
    translations.map((t) =>
      addTranslation({
        key: t.key,
        values: { ar: t.ar, en: t.en },
        module: t.module,
      }),
    ),
  );

  const successful = results.filter((r) => r.success).length;
  const failed = results.filter((r) => !r.success).length;

  return { successful, failed, results };
}

export default {
  addTranslation,
  addTranslationBatch,
};
