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

export interface GameDescription {
  title: string;
  tagline: string;
  shortDescription: string;
  longDescription: string;
  features: string[];
  playerAppeal: string[];
  marketingCopy: string;
  keywords: string[];
}

/**
 * AI-Powered Game Description Generator
 * Uses LLM to generate compelling game descriptions and marketing copy
 */
export class GameDescriptionGenerator {
  /**
   * Generate complete game description
   */
  static async generateDescription(gameConfig: {
    theme: string;
    rtp: number;
    volatility: string;
    paylines: number;
    bonusFeatures: string[];
    symbols: string[];
    targetAudience?: string;
  }): Promise<GameDescription> {
    const prompt = `Generate a compelling game description for a slot game with these specs:
    
Theme: ${gameConfig.theme}
RTP: ${gameConfig.rtp}%
Volatility: ${gameConfig.volatility}
Paylines: ${gameConfig.paylines}
Bonus Features: ${gameConfig.bonusFeatures.join(", ")}
Symbols: ${gameConfig.symbols.join(", ")}
Target Audience: ${gameConfig.targetAudience || "General"}

Generate a JSON response with:
{
  "title": "Catchy game title",
  "tagline": "One-liner that captures the essence",
  "shortDescription": "2-3 sentence description",
  "longDescription": "Detailed 4-5 sentence description",
  "features": ["Feature 1", "Feature 2", ...],
  "playerAppeal": ["Appeal 1", "Appeal 2", ...],
  "marketingCopy": "Persuasive marketing paragraph",
  "keywords": ["keyword1", "keyword2", ...]
}`;

    try {
      const response = await invokeLLM({
        messages: [
          {
            role: "system",
            content: "You are a creative game marketing expert. Generate compelling descriptions that appeal to slot players.",
          },
          {
            role: "user",
            content: prompt,
          },
        ],
        response_format: {
          type: "json_schema",
          json_schema: {
            name: "game_description",
            strict: true,
            schema: {
              type: "object",
              properties: {
                title: { type: "string" },
                tagline: { type: "string" },
                shortDescription: { type: "string" },
                longDescription: { type: "string" },
                features: { type: "array", items: { type: "string" } },
                playerAppeal: { type: "array", items: { type: "string" } },
                marketingCopy: { type: "string" },
                keywords: { type: "array", items: { type: "string" } },
              },
              required: [
                "title",
                "tagline",
                "shortDescription",
                "longDescription",
                "features",
                "playerAppeal",
                "marketingCopy",
                "keywords",
              ],
              additionalProperties: false,
            },
          },
        },
      });

      const content = response.choices[0].message.content;
      if (typeof content === "string") {
        return JSON.parse(content);
      }
      return content as GameDescription;
    } catch (error) {
      console.error("Error generating game description:", error);
      return this.generateFallbackDescription(gameConfig);
    }
  }

  /**
   * Generate game title
   */
  static async generateTitle(theme: string, volatility: string): Promise<string> {
    const prompt = `Generate a catchy, exciting game title for a ${volatility} volatility ${theme} themed slot game. 
    Return only the title, nothing else.`;

    try {
      const response = await invokeLLM({
        messages: [
          {
            role: "system",
            content: "You are a creative game title generator. Create exciting, memorable slot game titles.",
          },
          {
            role: "user",
            content: prompt,
          },
        ],
      });

      const content = response.choices[0].message.content;
      return typeof content === "string" ? content.trim() : "Slot Game";
    } catch {
      return `${theme} ${volatility.charAt(0).toUpperCase() + volatility.slice(1)}`;
    }
  }

  /**
   * Generate marketing tagline
   */
  static async generateTagline(theme: string, bonusFeatures: string[]): Promise<string> {
    const prompt = `Generate a one-liner tagline for a ${theme} slot game with features: ${bonusFeatures.join(", ")}.
    Make it exciting and appealing to slot players. Return only the tagline.`;

    try {
      const response = await invokeLLM({
        messages: [
          {
            role: "system",
            content: "You are a marketing copywriter. Create catchy, compelling game taglines.",
          },
          {
            role: "user",
            content: prompt,
          },
        ],
      });

      const content = response.choices[0].message.content;
      return typeof content === "string" ? content.trim() : "Experience the thrill!";
    } catch {
      return `Spin to win with ${theme}!`;
    }
  }

  /**
   * Generate feature highlights
   */
  static async generateFeatureHighlights(bonusFeatures: string[]): Promise<string[]> {
    const prompt = `For a slot game with these bonus features: ${bonusFeatures.join(", ")}
    Generate 3-4 compelling feature highlights that appeal to players. Return as JSON array of strings.`;

    try {
      const response = await invokeLLM({
        messages: [
          {
            role: "system",
            content: "You are a game feature copywriter. Highlight features in ways that excite players.",
          },
          {
            role: "user",
            content: prompt,
          },
        ],
      });

      const content = response.choices[0].message.content;
      if (typeof content === "string") {
        const parsed = JSON.parse(content);
        return Array.isArray(parsed) ? parsed : bonusFeatures;
      }
      return bonusFeatures;
    } catch {
      return bonusFeatures;
    }
  }

  /**
   * Generate fallback description
   */
  private static generateFallbackDescription(gameConfig: {
    theme: string;
    rtp: number;
    volatility: string;
    paylines: number;
    bonusFeatures: string[];
    symbols: string[];
  }): GameDescription {
    return {
      title: `${gameConfig.theme} Slots`,
      tagline: `Experience the excitement of ${gameConfig.theme}!`,
      shortDescription: `A thrilling ${gameConfig.volatility} volatility slot game with ${gameConfig.paylines} paylines and ${gameConfig.rtp}% RTP.`,
      longDescription: `Enjoy an immersive ${gameConfig.theme} themed slot experience with ${gameConfig.paylines} paylines and exciting bonus features. With a ${gameConfig.rtp}% RTP and ${gameConfig.volatility} volatility, this game offers ${gameConfig.volatility === "high" ? "big win potential" : gameConfig.volatility === "medium" ? "balanced gameplay" : "frequent smaller wins"}. Features include ${gameConfig.bonusFeatures.join(", ")}.`,
      features: gameConfig.bonusFeatures,
      playerAppeal: [
        `${gameConfig.paylines} paylines for more winning combinations`,
        `${gameConfig.volatility} volatility gameplay`,
        `${gameConfig.rtp}% RTP for fair returns`,
        `Immersive ${gameConfig.theme} theme`,
      ],
      marketingCopy: `Spin the reels and discover fortune in our ${gameConfig.theme} slot game! With ${gameConfig.paylines} paylines and exciting bonus features, every spin brings new possibilities. Join thousands of players enjoying this thrilling ${gameConfig.volatility} volatility game today!`,
      keywords: [gameConfig.theme, "slot", "bonus", "free spins", "multiplier", gameConfig.volatility],
    };
  }

  /**
   * Generate multi-language descriptions
   */
  static async generateMultiLanguageDescription(
    gameConfig: {
      theme: string;
      rtp: number;
      volatility: string;
      paylines: number;
      bonusFeatures: string[];
      symbols: string[];
    },
    languages: string[] = ["en", "es", "fr", "de"]
  ): Promise<Record<string, GameDescription>> {
    const descriptions: Record<string, GameDescription> = {};

    for (const lang of languages) {
      try {
        const prompt = `Generate a game description in ${lang === "en" ? "English" : lang === "es" ? "Spanish" : lang === "fr" ? "French" : "German"} for a slot game:
        
Theme: ${gameConfig.theme}
RTP: ${gameConfig.rtp}%
Volatility: ${gameConfig.volatility}
Paylines: ${gameConfig.paylines}
Features: ${gameConfig.bonusFeatures.join(", ")}

Return JSON with: title, tagline, shortDescription, longDescription, features, playerAppeal, marketingCopy, keywords`;

        const response = await invokeLLM({
          messages: [
            {
              role: "system",
              content: `You are a game marketing expert. Generate descriptions in ${lang}.`,
            },
            {
              role: "user",
              content: prompt,
            },
          ],
        });

        const content = response.choices[0].message.content;
        if (typeof content === "string") {
          descriptions[lang] = JSON.parse(content);
        }
      } catch (error) {
        console.error(`Error generating ${lang} description:`, error);
        descriptions[lang] = this.generateFallbackDescription(gameConfig);
      }
    }

    return descriptions;
  }
}

export default GameDescriptionGenerator;
