const fs = require('fs');
const path = require('path');
const inquirer = require('inquirer');
const chalk = require('chalk');

const { startGameServer } = require('./gameServer');
const { startGiftSimulatorPrompt } = require('./giftSimulator');

const games = JSON.parse(fs.readFileSync(path.join(__dirname, '..', 'games.json'), 'utf-8'));

const configPath = path.join(__dirname, '..', 'config', 'config.json');
const examplePath = path.join(__dirname, '..', 'config', 'config.example.json');
const defaultConfig = JSON.parse(fs.readFileSync(examplePath, 'utf-8'));
const savedConfig = fs.existsSync(configPath)
  ? JSON.parse(fs.readFileSync(configPath, 'utf-8'))
  : {};
const config = { ...defaultConfig, ...savedConfig };

function saveConfig(newConfig) {
  fs.writeFileSync(configPath, JSON.stringify(newConfig, null, 2), 'utf-8');
}

async function main() {
  console.log(chalk.bold.cyan('\n=== TikTok Live Games ===\n'));

  const { gameId } = await inquirer.prompt([
    {
      type: 'list',
      name: 'gameId',
      message: 'Quel jeu veux-tu lancer ?',
      choices: games.map((g) => ({ name: `${g.name} - ${g.description}`, value: g.id }))
    }
  ]);

  const { tiktokUsername } = await inquirer.prompt([
    {
      type: 'input',
      name: 'tiktokUsername',
      message: 'Pseudo TikTok du live (sans @), vide = mode simulation :',
      default: config.tiktokUsername && config.tiktokUsername !== defaultConfig.tiktokUsername
        ? config.tiktokUsername
        : ''
    }
  ]);

  const { port } = await inquirer.prompt([
    {
      type: 'number',
      name: 'port',
      message: 'Port local :',
      default: config.port || 3000
    }
  ]);

  // Un tiret veut dire la meme chose qu'un champ vide : pas de live, mode manuel via /simulator.
  const cleaned = tiktokUsername.trim();
  const effectiveUsername = cleaned === '-' ? '' : cleaned;

  const finalConfig = { ...config, tiktokUsername: effectiveUsername, port };
  saveConfig(finalConfig);

  const game = games.find((g) => g.id === gameId);

  console.log(chalk.cyan(`\nLancement de "${game.name}"...\n`));

  const { broadcast } = startGameServer({
    game,
    tiktokUsername: effectiveUsername,
    port,
    simulateWhenOffline: finalConfig.simulateWhenOffline
  });

  startGiftSimulatorPrompt(broadcast);
}

main().catch((err) => {
  console.error(chalk.red('Erreur:'), err);
  process.exit(1);
});
