import { TranslationContainerModel } from '../translation-container-model';
import { LocaleDescriptor, Localization, TranslationResponse } from '../services';
import { KosContext, KosParentAware } from '../../../../core';


// ---------------  Translation ---------------

/**
 * Configuration options for Translation model instances.
 *
 * This interface defines the complete configuration structure for individual translation
 * namespace models, including locale settings, resolution strategies, and custom loading
 * mechanisms. Translation models handle the actual key resolution and interpolation for
 * specific functional areas within KOS applications.
 *
 * @example Basic Translation Configuration
 * ```typescript
 * // Device status translations with English fallback
 * const statusOptions: TranslationOptions = {
 *   namespace: 'device-status',
 *   currentLocale: 'es',
 *   defaultLocale: 'en',
 *   descriptor: {
 *     'es': {
 *       fallbacks: ['en']
 *     },
 *     'en': {
 *       fallbacks: []
 *     }
 *   },
 *   kosParentId: 'translation-container'
 * };
 *
 * const statusTranslation = Translation.instance('status-translations')
 *   .options(statusOptions)
 *   .build();
 * ```
 *
 * @example Custom Bundle Resolution
 * ```typescript
 * // API-based translation loading
 * const apiBundleResolver = async (
 *   namespace: string,
 *   locale: string,
 *   context?: KosContext
 * ): Promise<TranslationResponse> => {
 *   const response = await fetch(`/api/translations/${namespace}/${locale}`);
 *   return await response.json();
 * };
 *
 * const apiOptions: TranslationOptions = {
 *   namespace: 'alerts',
 *   currentLocale: 'fr',
 *   defaultLocale: 'en',
 *   descriptor: {
 *     'fr': { fallbacks: ['en'] },
 *     'en': { fallbacks: [] }
 *   },
 *   bundleResolver: apiBundleResolver,
 *   kosParentId: 'translation-container'
 * };
 * ```
 *
 * @example Multi-Regional Configuration
 * ```typescript
 * // Complex fallback chains for regional variations
 * const regionalOptions: TranslationOptions = {
 *   namespace: 'regional-ui',
 *   currentLocale: 'pt-BR',
 *   defaultLocale: 'en',
 *   descriptor: {
 *     'pt-BR': { fallbacks: ['pt', 'es', 'en'] },
 *     'pt-PT': { fallbacks: ['pt', 'es', 'en'] },
 *     'pt': { fallbacks: ['es', 'en'] },
 *     'es': { fallbacks: ['en'] },
 *     'en': { fallbacks: [] }
 *   },
 *   kosParentId: 'translation-container'
 * };
 * ```
 *
 * @group KOS Model
 * @category i18n
 */
export interface TranslationOptions extends KosParentAware {
  /**
   * Translation namespace identifier, typically corresponding to a feature area.
   * Used to organize translations by functional domain and prevent key conflicts.
   *
   * @example "device-status"
   * @example "user-settings"
   * @example "maintenance-scheduler"
   */
  namespace: string;

  /**
   * Current active locale for this translation model.
   * Determines which language variant to load and display.
   *
   * @example "en" - English
   * @example "es" - Spanish
   * @example "pt-BR" - Brazilian Portuguese
   */
  currentLocale: string;

  /**
   * Default fallback locale when translations are missing in the current locale.
   * Typically set to the primary application language.
   *
   * @default "en"
   */
  defaultLocale: string;

  /**
   * Optional base URL for translation file loading.
   * Used with default file-based resolution strategy.
   *
   * @example "/assets/locales"
   * @example "https://cdn.example.com/translations"
   */
  rootUrl?: string;

  /**
   * Locale descriptors defining fallback chains and configuration for each locale.
   * Maps locale codes to their fallback hierarchy and metadata.
   */
  descriptor: Record<string, LocaleDescriptor>;

  /**
   * Optional custom path resolver for translation file loading.
   * Overrides default path construction logic.
   *
   * @param namespace - Target translation namespace
   * @param locale - Target locale code
   * @returns Full path to translation resource
   */
  resolver?: (namespace: string, locale: string) => string;

  /**
   * Optional custom bundle resolver for advanced translation loading strategies.
   * Enables loading from APIs, device storage, or custom sources.
   *
   * @param namespace - Target translation namespace
   * @param locale - Target locale code
   * @param context - KOS context for accessing shared data
   * @returns Promise resolving to translation data
   */
  bundleResolver?: (
    namespace: string,
    locale: string,
    context?: KosContext
  ) => Promise<TranslationResponse>;
}

// ---------------  TranslationContainer ---------------

/**
 * Configuration options for TranslationContainer model instances.
 *
 * This interface defines the configuration structure for translation container models,
 * which manage multiple translation namespaces and coordinate global locale switching.
 * Containers serve as the central orchestration point for internationalization in KOS
 * applications.
 *
 * @example Basic Container Configuration
 * ```typescript
 * // Multi-namespace application translations
 * const containerOptions: TranslationContainerOptions = {
 *   lang: 'es',
 *   defaultNamespace: 'common',
 *   descriptor: {
 *     namespaces: {
 *       'common': {
 *         basePath: '/assets/locales',
 *         locales: {
 *           'en': { file: 'en/common.json', defaultLocale: 'en' },
 *           'es': { file: 'es/common.json', defaultLocale: 'en' },
 *           'fr': { file: 'fr/common.json', defaultLocale: 'en' }
 *         }
 *       },
 *       'dashboard': {
 *         basePath: '/assets/locales',
 *         locales: {
 *           'en': { file: 'en/dashboard.json', defaultLocale: 'en' },
 *           'es': { file: 'es/dashboard.json', defaultLocale: 'en' },
 *           'fr': { file: 'fr/dashboard.json', defaultLocale: 'en' }
 *         }
 *       }
 *     }
 *   }
 * };
 *
 * const appTranslations = TranslationContainer.instance('app-i18n')
 *   .options(containerOptions)
 *   .build();
 * ```
 *
 * @example CDN-Based Translation Loading
 * ```typescript
 * // Custom resolver for CDN-hosted translations
 * const cdnResolver = function(
 *   namespace: string,
 *   locale: string
 * ): string {
 *   return `https://cdn.example.com/translations/${namespace}/${locale}.json`;
 * };
 *
 * const cdnOptions: TranslationContainerOptions = {
 *   lang: 'ja',
 *   resolver: cdnResolver,
 *   descriptor: {
 *     namespaces: {
 *       'device-control': {
 *         basePath: '', // Ignored with custom resolver
 *         locales: {
 *           'ja': { file: '', defaultLocale: 'en' },
 *           'en': { file: '', defaultLocale: 'en' }
 *         }
 *       }
 *     }
 *   }
 * };
 * ```
 *
 * @example Development Environment Setup
 * ```typescript
 * // Hot-reload friendly configuration for development
 * const devOptions: TranslationContainerOptions = {
 *   lang: 'en',
 *   rootUrl: '/dev-translations',
 *   descriptor: {
 *     namespaces: {
 *       'ui': {
 *         basePath: '/ui-translations',
 *         locales: {
 *           'en': { file: 'en/ui.json', defaultLocale: 'en' },
 *           'es': { file: 'es/ui.json', defaultLocale: 'en' }
 *         }
 *       },
 *       'forms': {
 *         basePath: '/form-translations',
 *         locales: {
 *           'en': { file: 'en/forms.json', defaultLocale: 'en' },
 *           'es': { file: 'es/forms.json', defaultLocale: 'en' }
 *         }
 *       }
 *     }
 *   }
 * };
 * ```
 *
 * @group KOS Model
 * @category i18n
 */
export interface TranslationContainerOptions {
  /**
   * Current application-wide locale setting.
   * Applied to all child translation models when they are created or updated.
   *
   * @example "en" - English
   * @example "es" - Spanish
   * @example "pt-BR" - Brazilian Portuguese
   */
  lang: string;

  /**
   * Comprehensive locale and namespace descriptor defining the complete
   * translation structure for the application.
   */
  descriptor: Localization;

  /**
   * Optional default namespace for application-wide common translations.
   * When specified, provides easy access to shared UI elements and messages.
   *
   * @example "common"
   * @example "shared"
   * @example "ui-elements"
   */
  defaultNamespace?: string;

  /**
   * Optional base URL for all translation file loading.
   * Applied as prefix to all translation resource paths.
   *
   * @example "/assets/locales"
   * @example "https://cdn.example.com/app-translations"
   * @example "/tenant-specific/translations"
   */
  rootUrl?: string;

  /**
   * Optional URL for loading translation descriptor dynamically.
   * Enables runtime configuration of translation structure.
   *
   * @example "/api/translations/descriptor"
   * @example "https://config.example.com/translation-manifest.json"
   */
  descriptorUrl?: string;

  /**
   * Optional custom resolver for translation file path construction.
   * Overrides default path resolution logic for all namespaces.
   *
   * @param namespace - Target translation namespace
   * @param locale - Target locale code
   * @returns Full path to translation resource
   */
  resolver?: (
    this: TranslationContainerModel,
    namespace: string,
    locale: string
  ) => string;
}

/**
 * Type definitions for variable interpolation in translation keys.
 *
 * Translation models support sophisticated variable substitution patterns
 * for dynamic content in internationalized applications.
 *
 * @group KOS Model
 * @category Internationalization
 */
export type ResolveTranslationOptions<T = string> =
  | {
      /**
       * Context variables for template-based interpolation using {{variable}} syntax.
       *
       * @example
       * ```typescript
       * t('welcome.message', {
       *   context: { username: 'John', unreadCount: 5 }
       * })
       * // "Welcome {{username}}, you have {{unreadCount}} messages"
       * // Result: "Welcome John, you have 5 messages"
       * ```
       */
      context?: Record<string, any>;

      /**
       * Data variables for macro-based interpolation using __variable__ syntax.
       *
       * @example
       * ```typescript
       * t('system.info', {
       *   data: { version: '2.1.0', platform: 'Linux' }
       * })
       * // "System __version__ running on __platform__"
       * // Result: "System 2.1.0 running on Linux"
       * ```
       */
      data?: Record<string, any>;

      /**
       * Contextual modifier for conditional key resolution.
       * Enables different translations based on application state.
       *
       * @example
       * ```typescript
       * // Translation file: { "title": "Create", "title_edit": "Update" }
       * t('title', { context: 'edit' })
       * // Resolves to "title_edit" key, returns "Update"
       * ```
       */
      context?: string;

      /**
       * Fallback value when translation key is not found.
       * Ensures graceful degradation for missing translations.
       */
      defaultValue?: T;
    }
  | string;

declare global {
  interface AbstractModelFactory {
    createTranslation: (id: string, options: TranslationOptions) => Translation;
    createTranslationContainer: (
      options: TranslationContainerOptions
    ) => TranslationContainer;
  }
}
