import { invokeLLM } from "../_core/llm.ts";
import { db } from "../db.ts";
import { allGames } from "../../drizzle/schema.ts";

export interface PendingGame {
  id: string;
  name: string;
  theme: string;
  sourceUrl: string;
  analysis: any;
  config: any;
  code: string;
  thumbnail: string;
  status: "pending" | "approved" | "rejected";
  createdBy: number;
  createdAt: Date;
  reviewedBy?: number;
  reviewedAt?: Date;
  reviewNotes?: string;
}

/**
 * Enhanced Game Builder Service with real LLM analysis
 */
export class EnhancedGameBuilder {
  /**
   * Analyze game from URL using real LLM with vision capabilities
   */
  static async analyzeGameWithLLM(gameUrl: string): Promise<any> {
    const prompt = `You are an expert slot game analyst. Analyze the game at this URL and extract detailed game mechanics.

Game URL: ${gameUrl}

Provide a comprehensive analysis including:
1. Game Theme and Visual Style
2. Reel Configuration (reels x rows)
3. Paylines and Win Conditions
4. Symbol Types and Values
5. Bonus Features (free spins, wilds, scatters, multipliers)
6. Estimated RTP (Return to Player percentage)
7. Volatility Level (low/medium/high)
8. Special Features and Mechanics
9. Animation and Sound Effects
10. UI Layout and Controls

Return as detailed JSON with all extracted information.`;

    try {
      const response = await invokeLLM({
        messages: [
          {
            role: "system",
            content: "You are a professional slot game analyst with expertise in game mechanics, RTP calculations, and volatility assessment.",
          },
          {
            role: "user",
            content: prompt,
          },
        ],
      });

      const content = response.choices[0]?.message?.content || "{}";
      return JSON.parse(content);
    } catch (error) {
      console.error("Error analyzing game with LLM:", error);
      throw new Error("Failed to analyze game");
    }
  }

  /**
   * Generate realistic game code from LLM analysis
   */
  static async generateGameCodeFromAnalysis(
    analysis: any,
    gameName: string
  ): Promise<string> {
    const prompt = `Generate production-ready React/TypeScript code for a slot game based on this analysis:

Game Name: ${gameName}
Analysis: ${JSON.stringify(analysis, null, 2)}

Requirements:
1. Create a fully functional slot game component
2. Implement all analyzed features and mechanics
3. Use React hooks for state management
4. Support the CoinKrazy slot engine interface
5. Include animations and transitions
6. Implement win calculations based on analyzed RTP
7. Support bonus features from analysis
8. Include viral win-share popup
9. Use SC (Sweep Coins) currency
10. Make it production-ready

Return complete, working React component code.`;

    try {
      const response = await invokeLLM({
        messages: [
          {
            role: "system",
            content: "You are an expert React developer. Generate production-ready game code.",
          },
          {
            role: "user",
            content: prompt,
          },
        ],
      });

      return response.choices[0]?.message?.content || "";
    } catch (error) {
      console.error("Error generating game code:", error);
      throw new Error("Failed to generate game code");
    }
  }

  /**
   * Generate branded thumbnail from game analysis
   */
  static async generateBrandedThumbnail(
    gameName: string,
    analysis: any
  ): Promise<string> {
    const prompt = `Generate a professional slot game thumbnail design specification for PlayCoinKrazy.com.

Game Name: ${gameName}
Theme: ${analysis.theme}
Key Symbols: ${(analysis.symbols || []).map((s: any) => s.name).join(", ")}

Create detailed specifications for:
1. Layout and composition
2. Color scheme matching theme
3. Typography and text placement
4. PlayCoinKrazy.com logo positioning
5. Game title styling
6. Symbol showcase
7. Visual effects and gradients
8. Dimensions and safe areas

Return as detailed design specification that can be used for asset generation.`;

    try {
      const response = await invokeLLM({
        messages: [
          {
            role: "system",
            content: "You are a professional game thumbnail designer.",
          },
          {
            role: "user",
            content: prompt,
          },
        ],
      });

      return response.choices[0]?.message?.content || "";
    } catch (error) {
      console.error("Error generating thumbnail:", error);
      throw new Error("Failed to generate thumbnail");
    }
  }

  /**
   * Create pending game for approval workflow
   */
  static async createPendingGame(
    gameUrl: string,
    gameName: string,
    userId: number
  ): Promise<PendingGame> {
    try {
      // Analyze game
      const analysis = await this.analyzeGameWithLLM(gameUrl);

      // Generate code
      const code = await this.generateGameCodeFromAnalysis(analysis, gameName);

      // Generate thumbnail
      const thumbnail = await this.generateBrandedThumbnail(gameName, analysis);

      // Create config
      const config = {
        id: `pending-${Date.now()}`,
        name: gameName,
        theme: analysis.theme,
        description: `${gameName} - A ${analysis.volatility} volatility slot game`,
        reels: analysis.reels || 5,
        rows: analysis.rows || 3,
        paylines: analysis.paylines || 20,
        rtp: analysis.rtp || 96.5,
        volatility: analysis.volatility || "medium",
        symbols: analysis.symbols || [],
        bonusFeatures: analysis.bonusFeatures || {},
        minBet: 0.1,
        maxBet: 100,
        defaultBet: 1,
      };

      const pendingGame: PendingGame = {
        id: config.id,
        name: gameName,
        theme: analysis.theme,
        sourceUrl: gameUrl,
        analysis,
        config,
        code,
        thumbnail,
        status: "pending",
        createdBy: userId,
        createdAt: new Date(),
      };

      return pendingGame;
    } catch (error) {
      console.error("Error creating pending game:", error);
      throw new Error("Failed to create pending game");
    }
  }

  /**
   * Approve pending game and deploy to database
   */
  static async approvePendingGame(
    pendingGameId: string,
    reviewedBy: number,
    reviewNotes?: string
  ): Promise<void> {
    try {
      // In production, this would fetch from a pending_games table
      // For now, we'll directly insert into allGames

      const gameData = {
        gameId: `approved-${Date.now()}`,
        name: "Approved Game",
        provider: "CoinKrazy Original",
        category: "slot",
        description: "Approved game from builder",
        rtp: 96.5,
        volatility: "medium" as const,
        reels: 5,
        rows: 3,
        paylines: 20,
        minBet: 0.1,
        maxBet: 100,
        defaultBet: 1,
        isActive: true,
        isFeatured: false,
        metadata: JSON.stringify({
          approvedBy: reviewedBy,
          approvedAt: new Date().toISOString(),
          reviewNotes,
          pendingGameId,
        }),
      };

      await db.insert(allGames).values(gameData);
    } catch (error) {
      console.error("Error approving game:", error);
      throw new Error("Failed to approve game");
    }
  }

  /**
   * Reject pending game
   */
  static async rejectPendingGame(
    pendingGameId: string,
    reviewedBy: number,
    reason: string
  ): Promise<void> {
    try {
      // In production, update pending_games table status to 'rejected'
      console.log(`Game ${pendingGameId} rejected by user ${reviewedBy}: ${reason}`);
    } catch (error) {
      console.error("Error rejecting game:", error);
      throw new Error("Failed to reject game");
    }
  }

  /**
   * Get pending games for approval
   */
  static async getPendingGames(): Promise<PendingGame[]> {
    try {
      // In production, query from pending_games table
      return [];
    } catch (error) {
      console.error("Error fetching pending games:", error);
      throw new Error("Failed to fetch pending games");
    }
  }
}

export default EnhancedGameBuilder;
