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

export interface GameAnalysis {
  theme: string;
  symbols: Array<{ id: string; name: string; value: number; color: string }>;
  reels: number;
  rows: number;
  paylines: number;
  rtp: number;
  volatility: "low" | "medium" | "high";
  bonusFeatures: string[];
  freeSpins: boolean;
  scatters: boolean;
  wilds: boolean;
  maxWin: number;
  animations: string[];
  sounds: string[];
  uiLayout: string;
}

export interface GameConfig {
  id: string;
  name: string;
  theme: string;
  description: string;
  reels: number;
  rows: number;
  paylines: number;
  rtp: number;
  volatility: "low" | "medium" | "high";
  symbols: Array<{
    id: string;
    name: string;
    type: "regular" | "wild" | "scatter" | "bonus";
    value: number;
    multiplier: number;
    frequency: number;
    color: string;
  }>;
  bonusFeatures: Record<string, any>;
  minBet: number;
  maxBet: number;
  defaultBet: number;
}

/**
 * Analyzes a game URL and extracts game metadata
 */
export async function analyzeGameFromUrl(gameUrl: string): Promise<GameAnalysis> {
  const prompt = `You are a slot game expert. Analyze the following game URL and extract detailed information about the game mechanics, theme, and features.

Game URL: ${gameUrl}

Please provide a detailed analysis in JSON format with the following structure:
{
  "theme": "string (e.g., 'Ancient Egypt', 'Fruit Machine')",
  "symbols": [{"id": "string", "name": "string", "value": number, "color": "string"}],
  "reels": number,
  "rows": number,
  "paylines": number,
  "rtp": number (e.g., 96.5),
  "volatility": "low|medium|high",
  "bonusFeatures": ["string array of bonus features"],
  "freeSpins": boolean,
  "scatters": boolean,
  "wilds": boolean,
  "maxWin": number,
  "animations": ["string array of animation types"],
  "sounds": ["string array of sound effects"],
  "uiLayout": "string description of UI layout"
}

Return ONLY valid JSON, no additional text.`;

  try {
    const response = await invokeLLM({
      messages: [
        {
          role: "system",
          content: "You are a slot game analysis expert. Extract game metadata and return valid JSON only.",
        },
        {
          role: "user",
          content: prompt,
        },
      ],
    });

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

/**
 * Generates a game configuration from analysis
 */
export function generateGameConfig(
  analysis: GameAnalysis,
  gameName: string,
  gameId: string
): GameConfig {
  return {
    id: gameId,
    name: gameName,
    theme: analysis.theme,
    description: `${gameName} - A ${analysis.volatility} volatility slot game with ${analysis.paylines} paylines`,
    reels: analysis.reels,
    rows: analysis.rows,
    paylines: analysis.paylines,
    rtp: analysis.rtp,
    volatility: analysis.volatility,
    symbols: analysis.symbols.map((sym) => ({
      id: sym.id,
      name: sym.name,
      type: sym.id === "wild" ? "wild" : sym.id === "scatter" ? "scatter" : "regular",
      value: sym.value,
      multiplier: 1,
      frequency: 1 / analysis.symbols.length,
      color: sym.color,
    })),
    bonusFeatures: {
      freeSpins: {
        enabled: analysis.freeSpins,
        triggerSymbol: "scatter",
        triggerCount: 3,
        freeSpins: 10,
        multiplier: 1,
      },
      wilds: {
        enabled: analysis.wilds,
        wildSymbol: "wild",
      },
      scatters: {
        enabled: analysis.scatters,
        scatterSymbol: "scatter",
      },
    },
    minBet: 0.1,
    maxBet: 100,
    defaultBet: 1,
  };
}

/**
 * Generates game assets (symbols, backgrounds, UI)
 */
export async function generateGameAssets(analysis: GameAnalysis, gameName: string) {
  const prompt = `Create a comprehensive visual design specification for a slot game with the following characteristics:

Theme: ${analysis.theme}
Symbols: ${analysis.symbols.map((s) => s.name).join(", ")}
Volatility: ${analysis.volatility}
Reels: ${analysis.reels}x${analysis.rows}

Generate specifications for:
1. Symbol designs (describe visual style, colors, animations)
2. Background design (theme-appropriate, professional)
3. UI layout (button positions, info displays, bet controls)
4. Color palette (primary, secondary, accent colors)
5. Typography (font styles and sizes)
6. Animation effects (spinning, winning, bonus triggers)
7. Sound effects (spin, win, bonus, background music)

Format as detailed JSON with visual descriptions that can be used for asset generation.`;

  try {
    const response = await invokeLLM({
      messages: [
        {
          role: "system",
          content: "You are a game designer. Create detailed visual specifications for slot game assets.",
        },
        {
          role: "user",
          content: prompt,
        },
      ],
    });

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

/**
 * Generates game code compatible with CoinKrazy engine
 */
export async function generateGameCode(
  config: GameConfig,
  analysis: GameAnalysis
): Promise<string> {
  const prompt = `Generate TypeScript/React code for a slot game compatible with the CoinKrazy game engine.

Game Configuration:
${JSON.stringify(config, null, 2)}

Requirements:
1. Use React hooks for state management
2. Support the CoinKrazy slot engine interface
3. Implement spin logic with configurable RTP
4. Support bonus features: ${Object.keys(config.bonusFeatures).join(", ")}
5. Include animations and transitions
6. Support SC (Sweep Coins) currency
7. Include win-share popup for viral marketing
8. Make it fully compatible with the universal game loader

Return production-ready React component code.`;

  try {
    const response = await invokeLLM({
      messages: [
        {
          role: "system",
          content: "You are an expert React/TypeScript 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");
  }
}

/**
 * Creates a game remix by modifying an existing game
 */
export async function remixGame(
  baseGame: GameConfig,
  remixTheme: string
): Promise<GameConfig> {
  const prompt = `Create a remix of the following slot game with a new theme while maintaining the same gameplay structure.

Base Game:
${JSON.stringify(baseGame, null, 2)}

New Theme: ${remixTheme}

Requirements:
1. Keep the same RTP and volatility
2. Keep the same number of reels, rows, and paylines
3. Change symbols to match the new theme
4. Update colors and visual style
5. Keep bonus features similar
6. Maintain gameplay pacing

Return the remixed game configuration as valid JSON.`;

  try {
    const response = await invokeLLM({
      messages: [
        {
          role: "system",
          content: "You are a game designer. Create game remixes with new themes while maintaining gameplay.",
        },
        {
          role: "user",
          content: prompt,
        },
      ],
    });

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

/**
 * Generates a branded thumbnail for the game
 */
export async function generateGameThumbnail(
  gameName: string,
  theme: string,
  symbols: string[]
): Promise<string> {
  const prompt = `Generate a specification for a professional slot game thumbnail with PlayCoinKrazy.com branding.

Game Name: ${gameName}
Theme: ${theme}
Key Symbols: ${symbols.join(", ")}

Specification should include:
1. Layout and composition
2. Color scheme
3. Typography and text placement
4. PlayCoinKrazy.com logo positioning
5. Game title styling
6. Symbol showcase
7. Visual effects and gradients

Return as detailed design specification.`;

  try {
    const response = await invokeLLM({
      messages: [
        {
          role: "system",
          content: "You are a game thumbnail designer. Create specifications for professional game thumbnails.",
        },
        {
          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");
  }
}
