const fs = require('fs');
const path = require('path');
const { parse } = require('csv-parse/sync');
const db = require('./database');

function bootstrapGames() {
  // Check if games already exist
  const count = db.prepare('SELECT COUNT(*) as count FROM games').get();
  
  if (count.count > 0) {
    console.log(`Database already has ${count.count} games. Skipping bootstrap.`);
    return;
  }

  // Read the CSV file
  const csvPath = path.join(__dirname, '..', 'games-list.csv');
  
  if (!fs.existsSync(csvPath)) {
    console.log('games-list.csv not found. Skipping bootstrap.');
    return;
  }

  const csvContent = fs.readFileSync(csvPath, 'utf-8');
  const records = parse(csvContent, {
    columns: true,
    skip_empty_lines: true,
    trim: true
  });

  const insert = db.prepare(`
    INSERT INTO games (
      pack_name, title, min_players, max_players, length_minutes, 
      has_audience, family_friendly, game_type, secondary_type, enabled
    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 1)
  `);

  const insertMany = db.transaction((games) => {
    for (const game of games) {
      insert.run(
        game['Game Pack'],
        game['Game Title'],
        parseInt(game['Min. Players']) || 1,
        parseInt(game['Max. Players']) || 8,
        parseLengthMinutes(game['Length']),
        parseBoolean(game['Audience']),
        parseBoolean(game['Family Friendly?']),
        game['Game Type'] || null,
        game['Secondary Type'] || null
      );
    }
  });

  insertMany(records);
  console.log(`Successfully imported ${records.length} games from CSV`);
}

function bootstrapTickers() {
  const tickersPath = path.join(__dirname, 'config', 'tickers.json');

  if (!fs.existsSync(tickersPath)) {
    console.log('tickers.json not found. Skipping ticker bootstrap.');
    return;
  }

  const tickers = JSON.parse(fs.readFileSync(tickersPath, 'utf-8'));

  const update = db.prepare('UPDATE games SET ticker = ? WHERE title = ? AND (ticker IS NULL OR ticker != ?)');

  const updateMany = db.transaction((entries) => {
    let updated = 0;
    for (const [symbol, title] of entries) {
      const result = update.run(symbol, title, symbol);
      updated += result.changes;
    }
    return updated;
  });

  const updated = updateMany(Object.entries(tickers));
  if (updated > 0) {
    console.log(`Updated ticker symbols for ${updated} games`);
  }
}

function parseLengthMinutes(lengthStr) {
  if (!lengthStr || lengthStr === '????' || lengthStr === '?') {
    return null;
  }
  const match = lengthStr.match(/(\d+)/);
  return match ? parseInt(match[1]) : null;
}

function parseBoolean(value) {
  if (!value || value === '?' || value === '????') {
    return 0;
  }
  return value.toLowerCase() === 'yes' ? 1 : 0;
}

module.exports = { bootstrapGames, bootstrapTickers };

