/**
 * React Native Platform Detection Utilities
 * 
 * Provides automatic platform info detection for React Native apps.
 * 
 * @module @explorins/pers-sdk-react-native/utils
 */

import { Platform as RNPlatform } from 'react-native';
import type { Platform } from '@explorins/pers-sdk/core';

// DeviceInfo is optional - dynamically loaded if available
let DeviceInfo: any = null;
try {
  // eslint-disable-next-line @typescript-eslint/no-require-imports
  DeviceInfo = require('react-native-device-info').default;
} catch {
  // react-native-device-info not installed - will use basic detection
}

/**
 * Detect platform info for React Native apps
 * 
 * Automatically gathers OS, version, app info, and device type.
 * Uses react-native-device-info for enhanced detection if installed.
 * 
 * @example
 * ```typescript
 * import { detectReactNativePlatform } from '@explorins/pers-sdk-react-native';
 * 
 * // Get platform info
 * const platform = await detectReactNativePlatform();
 * // { os: 'iOS', osVersion: '17.4', app: 'MyApp', appVersion: '2.3.1', deviceType: 'phone' }
 * 
 * // Set in SDK
 * sdk.setPlatform(platform);
 * ```
 */
export async function detectReactNativePlatform(): Promise<Platform> {
  const platform: Platform = {
    os: RNPlatform.OS === 'ios' ? 'iOS' : RNPlatform.OS === 'android' ? 'Android' : RNPlatform.OS,
    osVersion: RNPlatform.Version?.toString(),
    deviceType: 'phone', // Default fallback
  };

  if (DeviceInfo) {
    try {
      // App info
      platform.app = await DeviceInfo.getApplicationName();
      platform.appVersion = DeviceInfo.getVersion();
      
      // Device type detection
      const isTablet = await DeviceInfo.isTablet();
      platform.deviceType = isTablet ? 'tablet' : 'phone';
    } catch (error) {
      console.debug('[Platform] DeviceInfo error, using basic detection');
    }
  }

  return platform;
}

/**
 * Synchronous version for immediate use (limited info)
 * 
 * Use when you need platform info immediately without async.
 * For full info including device type, use detectReactNativePlatform().
 */
export function detectReactNativePlatformSync(): Platform {
  const platform: Platform = {
    os: RNPlatform.OS === 'ios' ? 'iOS' : RNPlatform.OS === 'android' ? 'Android' : RNPlatform.OS,
    osVersion: RNPlatform.Version?.toString(),
    deviceType: 'phone', // Default, can't detect tablet sync without DeviceInfo
  };

  if (DeviceInfo) {
    try {
      platform.app = DeviceInfo.getApplicationNameSync?.();
      platform.appVersion = DeviceInfo.getVersion?.();
    } catch {
      // Ignore if DeviceInfo methods fail
    }
  }

  return platform;
}
