import GamePerformanceBenchmark, { GameBenchmark, ThemeBenchmark } from "./gamePerformanceBenchmark.ts";

export interface GameRecommendation {
  gameId: string;
  gameName: string;
  reason: string;
  recommendationType: "remix" | "new_variation" | "theme_expansion" | "performance_boost";
  confidence: number;
  expectedROI: number;
  suggestedTheme?: string;
  suggestedVariations?: string[];
}

/**
 * Game Recommendation Engine
 * Analyzes performance data to recommend games for remixing and new variations
 */
export class GameRecommendationEngine {
  /**
   * Get recommendations for game remixing
   */
  static getRemixRecommendations(): GameRecommendation[] {
    const topPerformers = GamePerformanceBenchmark.getTopPerformers(10);
    const recommendations: GameRecommendation[] = [];

    topPerformers.forEach((game) => {
      if (game.engagementScore > 8) {
        recommendations.push({
          gameId: game.gameId,
          gameName: game.gameName,
          reason: `High engagement score (${game.engagementScore.toFixed(1)}/10) - excellent candidate for remixing`,
          recommendationType: "remix",
          confidence: Math.min(game.engagementScore / 10, 1),
          expectedROI: game.revenuePerPlayer * 1.5,
          suggestedTheme: this.suggestThemeVariation(game.theme),
          suggestedVariations: this.suggestGameVariations(game),
        });
      }
    });

    return recommendations;
  }

  /**
   * Get recommendations for new game variations
   */
  static getNewVariationRecommendations(): GameRecommendation[] {
    const themeBenchmarks = GamePerformanceBenchmark.getThemeBenchmarks();
    const recommendations: GameRecommendation[] = [];

    themeBenchmarks.forEach((theme) => {
      if (theme.recommendedForRemix && theme.topPerformers.length > 0) {
        const topGame = theme.topPerformers[0];

        recommendations.push({
          gameId: `theme-${theme.theme}`,
          gameName: `${theme.theme} Variation`,
          reason: `${theme.theme} theme has high average engagement (${theme.averageEngagement.toFixed(1)}/10)`,
          recommendationType: "new_variation",
          confidence: Math.min(theme.averageEngagement / 10, 1),
          expectedROI: theme.averageEngagement * 500,
          suggestedTheme: theme.theme,
          suggestedVariations: this.suggestThemeVariations(theme.theme),
        });
      }
    });

    return recommendations;
  }

  /**
   * Get theme expansion recommendations
   */
  static getThemeExpansionRecommendations(): GameRecommendation[] {
    const themeBenchmarks = GamePerformanceBenchmark.getThemeBenchmarks();
    const recommendations: GameRecommendation[] = [];

    const underrepresentedThemes = themeBenchmarks.filter((t) => t.totalGames < 5);

    underrepresentedThemes.forEach((theme) => {
      if (theme.averageEngagement > 6) {
        recommendations.push({
          gameId: `expand-${theme.theme}`,
          gameName: `Expand ${theme.theme} Portfolio`,
          reason: `${theme.theme} has good engagement but only ${theme.totalGames} games - opportunity to expand`,
          recommendationType: "theme_expansion",
          confidence: 0.8,
          expectedROI: theme.averageEngagement * 1000,
          suggestedTheme: theme.theme,
          suggestedVariations: this.generateThemeExpansionVariations(theme.theme),
        });
      }
    });

    return recommendations;
  }

  /**
   * Get performance boost recommendations
   */
  static getPerformanceBoostRecommendations(): GameRecommendation[] {
    const allBenchmarks = GamePerformanceBenchmark.getTopPerformers(50);
    const recommendations: GameRecommendation[] = [];

    const underperformers = allBenchmarks.filter((g) => g.engagementScore < 6);

    underperformers.forEach((game) => {
      recommendations.push({
        gameId: game.gameId,
        gameName: game.gameName,
        reason: `Engagement score (${game.engagementScore.toFixed(1)}/10) below average - needs performance boost`,
        recommendationType: "performance_boost",
        confidence: 0.7,
        expectedROI: game.revenuePerPlayer * 2,
        suggestedTheme: this.suggestPerformanceBoostTheme(game.theme),
        suggestedVariations: ["Add bonus features", "Increase multipliers", "Add free spins"],
      });
    });

    return recommendations;
  }

  /**
   * Get all recommendations
   */
  static getAllRecommendations(): GameRecommendation[] {
    return [
      ...this.getRemixRecommendations(),
      ...this.getNewVariationRecommendations(),
      ...this.getThemeExpansionRecommendations(),
      ...this.getPerformanceBoostRecommendations(),
    ].sort((a, b) => b.expectedROI - a.expectedROI);
  }

  /**
   * Suggest theme variation
   */
  private static suggestThemeVariation(currentTheme: string): string {
    const themeVariations: { [key: string]: string[] } = {
      "Fruit Slots": ["Tropical Fruits", "Golden Fruits", "Neon Fruits"],
      Vegas: ["Old Vegas", "Modern Vegas", "Retro Vegas"],
      Asian: ["Dragon Themed", "Pagoda Themed", "Cherry Blossom"],
      Holiday: ["Christmas", "Halloween", "Valentine's Day"],
      Ocean: ["Deep Sea", "Tropical Beach", "Pirate Themed"],
    };

    const variations = themeVariations[currentTheme] || ["Modern Twist", "Classic Remix", "Premium Edition"];
    return variations[Math.floor(Math.random() * variations.length)];
  }

  /**
   * Suggest game variations
   */
  private static suggestGameVariations(game: GameBenchmark): string[] {
    const variations = [];

    if (game.rtp < 96) {
      variations.push("Increase RTP to 96.5%");
    }

    if (game.volatility === "low") {
      variations.push("Add medium volatility version");
    }

    if (game.paylines < 10) {
      variations.push("Create 25-payline version");
    }

    if (!variations.length) {
      variations.push("Add bonus round", "Increase multipliers", "Add progressive jackpot");
    }

    return variations.slice(0, 3);
  }

  /**
   * Suggest theme variations
   */
  private static suggestThemeVariations(theme: string): string[] {
    const variations: { [key: string]: string[] } = {
      "Fruit Slots": ["Exotic Fruits", "Lucky Fruits", "Mega Fruits"],
      Vegas: ["Downtown Vegas", "Casino Royale", "Vegas Nights"],
      Asian: ["Lucky Dragon", "Golden Temple", "Zen Garden"],
      Holiday: ["Winter Wonderland", "Spooky Season", "Love & Romance"],
      Ocean: ["Atlantis", "Treasure Hunt", "Mermaid's Fortune"],
    };

    return variations[theme] || ["Premium", "Deluxe", "Ultimate"];
  }

  /**
   * Generate theme expansion variations
   */
  private static generateThemeExpansionVariations(theme: string): string[] {
    return [
      `${theme} Classic`,
      `${theme} Deluxe`,
      `${theme} Premium`,
      `${theme} Mega`,
      `${theme} Extreme`,
    ];
  }

  /**
   * Suggest performance boost theme
   */
  private static suggestPerformanceBoostTheme(currentTheme: string): string {
    const boostThemes: { [key: string]: string } = {
      "Fruit Slots": "Golden Fruits",
      Vegas: "Vegas Nights",
      Asian: "Lucky Dragon",
      Holiday: "Winter Wonderland",
      Ocean: "Atlantis",
    };

    return boostThemes[currentTheme] || "Premium Edition";
  }
}

export default GameRecommendationEngine;
