import { loadConfig } from "file:///D:/Codex/FilyX/apps/bot-engine/src/config.ts";
import { PanelClient } from "file:///D:/Codex/FilyX/apps/bot-engine/src/api/PanelClient.ts";

const sleep = (milliseconds: number) => new Promise((resolve) => setTimeout(resolve, milliseconds));
const panel = new PanelClient(loadConfig());
const channels = await panel.channels();
const channel = channels.find((item) => item.slug.toLowerCase() === "hom3r_off");
if (!channel) throw new Error("Chaîne hom3r_off absente du moteur.");
const before = await panel.channelConfig(channel.channel_id);
if (before.active_game) throw new Error("Une partie est déjà active ; test public annulé.");

const eventId = `live-test-public-game-${Date.now()}`;
await panel.events([{
  id: eventId,
  channel_id: channel.channel_id,
  type: "chat.message",
  payload: {
    content: "!quiz",
    sender: {
      kick_user_id: `public-viewer-test-${Date.now()}`,
      username: "Viewer_Test_FilyX",
      roles: []
    },
    kick_channel_id: channel.kick_channel_id,
    kick_chatroom_id: channel.kick_chatroom_id,
    created_at: new Date().toISOString()
  }
}]);

let activeGame = null;
for (let attempt = 0; attempt < 24; attempt += 1) {
  const state = await panel.channelConfig(channel.channel_id);
  if (state.active_game?.game === "quiz") {
    activeGame = state.active_game;
    if (activeGame.state === "playing") break;
  }
  await sleep(1000);
}
if (!activeGame || activeGame.state !== "playing") throw new Error(`La commande publique n’a pas démarré: ${JSON.stringify(activeGame)}`);
process.stdout.write(`${JSON.stringify({ phase: "started", sessionId: activeGame.game_session_id, state: activeGame.state })}\n`);

await sleep(45000);
await panel.events([{
  id: `live-test-public-complete-${activeGame.game_session_id}-${Date.now()}`,
  channel_id: channel.channel_id,
  type: "game.session.completed",
  payload: { game_session_id: activeGame.game_session_id, reason: "automated-public-command-test" }
}]);
for (let attempt = 0; attempt < 12; attempt += 1) {
  const state = await panel.channelConfig(channel.channel_id);
  if (!state.active_game) break;
  await sleep(500);
}
process.stdout.write(`${JSON.stringify({ phase: "completed", sessionId: activeGame.game_session_id })}\n`);
