import { randomUUID } from "node:crypto";
import type { ChannelStatus, EngineEvent } from "../../types.ts";

// Kick does not expose raids through its public webhook API. Their current web
// client receives StreamHostedEvent on the public Centrifugo realtime channel
// for the destination chatroom. This relay only translates that event into
// FilyX's existing raid event, so alerts and chat announcements use their
// normal settings.
const KICK_REALTIME_API = "https://web.kick.com/api/v1/realtime";
const KICK_WEB_CLIENT_TOKEN = "e1393935a959b4020a4491574f6490129f678acdaa92760471263db43487f823";
const MAX_RETRY_DELAY_MS = 30_000;
const CONNECTION_REFRESH_MARGIN_MS = 45_000;
const CHANNEL_ID_CACHE_MS = 10 * 60_000;

type CentrifugoEnvelope = {
  id?: unknown;
  connect?: unknown;
  subscribe?: unknown;
  push?: unknown;
  error?: unknown;
};

type RealtimeCredentials = {
  url: string;
};

const asRecord = (value: unknown): Record<string, unknown> | null => (
  value !== null && typeof value === "object" && !Array.isArray(value)
    ? value as Record<string, unknown>
    : 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 => (
  /(?:^|\\)StreamHostedEvent$/.test(eventName)
  || /(?:^|\\)StreamHostEvent$/.test(eventName)
  || eventName === "stream.host"
  || eventName === "channel.hosted"
  || eventName === "channel.raid"
  || eventName === "channel.raid.received"
);

/**
 * One shared public realtime socket for every linked FilyX channel. It is
 * kept separate from command processing: an unavailable realtime edge can
 * never block chat commands, normal webhooks, or outbound messages.
 */
export class KickHostRelay {
  private readonly emit: (event: EngineEvent) => void;
  private readonly channelsByChatroom = new Map<string, ChannelStatus>();
  // The worker's status endpoint can legitimately omit kick_chatroom_id for
  // an already-linked channel. Keep every tracked channel apart from the
  // resolved realtime ids so a fresh process can bootstrap itself through
  // Kick's public channel endpoint. Subscribing before the stream begins
  // prevents the first Raid of a live from being missed by a stale status.
  private readonly trackedChannelsById = new Map<number, ChannelStatus>();
  private readonly subscribedChannels = new Set<string>();
  private readonly pendingSubscriptions = new Map<number, string>();
  private readonly resolvedChatroomIds = new Map<number, { expiresAt: number; ids: number[] }>();
  private readonly resolvingChannelIds = new Set<number>();
  private socket: WebSocket | null = null;
  private retryTimer: NodeJS.Timeout | null = null;
  private refreshTimer: NodeJS.Timeout | null = null;
  private retryAttempt = 0;
  private nextCommand = 1;
  private ready = false;
  private connecting = false;
  private closed = false;

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

  sync(channels: readonly ChannelStatus[]): void {
    if (this.closed) return;
    const next = new Map<string, ChannelStatus>();
    this.trackedChannelsById.clear();
    for (const channel of channels) {
      this.trackedChannelsById.set(channel.channel_id, channel);

      const chatroomId = safePositiveInteger(channel.kick_chatroom_id);
      if (chatroomId) next.set(`chatrooms.${chatroomId}`, channel);
      const cached = this.resolvedChatroomIds.get(channel.channel_id);
      if (cached && cached.expiresAt > Date.now()) {
        for (const resolvedId of cached.ids) next.set(`chatrooms.${resolvedId}`, channel);
      } else {
        void this.resolveRealtimeChannelIds(channel);
      }
    }

    this.channelsByChatroom.clear();
    for (const [realtimeChannel, channel] of next) this.channelsByChatroom.set(realtimeChannel, channel);

    if (this.channelsByChatroom.size === 0) {
      // Lookups are in flight for tracked channels whose stored chatroom id is
      // empty. Do not mark the relay as offline: resolveRealtimeChannelIds()
      // will add the canonical id and open the socket as soon as it returns.
      if (this.trackedChannelsById.size > 0) return;
      this.stopSocket();
      return;
    }
    if (!this.socket) {
      this.connect();
      return;
    }
    if (this.ready) this.subscribeWantedChannels();
  }

  close(): void {
    this.closed = true;
    this.channelsByChatroom.clear();
    this.trackedChannelsById.clear();
    this.stopSocket();
  }

  private connect(): void {
    if (this.closed || this.connecting || this.socket || this.channelsByChatroom.size === 0) return;
    this.connecting = true;
    void this.openConnection();
  }

  private async openConnection(): Promise<void> {
    try {
      const clientId = randomUUID();
      const descriptor = await this.postJson("/connection", {
        client: { id: clientId, type: "web" },
        capabilities: { accepted_providers: [{ provider: "centrifugo" }] },
      });
      if (this.closed || this.channelsByChatroom.size === 0) return;
      const connections = asRecord(descriptor.data)?.connections;
      const realtimeConnection = Array.isArray(connections)
        ? connections.map(asRecord).find((connection) => connection?.provider === "centrifugo")
        : null;
      const credentials = asRecord(realtimeConnection?.credentials) as RealtimeCredentials | null;
      if (!credentials || typeof credentials.url !== "string" || !credentials.url.startsWith("wss://")) {
        throw new Error("realtime credentials unavailable");
      }

      const authentication = await this.postJson("/auth/connection", { client_id: clientId });
      if (this.closed || this.channelsByChatroom.size === 0) return;
      const token = asRecord(authentication.data)?.token;
      if (typeof token !== "string" || token.length < 20) throw new Error("realtime token unavailable");

      const socket = new WebSocket(credentials.url);
      this.socket = socket;
      socket.onopen = () => {
        if (this.socket !== socket || this.closed || this.channelsByChatroom.size === 0) {
          this.stopSocket();
          return;
        }
        this.send(socket, { id: this.commandId(), connect: { token, name: "filyx-raid-relay", version: "1" } });
      };
      socket.onmessage = (message) => this.handleMessage(socket, message.data);
      socket.onerror = () => undefined;
      socket.onclose = () => {
        if (this.socket !== socket) return;
        this.socket = null;
        this.ready = false;
        this.subscribedChannels.clear();
        this.pendingSubscriptions.clear();
        this.clearRefreshTimer();
        if (!this.closed && this.channelsByChatroom.size > 0) this.retry();
      };
    } catch (error) {
      if (!this.closed && this.channelsByChatroom.size > 0) {
        const message = error instanceof Error ? error.message : "unknown error";
        console.warn(`[kick-host-relay] realtime connection unavailable (${message}).`);
        this.retry();
      }
    } finally {
      this.connecting = false;
    }
  }

  private async postJson(path: string, body: Record<string, unknown>): Promise<Record<string, unknown>> {
    const controller = new AbortController();
    const timeout = setTimeout(() => controller.abort(), 8_000);
    timeout.unref();
    try {
      const response = await fetch(`${KICK_REALTIME_API}${path}`, {
        method: "POST",
        headers: {
          "content-type": "application/json",
          "x-client-token": KICK_WEB_CLIENT_TOKEN,
        },
        body: JSON.stringify(body),
        signal: controller.signal,
      });
      if (!response.ok) throw new Error(`HTTP ${response.status}`);
      const payload = asRecord(await response.json());
      if (!payload) throw new Error("invalid realtime response");
      return payload;
    } finally {
      clearTimeout(timeout);
    }
  }

  /**
   * `kick_chatroom_id` is kept for compatibility with older Kick responses.
   * The current website can expose a different realtime/chat id for the same
   * live channel, so subscribe to both values for the short lifetime of a
   * live session. This request is cached and never runs on the chat command
   * path.
   */
  private async resolveRealtimeChannelIds(channel: ChannelStatus): Promise<void> {
    if (this.resolvingChannelIds.has(channel.channel_id)) return;
    const slug = String(channel.slug ?? "").trim().toLowerCase();
    if (!/^[a-z0-9_-]{2,80}$/.test(slug)) return;
    this.resolvingChannelIds.add(channel.channel_id);
    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-Raid-Relay/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("invalid channel payload");
      const ids = [...new Set([
        safePositiveInteger(payload.id),
        safePositiveInteger(asRecord(payload.chatroom)?.id),
        safePositiveInteger(channel.kick_chatroom_id),
      ].filter(Boolean))];
      if (!ids.length) throw new Error("no chatroom id");
      this.resolvedChatroomIds.set(channel.channel_id, {
        ids,
        expiresAt: Date.now() + CHANNEL_ID_CACHE_MS,
      });
      if (this.closed || !this.trackedChannelsById.has(channel.channel_id)) return;
      // Do not revive a removed channel while the public lookup is in flight.
      for (const id of ids) this.channelsByChatroom.set(`chatrooms.${id}`, channel);
      if (!this.socket) this.connect();
      else if (this.ready) this.subscribeWantedChannels();
    } catch (error) {
      const message = error instanceof Error ? error.message : "unknown error";
      console.warn(`[kick-host-relay] ${slug}: realtime id lookup unavailable (${message}).`);
    } finally {
      clearTimeout(timeout);
      this.resolvingChannelIds.delete(channel.channel_id);
    }
  }

  private handleMessage(socket: WebSocket, raw: unknown): void {
    if (this.socket !== socket || this.closed || typeof raw !== "string") return;
    // Centrifugo sends an empty WebSocket frame as a ping when `pong` is true.
    if (raw.trim() === "") {
      try {
        socket.send("{}");
      } catch {
        // Close owns reconnection if the socket disappeared meanwhile.
      }
      return;
    }
    for (const line of raw.trim().split("\n")) {
      let frame: CentrifugoEnvelope | null = null;
      try {
        frame = JSON.parse(line) as CentrifugoEnvelope;
      } catch {
        continue;
      }
      if (!frame) continue;
      const commandId = Number(frame.id);
      if (Number.isSafeInteger(commandId) && this.pendingSubscriptions.has(commandId)) {
        const realtimeChannel = this.pendingSubscriptions.get(commandId)!;
        this.pendingSubscriptions.delete(commandId);
        if (frame.error) {
          console.warn(`[kick-host-relay] subscription refused for ${realtimeChannel}.`);
        } else if (this.channelsByChatroom.has(realtimeChannel)) {
          this.subscribedChannels.add(realtimeChannel);
          console.info(`[kick-host-relay] ${this.channelsByChatroom.get(realtimeChannel)!.slug}: raid listener ready.`);
        }
      }
      if (frame.connect && !this.ready) {
        this.ready = true;
        this.retryAttempt = 0;
        this.scheduleRefresh(frame.connect);
        console.info(`[kick-host-relay] realtime connected; tracking ${this.channelsByChatroom.size} live channel(s).`);
        this.subscribeWantedChannels();
      }
      const push = asRecord(frame.push);
      if (push) this.handlePush(push);
    }
  }

  private scheduleRefresh(connect: unknown): void {
    this.clearRefreshTimer();
    const ttl = Number(asRecord(connect)?.ttl);
    if (!Number.isFinite(ttl) || ttl <= 60) return;
    const delay = Math.max(10_000, Math.floor(ttl * 1000) - CONNECTION_REFRESH_MARGIN_MS);
    this.refreshTimer = setTimeout(() => this.stopSocket(), delay);
    this.refreshTimer.unref();
  }

  private subscribeWantedChannels(): void {
    const socket = this.socket;
    if (!socket || !this.ready || socket.readyState !== WebSocket.OPEN) return;
    for (const realtimeChannel of this.channelsByChatroom.keys()) {
      if (this.subscribedChannels.has(realtimeChannel)) continue;
      if ([...this.pendingSubscriptions.values()].includes(realtimeChannel)) continue;
      const id = this.commandId();
      this.pendingSubscriptions.set(id, realtimeChannel);
      this.send(socket, { id, subscribe: { channel: realtimeChannel } });
    }
  }

  private handlePush(push: Record<string, unknown>): void {
    const realtimeChannel = String(push.channel ?? "");
    const channel = this.channelsByChatroom.get(realtimeChannel);
    if (!channel) return;
    const publication = asRecord(push.pub);
    const envelope = parseData(publication?.data);
    if (!envelope) return;
    const eventName = String(envelope.event ?? envelope.name ?? "");
    if (!isHostEvent(eventName)) return;
    const data = parseData(envelope.data) ?? envelope;
    // StreamHostedEvent, emitted by the current Kick web client, carries the
    // raider in `user` and the audience count in `message.numberOfViewers`.
    // Keep the older names as fallbacks for previous realtime deployments.
    const host = asRecord(data.user) ?? asRecord(data.host) ?? asRecord(data.hosted) ?? asRecord(data.raider) ?? asRecord(data.sender);
    const message = asRecord(data.message);
    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
      ?? message?.numberOfViewers
      ?? message?.number_of_viewers
      ?? message?.viewer_count
      ?? host?.viewer_count
      ?? host?.viewers_count,
    );
    const eventId = `kick-host:${channel.channel_id}:${username.toLowerCase()}:${viewers}:${Math.floor(Date.now() / 30_000)}`;
    console.info(`[kick-host-relay] ${channel.slug}: raid received from ${username} (${viewers} viewers).`);
    this.emit({
      id: eventId,
      channel_id: 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-realtime-host",
      },
    });
  }

  private commandId(): number {
    const id = this.nextCommand;
    this.nextCommand = this.nextCommand >= 2_000_000_000 ? 1 : this.nextCommand + 1;
    return id;
  }

  private send(socket: WebSocket, command: Record<string, unknown>): void {
    try {
      socket.send(JSON.stringify(command));
    } catch {
      // The close handler schedules a retry when the transport has gone away.
    }
  }

  private retry(): void {
    if (this.closed || this.retryTimer || this.socket || this.connecting || this.channelsByChatroom.size === 0) return;
    const delay = Math.min(MAX_RETRY_DELAY_MS, 1_000 * (2 ** Math.min(5, this.retryAttempt)));
    this.retryAttempt += 1;
    this.retryTimer = setTimeout(() => {
      this.retryTimer = null;
      this.connect();
    }, delay);
    this.retryTimer.unref();
  }

  private clearRefreshTimer(): void {
    if (this.refreshTimer) clearTimeout(this.refreshTimer);
    this.refreshTimer = null;
  }

  private stopSocket(): void {
    if (this.retryTimer) clearTimeout(this.retryTimer);
    this.retryTimer = null;
    this.clearRefreshTimer();
    this.ready = false;
    this.subscribedChannels.clear();
    this.pendingSubscriptions.clear();
    const socket = this.socket;
    this.socket = null;
    if (socket) {
      try {
        socket.close();
      } catch {
        // It is already closed.
      }
    }
  }
}
