import { invokeLLM } from "../_core/llm.ts";
import { GamePerformanceAnalytics } from "./gamePerformanceAnalytics.ts";

export interface ViralPrediction {
  gameId: string;
  gameName: string;
  theme: string;
  viralScore: number; // 0-100
  confidence: number; // 0-100
  reasoning: string;
  recommendations: string[];
}

export interface PlayerSegmentPrediction {
  segment: string;
  preferredThemes: string[];
  estimatedEngagement: number; // 0-100
  recommendedGames: string[];
}

export interface RevenueForcast {
  gameId: string;
  currentRevenue: number;
  forecastedRevenue: number;
  growthPotential: number; // Percentage
  timeframe: string;
  recommendations: string[];
}

/**
 * Predictive Analytics Engine using LLM
 */
export class PredictiveAnalyticsEngine {
  /**
   * Forecast viral potential of games using LLM analysis
   */
  static async forecastViralPotential(
    gameMetrics: any[]
  ): Promise<ViralPrediction[]> {
    try {
      const metricsJson = JSON.stringify(gameMetrics, null, 2);

      const response = await invokeLLM({
        messages: [
          {
            role: "system",
            content:
              "You are a gaming industry expert specializing in viral mechanics and player engagement. Analyze game metrics and predict viral potential.",
          },
          {
            role: "user",
            content: `Analyze these game metrics and predict viral potential for each game. Consider win rates, player retention, social engagement, and theme appeal. Return a JSON array with predictions.

Game Metrics:
${metricsJson}

For each game, provide:
- viralScore (0-100)
- confidence (0-100)
- reasoning (why this score)
- recommendations (array of 3 actionable recommendations)

Return ONLY valid JSON array, no other text.`,
          },
        ],
        response_format: {
          type: "json_schema",
          json_schema: {
            name: "viral_predictions",
            strict: true,
            schema: {
              type: "array",
              items: {
                type: "object",
                properties: {
                  gameId: { type: "string" },
                  viralScore: { type: "number" },
                  confidence: { type: "number" },
                  reasoning: { type: "string" },
                  recommendations: {
                    type: "array",
                    items: { type: "string" },
                  },
                },
                required: [
                  "gameId",
                  "viralScore",
                  "confidence",
                  "reasoning",
                  "recommendations",
                ],
              },
            },
          },
        },
      });

      const predictions = JSON.parse(response.choices[0].message.content || "[]");
      console.log(`✅ Viral predictions generated for ${predictions.length} games`);

      return predictions;
    } catch (error) {
      console.error("Error forecasting viral potential:", error);
      return [];
    }
  }

  /**
   * Predict player preferences by segment
   */
  static async predictPlayerPreferences(
    playerData: any[]
  ): Promise<PlayerSegmentPrediction[]> {
    try {
      const dataJson = JSON.stringify(playerData, null, 2);

      const response = await invokeLLM({
        messages: [
          {
            role: "system",
            content:
              "You are a player behavior analyst. Analyze player data and predict preferences by segment.",
          },
          {
            role: "user",
            content: `Analyze this player data and predict preferences by segment:

${dataJson}

Identify player segments and for each segment predict:
- Preferred themes (array)
- Estimated engagement (0-100)
- Recommended games (array of game names)

Return JSON array of predictions.`,
          },
        ],
      });

      const predictions = JSON.parse(response.choices[0].message.content || "[]");
      console.log(`✅ Player preferences predicted for ${predictions.length} segments`);

      return predictions;
    } catch (error) {
      console.error("Error predicting player preferences:", error);
      return [];
    }
  }

  /**
   * Forecast revenue impact of new themes
   */
  static async forecastRevenueImpact(
    gameId: string,
    newTheme: string,
    historicalData: any[]
  ): Promise<RevenueForcast | null> {
    try {
      const dataJson = JSON.stringify(historicalData, null, 2);

      const response = await invokeLLM({
        messages: [
          {
            role: "system",
            content:
              "You are a revenue forecasting expert for gaming platforms. Predict revenue impact of theme changes.",
          },
          {
            role: "user",
            content: `Forecast revenue impact for game ${gameId} with new theme "${newTheme}".

Historical Data:
${dataJson}

Based on similar theme changes and player preferences, predict:
- Forecasted revenue (estimate)
- Growth potential (percentage)
- Timeframe for impact
- Recommendations to maximize revenue

Return JSON with these fields.`,
          },
        ],
      });

      const forecast = JSON.parse(response.choices[0].message.content || "{}");
      console.log(`✅ Revenue forecast generated for game ${gameId}`);

      return {
        gameId,
        currentRevenue: historicalData[0]?.revenue || 0,
        forecastedRevenue: forecast.forecastedRevenue || 0,
        growthPotential: forecast.growthPotential || 0,
        timeframe: forecast.timeframe || "30 days",
        recommendations: forecast.recommendations || [],
      };
    } catch (error) {
      console.error("Error forecasting revenue impact:", error);
      return null;
    }
  }

  /**
   * Generate theme recommendations based on trends
   */
  static async generateThemeRecommendations(): Promise<string[]> {
    try {
      const response = await invokeLLM({
        messages: [
          {
            role: "system",
            content:
              "You are a gaming trend analyst. Recommend trending themes for slot games.",
          },
          {
            role: "user",
            content: `Based on current gaming trends and player preferences, recommend 5 trending themes for slot games that would have high viral potential and player engagement.

Consider:
- Current pop culture trends
- Seasonal events
- Player demographics
- Social media trends
- Viral mechanics

Return a JSON array of theme names and brief descriptions.`,
          },
        ],
      });

      const themes = JSON.parse(response.choices[0].message.content || "[]");
      console.log(`✅ Generated ${themes.length} theme recommendations`);

      return themes;
    } catch (error) {
      console.error("Error generating theme recommendations:", error);
      return [];
    }
  }

  /**
   * Predict churn risk for games
   */
  static async predictChurnRisk(gameMetrics: any[]): Promise<any[]> {
    try {
      const metricsJson = JSON.stringify(gameMetrics, null, 2);

      const response = await invokeLLM({
        messages: [
          {
            role: "system",
            content:
              "You are a player retention expert. Analyze game metrics and predict churn risk.",
          },
          {
            role: "user",
            content: `Analyze these game metrics and predict churn risk for each game:

${metricsJson}

For each game, predict:
- Churn risk (0-100, where 100 is highest risk)
- Key risk factors (array)
- Retention recommendations (array)

Return JSON array of predictions.`,
          },
        ],
      });

      const predictions = JSON.parse(response.choices[0].message.content || "[]");
      console.log(`✅ Churn risk predictions generated`);

      return predictions;
    } catch (error) {
      console.error("Error predicting churn risk:", error);
      return [];
    }
  }

  /**
   * Get comprehensive predictions dashboard
   */
  static async getPredictionsDashboard(): Promise<any> {
    try {
      const topPerformers =
        await GamePerformanceAnalytics.getTopPerformersForRemix(5);

      const viralPredictions = await this.forecastViralPotential(topPerformers);
      const themeRecommendations = await this.generateThemeRecommendations();
      const churnRisks = await this.predictChurnRisk(topPerformers);

      return {
        timestamp: new Date(),
        viralPredictions,
        themeRecommendations,
        churnRisks,
        summary: {
          topViralGame: viralPredictions[0],
          recommendedThemes: themeRecommendations.slice(0, 3),
          highRiskGames: churnRisks.filter((r: any) => r.churnRisk > 70),
        },
      };
    } catch (error) {
      console.error("Error getting predictions dashboard:", error);
      return null;
    }
  }
}

export default PredictiveAnalyticsEngine;
