import { router, protectedProcedure, adminProcedure } from '../_core/trpc.ts';
import { z } from 'zod';
import { TRPCError } from '@trpc/server';

/**
 * Game Recommendations Router
 * Provides personalized game recommendations based on player behavior and preferences
 */
export const gameRecommendationsRouter = router({
  /**
   * Get personalized game recommendations for a player
   */
  getRecommendations: protectedProcedure
    .input(
      z.object({
        limit: z.number().default(5),
        excludePlayedGames: z.boolean().default(true),
      })
    )
    .query(async ({ ctx, input }) => {
      // In production, this would use ML models and player history
      const recommendations = [
        {
          gameId: 'game_001',
          title: 'Crystal Cascade',
          genre: 'slot',
          matchPercentage: 92,
          reason: 'Based on your preference for medium volatility games with bonus features',
          thumbnail: 'https://example.com/crystal-cascade.jpg',
          rtp: 96.5,
          volatility: 'medium',
        },
        {
          gameId: 'game_002',
          title: "Dragon's Hoard",
          genre: 'slot',
          matchPercentage: 87,
          reason: 'You\'ve enjoyed similar games with sticky wilds and bonus picks',
          thumbnail: 'https://example.com/dragons-hoard.jpg',
          rtp: 95.8,
          volatility: 'medium-high',
        },
        {
          gameId: 'game_003',
          title: 'Neon Lights',
          genre: 'slot',
          matchPercentage: 84,
          reason: 'High engagement players like you love the excitement of dynamic paylines',
          thumbnail: 'https://example.com/neon-lights.jpg',
          rtp: 96.2,
          volatility: 'high',
        },
      ];

      return recommendations.slice(0, input.limit);
    }),

  /**
   * Get recommendations by genre
   */
  getRecommendationsByGenre: protectedProcedure
    .input(
      z.object({
        genre: z.enum(['slot', 'puzzle', 'action', 'strategy', 'arcade', 'card']),
        limit: z.number().default(5),
      })
    )
    .query(async ({ ctx, input }) => {
      // Mock data - in production, would query database
      const genreGames: Record<string, any[]> = {
        slot: [
          { gameId: 'slot_001', title: 'Crystal Cascade', matchPercentage: 92 },
          { gameId: 'slot_002', title: "Dragon's Hoard", matchPercentage: 87 },
          { gameId: 'slot_003', title: 'Neon Lights', matchPercentage: 84 },
        ],
        puzzle: [
          { gameId: 'puzzle_001', title: 'Block Master', matchPercentage: 78 },
          { gameId: 'puzzle_002', title: 'Match Mania', matchPercentage: 75 },
        ],
        action: [
          { gameId: 'action_001', title: 'Space Invaders', matchPercentage: 82 },
          { gameId: 'action_002', title: 'Asteroid Rush', matchPercentage: 79 },
        ],
      };

      return (genreGames[input.genre] || []).slice(0, input.limit);
    }),

  /**
   * Get trending games
   */
  getTrendingGames: protectedProcedure
    .input(z.object({ limit: z.number().default(10) }))
    .query(async ({ ctx, input }) => {
      return [
        { gameId: 'trending_001', title: 'Crystal Cascade', players: 2500, avgPlayTime: 15, trend: 'up' },
        { gameId: 'trending_002', title: "Dragon's Hoard", players: 2200, avgPlayTime: 18, trend: 'up' },
        { gameId: 'trending_003', title: 'Neon Lights', players: 1800, avgPlayTime: 12, trend: 'stable' },
      ].slice(0, input.limit);
    }),

  /**
   * Get new games
   */
  getNewGames: protectedProcedure
    .input(z.object({ limit: z.number().default(5) }))
    .query(async ({ ctx, input }) => {
      return [
        { gameId: 'new_001', title: 'Treasure Hunt', releaseDate: '2024-04-20', genre: 'slot' },
        { gameId: 'new_002', title: 'Cosmic Reels', releaseDate: '2024-04-18', genre: 'slot' },
        { gameId: 'new_003', title: 'Galaxy Rush', releaseDate: '2024-04-15', genre: 'action' },
      ].slice(0, input.limit);
    }),

  /**
   * Get player's favorite games
   */
  getFavoriteGames: protectedProcedure
    .input(z.object({ limit: z.number().default(5) }))
    .query(async ({ ctx, input }) => {
      // In production, query player's favorite games from database
      return [
        { gameId: 'fav_001', title: 'Crystal Cascade', plays: 145, avgWin: 250, lastPlayed: '2 hours ago' },
        { gameId: 'fav_002', title: "Dragon's Hoard", plays: 98, avgWin: 320, lastPlayed: '1 day ago' },
        { gameId: 'fav_003', title: 'Neon Lights', plays: 67, avgWin: 180, lastPlayed: '3 days ago' },
      ].slice(0, input.limit);
    }),

  /**
   * Get similar games to a given game
   */
  getSimilarGames: protectedProcedure
    .input(
      z.object({
        gameId: z.string(),
        limit: z.number().default(5),
      })
    )
    .query(async ({ ctx, input }) => {
      // In production, use ML similarity scoring
      return [
        { gameId: 'similar_001', title: 'Similar Game 1', similarity: 0.92 },
        { gameId: 'similar_002', title: 'Similar Game 2', similarity: 0.87 },
        { gameId: 'similar_003', title: 'Similar Game 3', similarity: 0.84 },
      ].slice(0, input.limit);
    }),

  /**
   * Track recommendation click
   */
  trackRecommendationClick: protectedProcedure
    .input(
      z.object({
        gameId: z.string(),
        recommendationType: z.enum(['personalized', 'trending', 'new', 'similar']),
      })
    )
    .mutation(async ({ ctx, input }) => {
      // In production, track this for analytics
      return { success: true, tracked: true };
    }),

  /**
   * Get recommendation analytics (admin)
   */
  getRecommendationAnalytics: adminProcedure
    .input(
      z.object({
        startDate: z.date().optional(),
        endDate: z.date().optional(),
      })
    )
    .query(async ({ ctx, input }) => {
      return {
        totalRecommendations: 15420,
        totalClicks: 3850,
        clickThroughRate: 0.25,
        topRecommendedGames: [
          { gameId: 'game_001', title: 'Crystal Cascade', recommendations: 1200, clicks: 450 },
          { gameId: 'game_002', title: "Dragon's Hoard", recommendations: 980, clicks: 380 },
          { gameId: 'game_003', title: 'Neon Lights', recommendations: 850, clicks: 290 },
        ],
        recommendationTypes: {
          personalized: 0.45,
          trending: 0.25,
          new: 0.2,
          similar: 0.1,
        },
      };
    }),

  /**
   * Update recommendation algorithm weights (admin)
   */
  updateAlgorithmWeights: adminProcedure
    .input(
      z.object({
        engagementWeight: z.number().min(0).max(1),
        spendingWeight: z.number().min(0).max(1),
        genreWeight: z.number().min(0).max(1),
        rtpWeight: z.number().min(0).max(1),
        volatilityWeight: z.number().min(0).max(1),
      })
    )
    .mutation(async ({ ctx, input }) => {
      // In production, save these weights to database
      return {
        success: true,
        weights: input,
      };
    }),
});
