import * as fs from 'fs';
import * as path from 'path';

// Define paths
const DATA_DIR = path.join(process.cwd(), 'data');
const CONTENT_DIR = path.join(process.cwd(), 'content/game');
const GAMES_JSON = path.join(DATA_DIR, 'games.json');

export interface GameCategory {
  name: string;
  id: string;
}

export interface GameData {
  id: string;
  title: string;
  cat: string[];
  thumb: string;
  gameUrl: string;
  pageUrl: string;
  slug: string;
  code: string;
  description?: string;
  content?: string;
}

export interface GameContent {
  title?: string;
  title_blog?: string;
  meta_description?: string;
  meta_description_blog?: string;
  description: string; // HTML string
  description_alt?: string; // HTML string
  questions?: Array<{
    question: string;
    answer: string;
  }>;
  related_keywords?: string[];
}

/**
 * Get all games from games.json
 */
export async function getAllGames(): Promise<GameData[]> {
  try {
    if (!fs.existsSync(GAMES_JSON)) {
      console.warn(`Games JSON file not found at ${GAMES_JSON}`);
      return [];
    }

    const fileContents = fs.readFileSync(GAMES_JSON, 'utf8');
    const games = JSON.parse(fileContents) as GameData[];
    return games;
  } catch (error) {
    console.error('Error reading games.json:', error);
    return [];
  }
}

/**
 * Get game by slug
 */
export async function getGameBySlug(slug: string): Promise<GameData | null> {
  const games = await getAllGames();
  return games.find((game) => game.slug === slug) || null;
}

/**
 * Get game categories (from content folder structure)
 */
export async function getGameCategories(): Promise<string[]> {
  try {
    if (!fs.existsSync(CONTENT_DIR)) {
      return [];
    }

    const categories = fs.readdirSync(CONTENT_DIR).filter((file) => {
      const fullPath = path.join(CONTENT_DIR, file);
      return fs.statSync(fullPath).isDirectory();
    });

    return categories.sort();
  } catch (error) {
    console.error('Error reading game categories:', error);
    return [];
  }
}

/**
 * Get all game content files from a category folder
 */
export async function getGameContentByCategory(category: string): Promise<string[]> {
  try {
    const categoryPath = path.join(CONTENT_DIR, category);
    if (!fs.existsSync(categoryPath)) {
      return [];
    }

    const files = fs.readdirSync(categoryPath).filter((file) => {
      const fullPath = path.join(categoryPath, file);
      return fs.statSync(fullPath).isFile() && file.endsWith('.json');
    });

    return files;
  } catch (error) {
    console.error(`Error reading game content from ${category}:`, error);
    return [];
  }
}

/**
 * Get game content by category and filename
 */
export async function getGameContent(category: string, filename: string): Promise<GameContent | null> {
  try {
    const filePath = path.join(CONTENT_DIR, category, filename);

    if (!fs.existsSync(filePath)) {
      return null;
    }

    const fileContents = fs.readFileSync(filePath, 'utf8');
    const content = JSON.parse(fileContents) as GameContent;
    return content;
  } catch (error) {
    console.error(`Error reading game content from ${category}/${filename}:`, error);
    return null;
  }
}

/**
 * Get all game content from all categories (for sitemap)
 */
export async function getAllGameContent(): Promise<
  Array<{
    category: string;
    filename: string;
    gameId: string;
    title: string;
    slug: string;
  }>
> {
  try {
    const categories = await getGameCategories();
    const allContent = [];

    for (const category of categories) {
      const files = await getGameContentByCategory(category);
      const games = await getAllGames();

      for (const file of files) {
        const gameId = file.replace('.json', '');
        const game = games.find((g) => g.id === gameId || g.slug === gameId);

        if (game) {
          allContent.push({
            category,
            filename: file,
            gameId,
            title: game.title,
            slug: game.slug,
          });
        }
      }
    }

    return allContent;
  } catch (error) {
    console.error('Error getting all game content:', error);
    return [];
  }
}
