import type { ChannelStatus, EngineEvent } from "../../types.ts";

// Kick's documented webhooks currently do not include the host event. This
// relay is deliberately narrow: it listens only to the channel stream signal
// while the channel is online, then translates StreamHostEvent into the
// already-supported `channel.hosted` event used by the Alerts widget.
//
// It does not read viewer chat, issue any HTTP polling, or send messages to
// Kick. The official webhooks remain the only source for every other event.
const PUSHER_URL = "wss://ws-us2.pusher.com/app/32cbd69e4b950bf97679?protocol=7&client=js&version=8.4.0&flash=false";
const MAX_RETRY_DELAY_MS = 30_000;

type RelayConnection = {
  channel: ChannelStatus;
  socket: WebSocket | null;
  retryAttempt: number;
  retryTimer: NodeJS.Timeout | null;
  stopped: boolean;
};

type PusherFrame = {
  event?: unknown;
  channel?: unknown;
  data?: unknown;
};

const asRecord = (value: unknown): Record<string, unknown> | null => (
  value !== null && typeof value === "object" && !Array.isArray(value)
    ? value as Record<string, unknown>
    : null
);

const parseFrame = (raw: unknown): PusherFrame | null => {
  if (typeof raw !== "string") return null;
  try {
    return asRecord(JSON.parse(raw)) as PusherFrame | null;
  } catch {
    return null;
  }
};

const parseData = (value: unknown): Record<string, unknown> | null => {
  if (typeof value === "string") {
    try {
      return asRecord(JSON.parse(value));
    } catch {
      return null;
    }
  }
  return asRecord(value);
};

const safeUsername = (value: unknown): string => {
  const username = String(value ?? "").trim();
  return /^[a-z0-9_]{1,80}$/i.test(username) ? username : "";
};

const safeViewerCount = (value: unknown): number => {
  const count = Number(value);
  return Number.isFinite(count) ? Math.max(0, Math.min(10_000_000, Math.trunc(count))) : 0;
};

export class KickHostRelay {
  private readonly connections = new Map<number, RelayConnection>();
  private readonly emit: (event: EngineEvent) => void;
  private closed = false;

  constructor(emit: (event: EngineEvent) => void) {
    this.emit = emit;
  }

  sync(channels: readonly ChannelStatus[]): void {
    if (this.closed) return;
    const wanted = new Map<number, ChannelStatus>();
    for (const channel of channels) {
      const kickChannelId = Number(channel.kick_channel_id);
      // A host targets a live channel. Keeping inactive channels disconnected
      // prevents needless sockets as FilyX grows, while the regular channel
      // status sync reconnects a source within at most ten seconds of live.
      if (!Number.isSafeInteger(kickChannelId) || kickChannelId <= 0 || channel.live_status !== "online") continue;
      wanted.set(channel.channel_id, channel);
    }

    for (const [channelId, connection] of this.connections) {
      if (!wanted.has(channelId)) this.stop(connection);
    }
    for (const channel of wanted.values()) {
      const existing = this.connections.get(channel.channel_id);
      if (existing) {
        existing.channel = channel;
        continue;
      }
      const connection: RelayConnection = {
        channel,
        socket: null,
        retryAttempt: 0,
        retryTimer: null,
        stopped: false,
      };
      this.connections.set(channel.channel_id, connection);
      this.connect(connection);
    }
  }

  close(): void {
    this.closed = true;
    for (const connection of this.connections.values()) this.stop(connection);
  }

  private connect(connection: RelayConnection): void {
    if (this.closed || connection.stopped || this.connections.get(connection.channel.channel_id) !== connection) return;
    let socket: WebSocket;
    try {
      socket = new WebSocket(PUSHER_URL);
    } catch {
      this.retry(connection);
      return;
    }
    connection.socket = socket;
    socket.onopen = () => {
      if (connection.stopped || this.connections.get(connection.channel.channel_id) !== connection) {
        socket.close();
        return;
      }
      connection.retryAttempt = 0;
      const kickChannelId = Number(connection.channel.kick_channel_id);
      socket.send(JSON.stringify({
        event: "pusher:subscribe",
        data: { channel: `channel.${kickChannelId}` },
      }));
    };
    socket.onmessage = (message) => this.handleMessage(connection, socket, message.data);
    // Assigning an error handler prevents a temporary websocket failure from
    // becoming an unhandled engine error. `close` schedules the retry.
    socket.onerror = () => undefined;
    socket.onclose = () => {
      if (connection.socket === socket) connection.socket = null;
      this.retry(connection);
    };
  }

  private handleMessage(connection: RelayConnection, socket: WebSocket, raw: unknown): void {
    const frame = parseFrame(raw);
    if (!frame || connection.stopped || this.connections.get(connection.channel.channel_id) !== connection) return;
    const eventName = String(frame.event ?? "");
    if (eventName === "pusher:ping") {
      socket.send(JSON.stringify({ event: "pusher:pong", data: {} }));
      return;
    }
    if (!eventName.endsWith("StreamHostEvent")) return;
    const kickChannelId = Number(connection.channel.kick_channel_id);
    if (String(frame.channel ?? "") !== `channel.${kickChannelId}`) return;
    const data = parseData(frame.data);
    if (!data) return;
    const username = safeUsername(data.host_username ?? data.username ?? data.host);
    if (!username) return;
    const viewers = safeViewerCount(data.number_viewers ?? data.viewer_count ?? data.viewers);
    // Pusher can replay a frame after reconnect. The 30-second identity keeps
    // the existing Alert and chat-queue dedupe path idempotent.
    const eventId = `pusher-host:${kickChannelId}:${username.toLowerCase()}:${viewers}:${Math.floor(Date.now() / 30_000)}`;
    this.emit({
      id: eventId,
      channel_id: connection.channel.channel_id,
      type: "channel.hosted",
      payload: {
        username,
        user_name: username,
        host_username: username,
        viewer_count: viewers,
        number_of_viewers: viewers,
        raid_size: viewers,
        optional_message: String(data.optional_message ?? "").trim().slice(0, 500),
        _filyx_source: "kick-pusher-host",
      },
    });
  }

  private retry(connection: RelayConnection): void {
    if (this.closed || connection.stopped || this.connections.get(connection.channel.channel_id) !== connection || connection.retryTimer) return;
    const delay = Math.min(MAX_RETRY_DELAY_MS, 1_000 * (2 ** Math.min(5, connection.retryAttempt)));
    connection.retryAttempt += 1;
    connection.retryTimer = setTimeout(() => {
      connection.retryTimer = null;
      this.connect(connection);
    }, delay);
    connection.retryTimer.unref();
  }

  private stop(connection: RelayConnection): void {
    connection.stopped = true;
    if (connection.retryTimer) clearTimeout(connection.retryTimer);
    connection.retryTimer = null;
    const socket = connection.socket;
    connection.socket = null;
    if (socket) {
      try {
        socket.close();
      } catch {
        // The connection is already gone; no action is needed.
      }
    }
    this.connections.delete(connection.channel.channel_id);
  }
}
