/**
 * Game Performance Benchmark Service
 * Tracks and analyzes game performance metrics to identify top performers
 */
export interface GameBenchmark {
  gameId: string;
  gameName: string;
  theme: string;
  rtp: number;
  volatility: string;
  totalPlays: number;
  totalWinnings: number;
  averageWin: number;
  winRate: number;
  playerRetention: number;
  engagementScore: number;
  revenuePerPlayer: number;
  rank: number;
  trend: "up" | "down" | "stable";
}

export interface ThemeBenchmark {
  theme: string;
  totalGames: number;
  averageRTP: number;
  averageEngagement: number;
  topPerformers: string[];
  recommendedForRemix: boolean;
}

export class GamePerformanceBenchmark {
  private static benchmarks: Map<string, GameBenchmark> = new Map();
  private static themeBenchmarks: Map<string, ThemeBenchmark> = new Map();

  /**
   * Record game performance metrics
   */
  static recordGameMetrics(
    gameId: string,
    gameName: string,
    metrics: {
      theme: string;
      rtp: number;
      volatility: string;
      plays: number;
      winnings: number;
      retention: number;
      engagement: number;
    }
  ): void {
    const benchmark: GameBenchmark = {
      gameId,
      gameName,
      theme: metrics.theme,
      rtp: metrics.rtp,
      volatility: metrics.volatility,
      totalPlays: metrics.plays,
      totalWinnings: metrics.winnings,
      averageWin: metrics.winnings / Math.max(metrics.plays, 1),
      winRate: (metrics.winnings / (metrics.plays * 10)) * 100, // Simplified
      playerRetention: metrics.retention,
      engagementScore: metrics.engagement,
      revenuePerPlayer: metrics.winnings / Math.max(metrics.plays, 1),
      rank: 0,
      trend: "stable",
    };

    this.benchmarks.set(gameId, benchmark);
    this.updateThemeBenchmark(metrics.theme);
  }

  /**
   * Update theme benchmark
   */
  private static updateThemeBenchmark(theme: string): void {
    const gamesByTheme = Array.from(this.benchmarks.values()).filter(
      (g) => g.theme === theme
    );

    if (gamesByTheme.length === 0) return;

    const avgRTP = gamesByTheme.reduce((sum, g) => sum + g.rtp, 0) / gamesByTheme.length;
    const avgEngagement =
      gamesByTheme.reduce((sum, g) => sum + g.engagementScore, 0) / gamesByTheme.length;

    const topPerformers = gamesByTheme
      .sort((a, b) => b.engagementScore - a.engagementScore)
      .slice(0, 3)
      .map((g) => g.gameName);

    const recommendedForRemix = avgEngagement > 7.5 && avgRTP > 95;

    this.themeBenchmarks.set(theme, {
      theme,
      totalGames: gamesByTheme.length,
      averageRTP: avgRTP,
      averageEngagement: avgEngagement,
      topPerformers,
      recommendedForRemix,
    });
  }

  /**
   * Get top performing games
   */
  static getTopPerformers(limit: number = 10): GameBenchmark[] {
    const sorted = Array.from(this.benchmarks.values())
      .sort((a, b) => b.engagementScore - a.engagementScore)
      .slice(0, limit);

    // Update ranks
    sorted.forEach((game, idx) => {
      game.rank = idx + 1;
    });

    return sorted;
  }

  /**
   * Get theme benchmarks
   */
  static getThemeBenchmarks(): ThemeBenchmark[] {
    return Array.from(this.themeBenchmarks.values()).sort(
      (a, b) => b.averageEngagement - a.averageEngagement
    );
  }

  /**
   * Get recommended themes for remixing
   */
  static getRecommendedThemesForRemix(): ThemeBenchmark[] {
    return Array.from(this.themeBenchmarks.values())
      .filter((t) => t.recommendedForRemix)
      .sort((a, b) => b.averageEngagement - a.averageEngagement);
  }

  /**
   * Get game trend
   */
  static getGameTrend(gameId: string): "up" | "down" | "stable" {
    const benchmark = this.benchmarks.get(gameId);
    if (!benchmark) return "stable";

    // Simplified trend calculation
    if (benchmark.engagementScore > 8) return "up";
    if (benchmark.engagementScore < 5) return "down";
    return "stable";
  }

  /**
   * Compare games
   */
  static compareGames(gameId1: string, gameId2: string): {
    game1: GameBenchmark | null;
    game2: GameBenchmark | null;
    winner: string;
    difference: number;
  } | null {
    const game1 = this.benchmarks.get(gameId1);
    const game2 = this.benchmarks.get(gameId2);

    if (!game1 || !game2) return null;

    const difference = Math.abs(game1.engagementScore - game2.engagementScore);
    const winner = game1.engagementScore > game2.engagementScore ? gameId1 : gameId2;

    return { game1, game2, winner, difference };
  }

  /**
   * Get performance report
   */
  static getPerformanceReport(): {
    topPerformers: GameBenchmark[];
    recommendedThemes: ThemeBenchmark[];
    averageEngagement: number;
    totalGames: number;
  } {
    const allGames = Array.from(this.benchmarks.values());
    const avgEngagement =
      allGames.length > 0
        ? allGames.reduce((sum, g) => sum + g.engagementScore, 0) / allGames.length
        : 0;

    return {
      topPerformers: this.getTopPerformers(5),
      recommendedThemes: this.getRecommendedThemesForRemix(),
      averageEngagement: avgEngagement,
      totalGames: allGames.length,
    };
  }
}

export default GamePerformanceBenchmark;
