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;
  /** Public Pusher channels currently attached to this live channel. */
  pusherChannels: Set<string>;
  retryAttempt: number;
  retryTimer: NodeJS.Timeout | null;
  /** Timestamp of the last connected socket; used to distinguish a stable
   *  connection from an immediate Pusher rejection. */
  connectedAtMs: number;
  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;
};

const safePositiveInteger = (value: unknown): number => {
  const number = Number(value);
  return Number.isSafeInteger(number) && number > 0 ? number : 0;
};

const isHostEvent = (eventName: string): boolean => (
  /(?:^|\\)StreamHostEvent$/.test(eventName)
  || eventName === "stream.host"
  || eventName === "channel.hosted"
  || eventName === "channel.raid"
  || eventName === "channel.raid.received"
);

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,
        pusherChannels: new Set(),
        retryAttempt: 0,
        retryTimer: null,
        connectedAtMs: 0,
        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 = () => {
      connection.connectedAtMs = Date.now();
      void this.subscribe(connection, socket);
    };
    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;
      // A connection that stayed alive briefly was healthy: its next retry
      // may start immediately. An immediate close (which happens when a
      // Pusher edge rejects a subscription) keeps its growing backoff instead
      // of reconnecting every second and starving the official alert worker.
      const livedMs = connection.connectedAtMs > 0 ? Date.now() - connection.connectedAtMs : 0;
      if (livedMs >= 5_000) connection.retryAttempt = 0;
      connection.connectedAtMs = 0;
      this.retry(connection);
    };
  }

  /**
   * Kick's official channel API identifies a broadcaster by user id. Pusher's
   * host/raid frame, however, is delivered on the legacy *chatroom* channel.
   * Existing FilyX links legitimately have no chatroom id, so resolve it once
   * when that stream goes live. The legacy channel remains subscribed as a
   * compatibility fallback for older Kick broadcasts.
   */
  private async resolvePusherChannels(connection: RelayConnection): Promise<Set<string>> {
    // Reconnects during a live must not continuously call Kick's public
    // metadata endpoint. The channel identifiers do not change during the
    // same live session and keeping them removes a major source of CPU/network
    // pressure when a Pusher edge is temporarily unavailable.
    if (connection.pusherChannels.size > 0) {
      return new Set(connection.pusherChannels);
    }
    const result = new Set<string>();
    const broadcasterId = safePositiveInteger(connection.channel.kick_channel_id);
    if (broadcasterId) result.add(`channel.${broadcasterId}`);

    const storedChatroomId = safePositiveInteger(connection.channel.kick_chatroom_id);
    if (storedChatroomId) result.add(`chatrooms.${storedChatroomId}.v2`);

    const slug = String(connection.channel.slug ?? "").trim().toLowerCase();
    if (!/^[a-z0-9_-]{2,80}$/.test(slug)) return result;

    // The public response also exposes a legacy channel id. Subscribe to it
    // when available because Kick has used both channels across deployments.
    const controller = new AbortController();
    const timeout = setTimeout(() => controller.abort(), 5_000);
    timeout.unref();
    try {
      const response = await fetch(`https://kick.com/api/v2/channels/${encodeURIComponent(slug)}`, {
        headers: { "User-Agent": "FilyX-Bot/1.0" },
        signal: controller.signal,
      });
      if (!response.ok) throw new Error(`HTTP ${response.status}`);
      const payload = asRecord(await response.json());
      if (!payload) throw new Error("payload invalide");
      const legacyChannelId = safePositiveInteger(payload.id);
      if (legacyChannelId) result.add(`channel.${legacyChannelId}`);
      const chatroom = asRecord(payload.chatroom);
      const chatroomId = safePositiveInteger(chatroom?.id);
      if (chatroomId) result.add(`chatrooms.${chatroomId}.v2`);
    } catch (error) {
      // Never block the bot or existing alerts if Kick's public metadata edge
      // is momentarily unavailable. The persisted id and legacy fallback stay
      // active and the next reconnect retries this best-effort lookup.
      console.warn(`[kick-host-relay] ${slug}: chatroom lookup unavailable (${error instanceof Error ? error.message : "unknown"}).`);
    } finally {
      clearTimeout(timeout);
    }
    return result;
  }

  private async subscribe(connection: RelayConnection, socket: WebSocket): Promise<void> {
    if (connection.stopped || this.connections.get(connection.channel.channel_id) !== connection) {
      socket.close();
      return;
    }
    const channels = await this.resolvePusherChannels(connection);
    if (connection.stopped || connection.socket !== socket || this.connections.get(connection.channel.channel_id) !== connection) return;
    connection.pusherChannels = channels;
    for (const channel of channels) {
      socket.send(JSON.stringify({ event: "pusher:subscribe", data: { channel } }));
    }
    console.info(`[kick-host-relay] ${connection.channel.slug}: listening on ${[...channels].join(", ") || "no channel"}.`);
  }

  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 (!isHostEvent(eventName)) return;
    const pusherChannel = String(frame.channel ?? "");
    if (!connection.pusherChannels.has(pusherChannel)) return;
    const data = parseData(frame.data);
    if (!data) return;
    const host = asRecord(data.host) ?? asRecord(data.hosted) ?? asRecord(data.raider) ?? asRecord(data.sender);
    const username = safeUsername(
      data.host_username
      ?? data.username
      ?? data.user_name
      ?? host?.username
      ?? host?.slug
      ?? data.host,
    );
    if (!username) return;
    const viewers = safeViewerCount(
      data.number_viewers
      ?? data.viewer_count
      ?? data.viewers
      ?? data.raid_size
      ?? host?.viewer_count
      ?? host?.viewers_count,
    );
    // 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:${connection.channel.channel_id}:${username.toLowerCase()}:${viewers}:${Math.floor(Date.now() / 30_000)}`;
    console.info(`[kick-host-relay] ${connection.channel.slug}: raid received from ${username} (${viewers} viewers) via ${pusherChannel}.`);
    this.emit({
      id: eventId,
      channel_id: connection.channel.channel_id,
      type: "channel.raid.received",
      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);
  }
}
