import 'dotenv/config';
import { REST, Routes } from 'discord.js';
import { readdirSync } from 'fs';
import path from 'path';
import { fileURLToPath, pathToFileURL } from 'url';

const __dirname = path.dirname(fileURLToPath(import.meta.url));

const commands = [];
const commandsDir = path.join(__dirname, '..', 'commands');
const files = readdirSync(commandsDir).filter(f => f.endsWith('.js'));

for (const file of files) {
  const mod = await import(pathToFileURL(path.join(commandsDir, file)).href);
  const cmd = mod.default;
  if (cmd?.data) commands.push(cmd.data.toJSON());
}

const rest = new REST().setToken(process.env.DISCORD_TOKEN);

try {
  console.log(`Registering ${commands.length} commands...`);
  if (process.env.DEV_GUILD_ID) {
    await rest.put(
      Routes.applicationGuildCommands(process.env.CLIENT_ID, process.env.DEV_GUILD_ID),
      { body: commands }
    );
    console.log(`✅ Registered to guild ${process.env.DEV_GUILD_ID} (instant)`);
  } else {
    await rest.put(Routes.applicationCommands(process.env.CLIENT_ID), { body: commands });
    console.log('✅ Registered globally (may take up to 1 hour)');
  }
} catch (e) {
  console.error('Deploy error:', e);
  process.exit(1);
}
