import fs from "node:fs/promises";
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 config = loadConfig();
const panel = new PanelClient(config);
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 réelle est déjà active ; test annulé.");

const eventId = `live-test-game-command-${Date.now()}`;
await panel.events([{
  id: eventId,
  channel_id: channel.channel_id,
  type: "chat.message",
  payload: {
    content: "!quiz",
    sender: {
      kick_user_id: `internal-test-${Date.now()}`,
      username: "hom3r_off",
      roles: ["broadcaster"]
    },
    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 && state.active_game.game === "quiz") {
    activeGame = state.active_game;
    if (state.active_game.state === "playing") break;
  }
  await sleep(1250);
}
if (!activeGame || activeGame.state !== "playing") {
  throw new Error(`Le moteur n’a pas démarré la session créée par !quiz: ${JSON.stringify(activeGame)}`);
}

const privateOverlay = JSON.parse(await fs.readFile("D:/Codex/Hom3r V2/outputs/obs-runtime/filyx-game-hub-private.json", "utf8"));
const overlayUrl = new URL(privateOverlay.overlay_url);
const [, , instance, token] = overlayUrl.pathname.split("/");
let overlayEvent = null;
for (let attempt = 0; attempt < 16; attempt += 1) {
  const response = await fetch(`${overlayUrl.origin}/api/overlay/events?instance=${encodeURIComponent(instance)}&token=${encodeURIComponent(token)}&after=0`, { cache: "no-store" });
  const payload = await response.json();
  overlayEvent = (payload.events || []).find((event: Record<string, unknown>) => {
    if (!String(event.event_type || "").startsWith("game.quiz.")) return false;
    try {
      const data = JSON.parse(String(event.payload_json || "{}"));
      return Number(data.game_session_id) === Number(activeGame.game_session_id);
    } catch {
      return false;
    }
  }) || null;
  if (overlayEvent) break;
  await sleep(750);
}

await panel.events([{
  id: `live-test-game-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-live-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);
}

if (!overlayEvent) throw new Error("La session a démarré, mais aucun événement n’est arrivé dans l’overlay unique.");
console.log(JSON.stringify({
  ok: true,
  channel: channel.slug,
  command: "!quiz",
  sessionId: activeGame.game_session_id,
  engineState: activeGame.state,
  overlayEvent: overlayEvent.event_type,
  cleanup: "completed"
}, null, 2));
