import { PredictiveAnalyticsEngine } from "./predictiveAnalyticsEngine.ts";
import GameRemizerBot from "./gameRemizerBotService.ts";

export interface SeasonalEvent {
  id: string;
  name: string;
  theme: string;
  startDate: Date;
  endDate: Date;
  description: string;
  viralPrediction: number; // 0-100
  generatedGames: string[];
  status: "scheduled" | "active" | "completed" | "cancelled";
  createdAt: Date;
}

export interface HolidayTheme {
  name: string;
  date: string; // MM-DD format
  themes: string[];
  viralTrend: "rising" | "peak" | "declining";
  recommendedGameCount: number;
  description: string;
}

export interface SeasonalGameConfig {
  eventId: string;
  baseTheme: string;
  variations: string[];
  rtp: number;
  volatility: string;
  bonusMultiplier: number;
}

/**
 * Seasonal Event Automation System
 */
export class SeasonalEventAutomation {
  private static events: Map<string, SeasonalEvent> = new Map();
  private static holidays: HolidayTheme[] = [
    {
      name: "New Year",
      date: "01-01",
      themes: ["Fireworks", "Champagne Celebration", "Lucky Numbers", "Golden Future"],
      viralTrend: "peak",
      recommendedGameCount: 5,
      description: "New Year celebration with lucky and prosperity themes",
    },
    {
      name: "Valentine's Day",
      date: "02-14",
      themes: ["Love & Romance", "Cupid's Arrow", "Heart Treasures", "Romantic Getaway"],
      viralTrend: "peak",
      recommendedGameCount: 4,
      description: "Love-themed games for Valentine's Day",
    },
    {
      name: "St. Patrick's Day",
      date: "03-17",
      themes: ["Lucky Leprechaun", "Pot of Gold", "Irish Luck", "Rainbow Riches"],
      viralTrend: "peak",
      recommendedGameCount: 4,
      description: "Irish luck and fortune themes",
    },
    {
      name: "Easter",
      date: "04-09",
      themes: ["Easter Eggs", "Spring Blossoms", "Bunny Bonanza", "Egg Hunt Treasures"],
      viralTrend: "peak",
      recommendedGameCount: 4,
      description: "Easter egg and spring celebration themes",
    },
    {
      name: "Summer",
      date: "06-21",
      themes: ["Beach Paradise", "Tropical Vibes", "Summer Splash", "Sun & Sand"],
      viralTrend: "rising",
      recommendedGameCount: 5,
      description: "Summer vacation and beach themes",
    },
    {
      name: "Halloween",
      date: "10-31",
      themes: ["Spooky Spirits", "Haunted House", "Witch's Brew", "Monster Mash", "Vampire's Gold"],
      viralTrend: "peak",
      recommendedGameCount: 5,
      description: "Halloween spooky and scary themes",
    },
    {
      name: "Thanksgiving",
      date: "11-23",
      themes: ["Harvest Bounty", "Turkey Feast", "Gratitude Gold", "Cornucopia"],
      viralTrend: "rising",
      recommendedGameCount: 4,
      description: "Thanksgiving harvest themes",
    },
    {
      name: "Christmas",
      date: "12-25",
      themes: ["Merry Christmas", "Santa's Sleigh", "Winter Wonderland", "Festive Cheer", "Reindeer Riches"],
      viralTrend: "peak",
      recommendedGameCount: 5,
      description: "Christmas and holiday celebration themes",
    },
  ];

  /**
   * Initialize seasonal event system
   */
  static async initialize(): Promise<void> {
    console.log("🎄 Initializing Seasonal Event Automation System");

    // Schedule daily check for upcoming events
    setInterval(() => {
      this.checkAndScheduleUpcomingEvents();
    }, 24 * 60 * 60 * 1000);

    // Check immediately on startup
    await this.checkAndScheduleUpcomingEvents();

    console.log("✅ Seasonal Event Automation System initialized");
  }

  /**
   * Check for upcoming holidays and schedule events
   */
  static async checkAndScheduleUpcomingEvents(): Promise<SeasonalEvent[]> {
    try {
      const createdEvents: SeasonalEvent[] = [];
      const today = new Date();

      for (const holiday of this.holidays) {
        const [month, day] = holiday.date.split("-");
        const holidayDate = new Date(today.getFullYear(), parseInt(month) - 1, parseInt(day));

        // Check if holiday is within next 30 days
        const daysUntilHoliday = Math.floor(
          (holidayDate.getTime() - today.getTime()) / (1000 * 60 * 60 * 24)
        );

        if (daysUntilHoliday >= 0 && daysUntilHoliday <= 30) {
          // Check if event already exists
          const existingEvent = Array.from(this.events.values()).find(
            (e) =>
              e.name === holiday.name &&
              e.startDate.getFullYear() === today.getFullYear()
          );

          if (!existingEvent) {
            const event = await this.createSeasonalEvent(holiday, holidayDate);
            if (event) {
              createdEvents.push(event);
            }
          }
        }
      }

      if (createdEvents.length > 0) {
        console.log(`🎉 Created ${createdEvents.length} seasonal events`);
      }

      return createdEvents;
    } catch (error) {
      console.error("Error checking and scheduling events:", error);
      return [];
    }
  }

  /**
   * Create a seasonal event with generated games
   */
  static async createSeasonalEvent(
    holiday: HolidayTheme,
    eventDate: Date
  ): Promise<SeasonalEvent | null> {
    try {
      const eventId = `event-${holiday.name.toLowerCase().replace(/\s/g, "-")}-${eventDate.getFullYear()}`;

      // Get viral prediction for this holiday
      const predictions = await PredictiveAnalyticsEngine.forecastViralPotential([
        { theme: holiday.themes[0], description: holiday.description },
      ]);

      const viralScore = predictions[0]?.viralScore || 75;

      // Calculate event duration (typically 2 weeks before to 1 day after)
      const startDate = new Date(eventDate);
      startDate.setDate(startDate.getDate() - 14);

      const endDate = new Date(eventDate);
      endDate.setDate(endDate.getDate() + 1);

      const event: SeasonalEvent = {
        id: eventId,
        name: holiday.name,
        theme: holiday.themes[0],
        startDate,
        endDate,
        description: holiday.description,
        viralPrediction: viralScore,
        generatedGames: [],
        status: "scheduled",
        createdAt: new Date(),
      };

      // Generate games for this event
      const generatedGames = await this.generateSeasonalGames(
        event,
        holiday.themes,
        holiday.recommendedGameCount
      );

      event.generatedGames = generatedGames;

      this.events.set(eventId, event);

      console.log(`🎮 Created seasonal event: ${holiday.name} (${generatedGames.length} games)`);

      return event;
    } catch (error) {
      console.error("Error creating seasonal event:", error);
      return null;
    }
  }

  /**
   * Generate seasonal games for an event
   */
  static async generateSeasonalGames(
    event: SeasonalEvent,
    themes: string[],
    count: number
  ): Promise<string[]> {
    try {
      const generatedGameIds: string[] = [];

      for (let i = 0; i < Math.min(count, themes.length); i++) {
        const theme = themes[i];
        const gameConfig: SeasonalGameConfig = {
          eventId: event.id,
          baseTheme: theme,
          variations: [`${theme} Classic`, `${theme} Deluxe`, `${theme} Premium`],
          rtp: 96.5 + Math.random() * 2, // 96.5-98.5%
          volatility: i % 2 === 0 ? "medium" : "high",
          bonusMultiplier: 1.5 + i * 0.25, // 1.5x to 2.25x
        };

        // Generate game using remix bot
        const game = await GameRemizerBot.generateRemix(
          `seasonal-${event.id}-${i}`,
          `${theme} - ${event.name} ${event.startDate.getFullYear()}`
        );

        if (game) {
          generatedGameIds.push(game.gameId);
          console.log(`✅ Generated seasonal game: ${theme}`);
        }
      }

      return generatedGameIds;
    } catch (error) {
      console.error("Error generating seasonal games:", error);
      return [];
    }
  }

  /**
   * Activate an event (make games live)
   */
  static async activateEvent(eventId: string): Promise<boolean> {
    try {
      const event = this.events.get(eventId);
      if (!event) return false;

      event.status = "active";
      this.events.set(eventId, event);

      console.log(`🚀 Activated seasonal event: ${event.name}`);
      return true;
    } catch (error) {
      console.error("Error activating event:", error);
      return false;
    }
  }

  /**
   * Complete an event (archive games)
   */
  static async completeEvent(eventId: string): Promise<boolean> {
    try {
      const event = this.events.get(eventId);
      if (!event) return false;

      event.status = "completed";
      this.events.set(eventId, event);

      console.log(`✅ Completed seasonal event: ${event.name}`);
      return true;
    } catch (error) {
      console.error("Error completing event:", error);
      return false;
    }
  }

  /**
   * Get all events
   */
  static getAllEvents(): SeasonalEvent[] {
    return Array.from(this.events.values());
  }

  /**
   * Get active events
   */
  static getActiveEvents(): SeasonalEvent[] {
    return Array.from(this.events.values()).filter((e) => e.status === "active");
  }

  /**
   * Get upcoming events
   */
  static getUpcomingEvents(days: number = 30): SeasonalEvent[] {
    const today = new Date();
    const futureDate = new Date(today.getTime() + days * 24 * 60 * 60 * 1000);

    return Array.from(this.events.values()).filter(
      (e) => e.startDate >= today && e.startDate <= futureDate && e.status === "scheduled"
    );
  }

  /**
   * Get event by ID
   */
  static getEvent(eventId: string): SeasonalEvent | null {
    return this.events.get(eventId) || null;
  }

  /**
   * Get statistics
   */
  static getStats() {
    const events = Array.from(this.events.values());
    const scheduled = events.filter((e) => e.status === "scheduled").length;
    const active = events.filter((e) => e.status === "active").length;
    const completed = events.filter((e) => e.status === "completed").length;

    const totalGames = events.reduce((sum, e) => sum + e.generatedGames.length, 0);
    const avgViralScore =
      events.length > 0
        ? events.reduce((sum, e) => sum + e.viralPrediction, 0) / events.length
        : 0;

    return {
      totalEvents: events.length,
      scheduled,
      active,
      completed,
      totalGames,
      avgViralScore: avgViralScore.toFixed(1),
    };
  }

  /**
   * Get holidays list
   */
  static getHolidays(): HolidayTheme[] {
    return this.holidays;
  }

  /**
   * Get next upcoming holiday
   */
  static getNextHoliday(): HolidayTheme | null {
    const today = new Date();
    const currentMonth = today.getMonth() + 1;
    const currentDay = today.getDate();

    // Find next holiday
    for (const holiday of this.holidays) {
      const [month, day] = holiday.date.split("-");
      const monthNum = parseInt(month);
      const dayNum = parseInt(day);

      if (monthNum > currentMonth || (monthNum === currentMonth && dayNum >= currentDay)) {
        return holiday;
      }
    }

    // If no holiday found this year, return first holiday of next year
    return this.holidays[0];
  }

  /**
   * Manually create event for a specific holiday
   */
  static async manuallyCreateEvent(holidayName: string): Promise<SeasonalEvent | null> {
    try {
      const holiday = this.holidays.find((h) => h.name === holidayName);
      if (!holiday) return null;

      const [month, day] = holiday.date.split("-");
      const eventDate = new Date(new Date().getFullYear(), parseInt(month) - 1, parseInt(day));

      return await this.createSeasonalEvent(holiday, eventDate);
    } catch (error) {
      console.error("Error manually creating event:", error);
      return null;
    }
  }
}

export default SeasonalEventAutomation;
