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

interface GameAnalysisResult {
  name: string;
  description: string;
  rtp: number;
  volatility: "low" | "medium" | "high";
  paylines: number;
  reels: number;
  minBet: number;
  maxBet: number;
  bonusFeatures: string[];
  symbols: Array<{
    name: string;
    multiplier: number;
    description: string;
  }>;
  theme: string;
  assetPrompt: string;
}

/**
 * Enhanced Game Builder Service with Real LLM Analysis
 */
export class EnhancedGameBuilderLLM {
  /**
   * Analyze game from URL using LLM
   */
  static async analyzeGameFromUrl(gameUrl: string): Promise<GameAnalysisResult | null> {
    try {
      console.log(`🔍 Analyzing game from URL: ${gameUrl}`);

      // Fetch game HTML
      const gameHtml = await this.fetchGameHtml(gameUrl);
      if (!gameHtml) {
        console.error("Failed to fetch game HTML");
        return null;
      }

      // Use LLM to analyze game mechanics
      const analysis = await this.analyzeGameMechanics(gameHtml, gameUrl);
      return analysis;
    } catch (error) {
      console.error("Error analyzing game:", error);
      return null;
    }
  }

  /**
   * Fetch game HTML from URL
   */
  private static async fetchGameHtml(gameUrl: string): Promise<string | null> {
    try {
      const response = await fetch(gameUrl, {
        headers: {
          "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
        },
      });

      if (!response.ok) {
        return null;
      }

      return await response.text();
    } catch (error) {
      console.error("Error fetching game HTML:", error);
      return null;
    }
  }

  /**
   * Analyze game mechanics using LLM
   */
  private static async analyzeGameMechanics(
    gameHtml: string,
    gameUrl: string
  ): Promise<GameAnalysisResult | null> {
    try {
      // Extract key content from HTML (first 5000 chars to avoid token limits)
      const htmlSnippet = gameHtml.substring(0, 5000);

      const response = await invokeLLM({
        messages: [
          {
            role: "system",
            content: `You are an expert slot game analyst. Analyze the provided game HTML and extract detailed information about the slot game mechanics. Return a JSON object with the following structure:
{
  "name": "Game Name",
  "description": "Brief description",
  "rtp": 96.5,
  "volatility": "medium",
  "paylines": 20,
  "reels": 5,
  "minBet": 0.1,
  "maxBet": 100,
  "bonusFeatures": ["Free Spins", "Wild Symbol", "Scatter Bonus"],
  "symbols": [
    {"name": "Gold Bar", "multiplier": 5, "description": "High value symbol"},
    {"name": "Diamond", "multiplier": 3, "description": "Medium value symbol"}
  ],
  "theme": "luxury",
  "assetPrompt": "Luxury slot game with gold bars, diamonds, and royal symbols"
}`,
          },
          {
            role: "user",
            content: `Analyze this slot game from ${gameUrl}:\n\n${htmlSnippet}`,
          },
        ],
        response_format: {
          type: "json_schema",
          json_schema: {
            name: "game_analysis",
            strict: true,
            schema: {
              type: "object",
              properties: {
                name: { type: "string" },
                description: { type: "string" },
                rtp: { type: "number" },
                volatility: { type: "string", enum: ["low", "medium", "high"] },
                paylines: { type: "number" },
                reels: { type: "number" },
                minBet: { type: "number" },
                maxBet: { type: "number" },
                bonusFeatures: { type: "array", items: { type: "string" } },
                symbols: {
                  type: "array",
                  items: {
                    type: "object",
                    properties: {
                      name: { type: "string" },
                      multiplier: { type: "number" },
                      description: { type: "string" },
                    },
                    required: ["name", "multiplier", "description"],
                  },
                },
                theme: { type: "string" },
                assetPrompt: { type: "string" },
              },
              required: [
                "name",
                "description",
                "rtp",
                "volatility",
                "paylines",
                "reels",
                "minBet",
                "maxBet",
                "bonusFeatures",
                "symbols",
                "theme",
                "assetPrompt",
              ],
            },
          },
        },
      });

      // Parse LLM response
      if (response.choices[0]?.message?.content) {
        const content = response.choices[0].message.content;
        const analysis = JSON.parse(content) as GameAnalysisResult;
        console.log(`✅ Analyzed game: ${analysis.name}`);
        return analysis;
      }

      return null;
    } catch (error) {
      console.error("Error analyzing game mechanics with LLM:", error);
      return null;
    }
  }

  /**
   * Generate game variations from analysis
   */
  static async generateGameVariations(
    baseAnalysis: GameAnalysisResult,
    variationCount: number = 3
  ): Promise<GameAnalysisResult[]> {
    try {
      console.log(`🎮 Generating ${variationCount} variations of ${baseAnalysis.name}`);

      const variations: GameAnalysisResult[] = [];

      for (let i = 0; i < variationCount; i++) {
        const variation = await this.createGameVariation(baseAnalysis, i + 1);
        if (variation) {
          variations.push(variation);
        }
      }

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

  /**
   * Create a single game variation
   */
  private static async createGameVariation(
    baseAnalysis: GameAnalysisResult,
    variationNumber: number
  ): Promise<GameAnalysisResult | null> {
    try {
      const response = await invokeLLM({
        messages: [
          {
            role: "system",
            content: `You are a creative slot game designer. Create a variation of a slot game with a different theme while maintaining similar mechanics. Return a JSON object with the same structure as the original game analysis.`,
          },
          {
            role: "user",
            content: `Create variation ${variationNumber} of "${baseAnalysis.name}" with a different theme. Original theme: ${baseAnalysis.theme}. Original RTP: ${baseAnalysis.rtp}%. Vary the theme, symbols, and asset prompt while keeping the same RTP and mechanics.`,
          },
        ],
        response_format: {
          type: "json_schema",
          json_schema: {
            name: "game_variation",
            strict: true,
            schema: {
              type: "object",
              properties: {
                name: { type: "string" },
                description: { type: "string" },
                rtp: { type: "number" },
                volatility: { type: "string", enum: ["low", "medium", "high"] },
                paylines: { type: "number" },
                reels: { type: "number" },
                minBet: { type: "number" },
                maxBet: { type: "number" },
                bonusFeatures: { type: "array", items: { type: "string" } },
                symbols: {
                  type: "array",
                  items: {
                    type: "object",
                    properties: {
                      name: { type: "string" },
                      multiplier: { type: "number" },
                      description: { type: "string" },
                    },
                    required: ["name", "multiplier", "description"],
                  },
                },
                theme: { type: "string" },
                assetPrompt: { type: "string" },
              },
              required: [
                "name",
                "description",
                "rtp",
                "volatility",
                "paylines",
                "reels",
                "minBet",
                "maxBet",
                "bonusFeatures",
                "symbols",
                "theme",
                "assetPrompt",
              ],
            },
          },
        },
      });

      if (response.choices[0]?.message?.content) {
        const content = response.choices[0].message.content;
        const variation = JSON.parse(content) as GameAnalysisResult;
        console.log(`✅ Created variation: ${variation.name}`);
        return variation;
      }

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

  /**
   * Generate asset descriptions for AI image generation
   */
  static async generateAssetDescriptions(analysis: GameAnalysisResult): Promise<string[]> {
    try {
      const prompts: string[] = [];

      // Main game background
      prompts.push(analysis.assetPrompt);

      // Symbol assets
      for (const symbol of analysis.symbols) {
        prompts.push(`Slot game symbol: ${symbol.name} - ${symbol.description}`);
      }

      // Bonus feature assets
      for (const feature of analysis.bonusFeatures) {
        prompts.push(`Slot game bonus feature: ${feature}`);
      }

      return prompts;
    } catch (error) {
      console.error("Error generating asset descriptions:", error);
      return [];
    }
  }
}

export default EnhancedGameBuilderLLM;
