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

export interface SeasonalGameTemplate {
  theme: string;
  symbols: string[];
  bonusFeatures: string[];
  rtp: number;
  volatility: "low" | "medium" | "high";
  paylines: number;
  reels: number;
  description: string;
}

export interface GeneratedSeasonalGame {
  gameId: string;
  name: string;
  theme: string;
  template: SeasonalGameTemplate;
  assets: {
    symbols: string[];
    background: string;
    animations: string[];
  };
  mechanics: {
    bonusRound: string;
    freeSpins: number;
    multiplier: number;
  };
  eventId: string;
}

/**
 * Seasonal Game Generator
 */
export class SeasonalGameGenerator {
  /**
   * Generate seasonal game template from theme
   */
  static async generateGameTemplate(
    theme: string,
    eventName: string
  ): Promise<SeasonalGameTemplate | null> {
    try {
      const response = await invokeLLM({
        messages: [
          {
            role: "system",
            content:
              "You are a slot game designer. Create detailed game templates with themes, symbols, and mechanics.",
          },
          {
            role: "user",
            content: `Design a slot game template for the theme "${theme}" for the event "${eventName}".

Create a JSON response with:
- symbols: Array of 5-6 thematic symbols (e.g., ["Golden Egg", "Spring Flower", "Bunny"])
- bonusFeatures: Array of 2-3 bonus features (e.g., ["Free Spins", "Multiplier", "Bonus Round"])
- rtp: RTP percentage (96.0-98.0)
- volatility: "low", "medium", or "high"
- paylines: Number of paylines (5, 10, 15, 20, or 25)
- reels: Number of reels (3, 4, or 5)
- description: One sentence description

Return ONLY valid JSON.`,
          },
        ],
        response_format: {
          type: "json_schema",
          json_schema: {
            name: "game_template",
            strict: true,
            schema: {
              type: "object",
              properties: {
                symbols: {
                  type: "array",
                  items: { type: "string" },
                },
                bonusFeatures: {
                  type: "array",
                  items: { type: "string" },
                },
                rtp: { type: "number" },
                volatility: { type: "string" },
                paylines: { type: "number" },
                reels: { type: "number" },
                description: { type: "string" },
              },
              required: [
                "symbols",
                "bonusFeatures",
                "rtp",
                "volatility",
                "paylines",
                "reels",
                "description",
              ],
            },
          },
        },
      });

      const templateData = JSON.parse(response.choices[0].message.content || "{}");

      return {
        theme,
        symbols: templateData.symbols || [],
        bonusFeatures: templateData.bonusFeatures || [],
        rtp: templateData.rtp || 96.5,
        volatility: templateData.volatility || "medium",
        paylines: templateData.paylines || 20,
        reels: templateData.reels || 5,
        description: templateData.description || `${theme} themed slot game`,
      };
    } catch (error) {
      console.error("Error generating game template:", error);
      return null;
    }
  }

  /**
   * Generate game variations from template
   */
  static async generateGameVariations(
    template: SeasonalGameTemplate,
    baseTheme: string,
    count: number = 3
  ): Promise<GeneratedSeasonalGame[]> {
    try {
      const variations: GeneratedSeasonalGame[] = [];

      for (let i = 0; i < count; i++) {
        const variationName = [
          `${baseTheme} Classic`,
          `${baseTheme} Deluxe`,
          `${baseTheme} Premium`,
        ][i] || `${baseTheme} Variation ${i + 1}`;

        const game: GeneratedSeasonalGame = {
          gameId: `seasonal-${baseTheme.toLowerCase().replace(/\s/g, "-")}-${i}`,
          name: variationName,
          theme: baseTheme,
          template,
          assets: {
            symbols: template.symbols.map((s) => `${s.toLowerCase().replace(/\s/g, "-")}.png`),
            background: `${baseTheme.toLowerCase().replace(/\s/g, "-")}-bg.png`,
            animations: [
              "spin-animation",
              "win-animation",
              "bonus-animation",
            ],
          },
          mechanics: {
            bonusRound: template.bonusFeatures[0] || "Free Spins",
            freeSpins: 10 + i * 5,
            multiplier: 1.5 + i * 0.5,
          },
          eventId: `event-${baseTheme.toLowerCase().replace(/\s/g, "-")}`,
        };

        variations.push(game);
      }

      console.log(`✅ Generated ${variations.length} game variations for ${baseTheme}`);
      return variations;
    } catch (error) {
      console.error("Error generating game variations:", error);
      return [];
    }
  }

  /**
   * Generate complete seasonal game package
   */
  static async generateSeasonalGamePackage(
    theme: string,
    eventName: string,
    variationCount: number = 3
  ): Promise<GeneratedSeasonalGame[] | null> {
    try {
      console.log(`🎮 Generating seasonal game package for ${theme}...`);

      // Generate template
      const template = await this.generateGameTemplate(theme, eventName);
      if (!template) return null;

      // Generate variations
      const variations = await this.generateGameVariations(template, theme, variationCount);

      console.log(`✅ Generated complete package: ${theme} (${variations.length} variations)`);
      return variations;
    } catch (error) {
      console.error("Error generating seasonal game package:", error);
      return null;
    }
  }

  /**
   * Generate asset descriptions for game
   */
  static async generateAssetDescriptions(
    theme: string,
    symbols: string[]
  ): Promise<Record<string, string>> {
    try {
      const response = await invokeLLM({
        messages: [
          {
            role: "system",
            content:
              "You are a game artist. Describe visual assets for slot game symbols.",
          },
          {
            role: "user",
            content: `Create visual descriptions for these ${theme} themed slot symbols: ${symbols.join(", ")}

For each symbol, provide a detailed visual description suitable for an AI image generator.
Return JSON with symbol names as keys and descriptions as values.`,
          },
        ],
      });

      const descriptions = JSON.parse(response.choices[0].message.content || "{}");
      return descriptions;
    } catch (error) {
      console.error("Error generating asset descriptions:", error);
      return {};
    }
  }

  /**
   * Generate bonus round mechanics
   */
  static async generateBonusRound(
    theme: string,
    bonusFeatures: string[]
  ): Promise<any> {
    try {
      const response = await invokeLLM({
        messages: [
          {
            role: "system",
            content:
              "You are a game designer. Design engaging bonus round mechanics for slot games.",
          },
          {
            role: "user",
            content: `Design a bonus round for a ${theme} themed slot game with these features: ${bonusFeatures.join(", ")}

Create a JSON response with:
- name: Bonus round name
- description: How it works
- triggerCondition: What triggers the bonus
- rewards: Array of possible rewards
- duration: Number of spins or time limit
- multiplier: Win multiplier during bonus

Return ONLY valid JSON.`,
          },
        ],
      });

      const bonusRound = JSON.parse(response.choices[0].message.content || "{}");
      return bonusRound;
    } catch (error) {
      console.error("Error generating bonus round:", error);
      return null;
    }
  }

  /**
   * Get seasonal game recommendations
   */
  static async getSeasonalRecommendations(
    upcomingHolidays: string[]
  ): Promise<any[]> {
    try {
      const response = await invokeLLM({
        messages: [
          {
            role: "system",
            content:
              "You are a gaming industry expert. Recommend game themes based on upcoming holidays.",
          },
          {
            role: "user",
            content: `For these upcoming holidays: ${upcomingHolidays.join(", ")}

Recommend the best slot game themes that would have high viral potential and player engagement.
Consider current trends, player preferences, and viral mechanics.

Return a JSON array with:
- holiday: Holiday name
- recommendedThemes: Array of 3-5 theme recommendations
- viralPotential: Score 0-100
- targetAudience: Description of target players
- marketingAngle: Marketing message

Return ONLY valid JSON array.`,
          },
        ],
      });

      const recommendations = JSON.parse(response.choices[0].message.content || "[]");
      return recommendations;
    } catch (error) {
      console.error("Error getting seasonal recommendations:", error);
      return [];
    }
  }

  /**
   * Generate game code from template
   */
  static async generateGameCode(
    template: SeasonalGameTemplate
  ): Promise<string> {
    try {
      const response = await invokeLLM({
        messages: [
          {
            role: "system",
            content:
              "You are a game developer. Generate TypeScript game code for slot machines.",
          },
          {
            role: "user",
            content: `Generate TypeScript code for a slot game with these specs:
- Theme: ${template.description}
- Symbols: ${template.symbols.join(", ")}
- Reels: ${template.reels}
- Paylines: ${template.paylines}
- RTP: ${template.rtp}%
- Volatility: ${template.volatility}
- Bonus Features: ${template.bonusFeatures.join(", ")}

Generate a complete game class with spin logic, win calculation, and bonus features.`,
          },
        ],
      });

      const code = response.choices[0].message.content || "";
      return code;
    } catch (error) {
      console.error("Error generating game code:", error);
      return "";
    }
  }
}

export default SeasonalGameGenerator;
