import apiService from './apiService';

export interface TranslationRecord {
  source_text: string;
  translated_text: string;
  language: string;
  context?: string;
}

export interface TranslationsMap {
  [key: string]: string;
}

/**
 * Fetch translations from Frappe Translation doctype
 * Frappe stores translations in the "Translation" doctype, not "Language"
 * Language doctype is just for enabling languages
 */
export async function fetchTranslationsFromFrappe(language: string): Promise<TranslationsMap> {
  try {
    // Fetch all translation records for the specified language
    // Frappe uses "Translation" doctype with fields: source_text, translated_text, language, context
    const response = await apiService.getDoctypeRecords(
      'Translation',
      { language: language },
      ['source_text', 'translated_text', 'context'],
      10000, // Large limit to get all translations
      0
    );

    const translations: TranslationsMap = {};

    if (response.records && response.records.length > 0) {
      response.records.forEach((record: any) => {
        const sourceText = record.source_text;
        const translatedText = record.translated_text || sourceText;
        
        // Frappe translations can have:
        // 1. source_text as the key (e.g., "Dashboard")
        // 2. context for namespacing (e.g., "common.Dashboard" if context is "common")
        // 3. Or source_text might already be a nested key (e.g., "common.dashboard")
        
        if (record.context) {
          // If context exists, create nested structure: context.source_text
          const key = `${record.context}.${sourceText}`;
          translations[key] = translatedText;
        } else if (sourceText.includes('.')) {
          // If source_text already contains dots, use it as-is (already nested)
          translations[sourceText] = translatedText;
        } else {
          // Flat structure: use source_text as key
          translations[sourceText] = translatedText;
        }
      });
    }

    return translations;
  } catch (error) {
    console.error('Error fetching translations from Frappe:', error);
    // Return empty object on error, will fall back to static translations
    return {};
  }
}

/**
 * Convert flat translation map to nested structure for i18next
 * Handles keys like "common.dashboard" -> { common: { dashboard: "..." } }
 * Also handles simple keys without dots
 */
export function nestTranslations(flatTranslations: TranslationsMap): Record<string, any> {
  const nested: Record<string, any> = {};

  Object.keys(flatTranslations).forEach((key) => {
    // If key contains dots, create nested structure
    if (key.includes('.')) {
      const parts = key.split('.');
      let current = nested;

      for (let i = 0; i < parts.length - 1; i++) {
        const part = parts[i];
        if (!current[part]) {
          current[part] = {};
        }
        current = current[part];
      }

      current[parts[parts.length - 1]] = flatTranslations[key];
    } else {
      // Simple key without dots - add directly
      nested[key] = flatTranslations[key];
    }
  });

  return nested;
}

/**
 * Get translations for a specific language from Frappe
 * Returns nested translation object ready for i18next
 */
export async function getFrappeTranslations(language: string): Promise<Record<string, any>> {
  const flatTranslations = await fetchTranslationsFromFrappe(language);
  return nestTranslations(flatTranslations);
}

