/**
 * Environment detection and runtime warnings for CDP compatibility issues
 */

export interface EnvironmentDiagnostics {
  cdpCompatibility: {
    isClientSide: boolean;
    hasProjectId: boolean;
    hasApiCredentials: boolean;
    nodeEnv: string;
    warnings: string[];
  };
  hookCompatibility: {
    detectedIssues: string[];
    recommendations: string[];
  };
}

/**
 * Detect runtime environment and CDP compatibility
 */
export function detectEnvironment(): EnvironmentDiagnostics {
  const isClientSide = typeof window !== 'undefined';
  const hasProjectId = typeof process !== 'undefined' && !!process.env.NEXT_PUBLIC_CDP_PROJECT_ID;
  const hasApiCredentials = typeof process !== 'undefined' && 
    !!(process.env.CDP_API_KEY_PRIVATE_KEY || process.env.CDP_SECRET_KEY) &&
    !!(process.env.CDP_API_KEY_NAME || process.env.CDP_SECRET_KEY_NAME);
  
  const warnings: string[] = [];
  const detectedIssues: string[] = [];
  const recommendations: string[] = [];

  // Check for common environment issues
  if (isClientSide && !hasProjectId) {
    warnings.push('NEXT_PUBLIC_CDP_PROJECT_ID not found in environment');
    recommendations.push('Set NEXT_PUBLIC_CDP_PROJECT_ID in your .env.local file');
  }

  if (!isClientSide && !hasApiCredentials) {
    warnings.push('CDP API credentials not found for server-side operations');
    recommendations.push('Set CDP_API_KEY_PRIVATE_KEY and CDP_API_KEY_NAME for onramp functionality');
  }

  // Check for Next.js specific issues
  if (isClientSide && !document.querySelector('script[src*="cdp"]')) {
    recommendations.push('Ensure components using CDP hooks have "use client" directive');
  }

  return {
    cdpCompatibility: {
      isClientSide,
      hasProjectId,
      hasApiCredentials,
      nodeEnv: typeof process !== 'undefined' ? process.env.NODE_ENV || 'unknown' : 'browser',
      warnings
    },
    hookCompatibility: {
      detectedIssues,
      recommendations
    }
  };
}

/**
 * Log environment diagnostics in development
 */
export function logEnvironmentDiagnostics() {
  if (typeof process !== 'undefined' && process.env.NODE_ENV !== 'development') {
    return;
  }

  const diagnostics = detectEnvironment();
  
  if (diagnostics.cdpCompatibility.warnings.length > 0) {
    console.warn('[CDP Kit] Environment warnings detected:');
    diagnostics.cdpCompatibility.warnings.forEach(warning => {
      console.warn(`  - ${warning}`);
    });
  }

  if (diagnostics.hookCompatibility.recommendations.length > 0) {
    console.info('[CDP Kit] Recommendations:');
    diagnostics.hookCompatibility.recommendations.forEach(rec => {
      console.info(`  - ${rec}`);
    });
  }
}

/**
 * Check for known compatibility issues at runtime
 */
export function checkHookCompatibility(hookResults: {
  evmAddress?: any;
  currentUser?: any;
  isInitialized?: any;
}) {
  const issues: string[] = [];
  
  // Check for object returns instead of primitives
  if (hookResults.evmAddress && typeof hookResults.evmAddress === 'object') {
    issues.push('useEvmAddress() returned object instead of string - using defensive extraction');
  }

  if (hookResults.currentUser && !hookResults.currentUser.userId && hookResults.currentUser.user) {
    issues.push('useCurrentUser() returned nested user object - using defensive extraction');
  }

  if (hookResults.isInitialized && typeof hookResults.isInitialized !== 'boolean') {
    issues.push('useIsInitialized() returned non-boolean - using defensive extraction');
  }

  if (issues.length > 0 && typeof console !== 'undefined') {
    console.warn('[CDP Kit] Hook compatibility issues detected:');
    issues.forEach(issue => console.warn(`  - ${issue}`));
    console.warn('The package is handling these issues automatically, but consider updating CDP SDK versions');
  }

  return issues;
}