import path from 'path';
import fs from 'fs';
import type { GameData, GameItem } from './game-types';

// Define paths
const GAME_CONTENT_DIR = path.join(process.cwd(), 'content', 'game');
const GAMES_JSON_PATH = path.join(process.cwd(), 'data', 'games.json');

/**
 * Get all game categories
 */
export async function getGameCategories(): Promise<string[]> {
  if (!fs.existsSync(GAME_CONTENT_DIR)) return [];
  
  return fs.readdirSync(GAME_CONTENT_DIR).filter((file) => {
    const filePath = path.join(GAME_CONTENT_DIR, file);
    return fs.statSync(filePath).isDirectory();
  });
}

/**
 * Get games for a specific category
 */
export async function getGamesByCategory(category: string): Promise<string[]> {
  const categoryDir = path.join(GAME_CONTENT_DIR, category);
  
  if (!fs.existsSync(categoryDir)) return [];
  
  return fs.readdirSync(categoryDir)
    .filter((file) => file.endsWith('.json'))
    .map((file) => file.replace('.json', ''));
}

/**
 * Get game data by category and slug
 */
export async function getGameData(category: string, slug: string): Promise<GameData | null> {
  const filePath = path.join(GAME_CONTENT_DIR, category, `${slug}.json`);
  
  if (!fs.existsSync(filePath)) return null;
  
  try {
    const fileContents = fs.readFileSync(filePath, 'utf8');
    return JSON.parse(fileContents) as GameData;
  } catch (err) {
    console.error(`Error reading or parsing game JSON: ${filePath}`, err);
    return null;
  }
}

/**
 * Get all games from games.json
 */
export async function getAllGames(): Promise<GameItem[]> {
  if (!fs.existsSync(GAMES_JSON_PATH)) return [];
  
  try {
    const fileContents = fs.readFileSync(GAMES_JSON_PATH, 'utf8');
    const games = JSON.parse(fileContents) as GameItem[];
    return games;
  } catch (err) {
    console.error(`Error reading or parsing games.json`, err);
    return [];
  }
}

/**
 * Get total count of games by category
 */
export async function getGameCountByCategory(category: string): Promise<number> {
  const games = await getGamesByCategory(category);
  return games.length;
}

/**
 * Get sample games for homepage
 */
export async function getSampleGames(limit: number = 50): Promise<GameItem[]> {
  const games = await getAllGames();
  return games.slice(0, limit);
}
