/**
 * Proxy Query Operations - Getting active proxies from cache
 */
import { OperationContext } from '@stock-bot/di';
import type { ProxyInfo } from '@stock-bot/proxy';
import { PROXY_CONFIG } from '../shared/config';

/**
 * Get a random active proxy from the cache
 * @param protocol - Optional protocol filter ('http' | 'https' | 'socks4' | 'socks5')
 * @param minSuccessRate - Minimum success rate percentage (default: 50)
 * @returns A random working proxy or null if none found
 */
export async function getRandomActiveProxy(
  protocol?: 'http' | 'https' | 'socks4' | 'socks5',
  minSuccessRate: number = 50
): Promise<ProxyInfo | null> {
  const ctx = OperationContext.create('proxy', 'get-random');

  try {
    // Get all active proxy keys from cache
    const pattern = protocol
      ? `${PROXY_CONFIG.CACHE_KEY}:${protocol}://*`
      : `${PROXY_CONFIG.CACHE_KEY}:*`;

    const keys = await ctx.cache.keys(pattern);

    if (keys.length === 0) {
      ctx.logger.debug('No active proxies found in cache', { pattern });
      return null;
    }

    // Shuffle the keys for randomness
    const shuffledKeys = keys.sort(() => Math.random() - 0.5);

    // Find a working proxy that meets the criteria
    for (const key of shuffledKeys) {
      try {
        const proxyData: ProxyInfo | null = await ctx.cache.get(key);

        if (
          proxyData &&
          proxyData.isWorking &&
          (!proxyData.successRate || proxyData.successRate >= minSuccessRate)
        ) {
          ctx.logger.debug('Random active proxy selected', {
            proxy: `${proxyData.host}:${proxyData.port}`,
            protocol: proxyData.protocol,
            successRate: proxyData.successRate?.toFixed(1) + '%',
            avgResponseTime: proxyData.averageResponseTime
              ? `${proxyData.averageResponseTime.toFixed(0)}ms`
              : 'N/A',
          });

          return proxyData;
        }
      } catch (error) {
        ctx.logger.debug('Error reading proxy from cache', {
          key,
          error: (error as Error).message,
        });
        continue;
      }
    }

    ctx.logger.debug('No working proxies found meeting criteria', {
      protocol,
      minSuccessRate,
      keysChecked: shuffledKeys.length,
    });

    return null;
  } catch (error) {
    ctx.logger.error('Error getting random active proxy', {
      error: error instanceof Error ? error.message : String(error),
      protocol,
      minSuccessRate,
    });
    return null;
  }
}
