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;
// Avoid polling deleted or renamed channels on every ten-second sync.
const CHANNEL_ID_FAILURE_BACKOFF_MS = 15 * 60_000;
const HANDSHAKE_TIMEOUT_MS = 10_000;
const PING_GRACE_MS = 10_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 unavailableChannelIds = new Map<number, 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 heartbeatTimer: NodeJS.Timeout | null = null;
  private handshakeTimer: NodeJS.Timeout | null = null;
  private pingIntervalMs = 0;
  private pongRequired = false;
  private connectCommandId = 0;
  private lastReceivedAt = 0;
  private retryAttempt = 0;
  private nextCommand = 1;
  private ready = false;
  private connecting = false;
  private closed = false;

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

  status(): Record<string, unknown> {
    return {
      connected: this.ready && this.socket?.readyState === WebSocket.OPEN,
      tracked_channels: this.trackedChannelsById.size,
      subscriptions: this.subscribedChannels.size,
      last_received_at: this.lastReceivedAt ? new Date(this.lastReceivedAt).toISOString() : null,
    };
  }

  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);
      // Keep the last working ids while refreshing them. A transient public
      // lookup failure must not discard an otherwise healthy subscription.
      if (cached) {
        for (const resolvedId of cached.ids) next.set(`chatrooms.${resolvedId}`, channel);
      }
      if ((!cached || cached.expiresAt <= Date.now())
        && (this.unavailableChannelIds.get(channel.channel_id) ?? 0) <= Date.now()) {
        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.retryTimer || 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;
      this.handshakeTimer = setTimeout(() => {
        if (this.socket === socket && !this.ready) this.reconnect("handshake timeout");
      }, HANDSHAKE_TIMEOUT_MS);
      this.handshakeTimer.unref();
      socket.onopen = () => {
        if (this.socket !== socket || this.closed || this.channelsByChatroom.size === 0) {
          this.stopSocket();
          return;
        }
        this.connectCommandId = this.commandId();
        this.send(socket, { id: this.connectCommandId, connect: { token, name: "filyx-raid-relay", version: "1" } });
      };
      socket.onmessage = (message) => this.handleMessage(socket, message.data);
      socket.onerror = () => undefined;
      socket.onclose = (event) => {
        if (this.socket !== socket) return;
        this.socket = null;
        this.ready = false;
        this.subscribedChannels.clear();
        this.pendingSubscriptions.clear();
        this.clearConnectionTimers();
        console.warn(`[kick-host-relay] realtime closed (${event.code}); reconnect scheduled.`);
        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}).`);
      }
    } finally {
      this.connecting = false;
      // retry() cannot schedule while connecting is true. In particular, an
      // HTTP/auth failure must not leave the relay idle until a future sync.
      if (!this.socket) this.retry();
    }
  }

  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,
      });
      this.unavailableChannelIds.delete(channel.channel_id);
      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";
      this.unavailableChannelIds.set(channel.channel_id, Date.now() + CHANNEL_ID_FAILURE_BACKOFF_MS);
      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;
    this.lastReceivedAt = Date.now();
    this.armHeartbeat(socket);
    // Accept a legacy empty text ping as well as the protocol's JSON {} ping.
    if (raw.trim() === "") {
      if (this.pongRequired) this.send(socket, {});
      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 || !asRecord(frame)) continue;
      if (Object.keys(frame).length === 0) {
        if (this.pongRequired) this.send(socket, {});
        continue;
      }
      const commandId = Number(frame.id);
      if (frame.error && commandId === this.connectCommandId) {
        this.reconnect("handshake refused");
        return;
      }
      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) {
        if (this.handshakeTimer) clearTimeout(this.handshakeTimer);
        this.handshakeTimer = null;
        this.ready = true;
        this.retryAttempt = 0;
        const heartbeat = asRecord(frame.connect);
        const interval = Number(heartbeat?.ping);
        this.pingIntervalMs = Number.isFinite(interval) && interval > 0 ? interval * 1000 : 30_000;
        this.pongRequired = heartbeat?.pong === true;
        this.armHeartbeat(socket);
        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) {
        if (asRecord(push.disconnect)) {
          this.reconnect("server disconnect");
          return;
        }
        this.handlePush(push);
      }
    }
  }

  private scheduleRefresh(connect: unknown): void {
    this.clearRefreshTimer();
    const ttl = Number(asRecord(connect)?.ttl);
    if (!Number.isFinite(ttl) || ttl <= 0) return;
    const delay = Math.max(1_000, Math.floor(ttl * 1000) - Math.min(CONNECTION_REFRESH_MARGIN_MS, ttl * 500));
    this.refreshTimer = setTimeout(() => this.reconnect("credentials refresh"), delay);
    this.refreshTimer.unref();
  }

  private armHeartbeat(socket: WebSocket): void {
    if (this.heartbeatTimer) clearTimeout(this.heartbeatTimer);
    this.heartbeatTimer = null;
    if (!this.ready || !this.pingIntervalMs) return;
    this.heartbeatTimer = setTimeout(() => {
      if (this.socket === socket) this.reconnect("heartbeat timeout");
    }, this.pingIntervalMs + PING_GRACE_MS);
    this.heartbeatTimer.unref();
  }

  private reconnect(reason: string): void {
    if (this.closed) return;
    console.warn(`[kick-host-relay] realtime reconnect (${reason}).`);
    this.stopSocket();
    this.retry();
  }

  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 clearConnectionTimers(): void {
    this.clearRefreshTimer();
    if (this.heartbeatTimer) clearTimeout(this.heartbeatTimer);
    if (this.handshakeTimer) clearTimeout(this.handshakeTimer);
    this.heartbeatTimer = null;
    this.handshakeTimer = null;
    this.pingIntervalMs = 0;
    this.pongRequired = false;
    this.connectCommandId = 0;
  }

  private stopSocket(): void {
    if (this.retryTimer) clearTimeout(this.retryTimer);
    this.retryTimer = null;
    this.clearConnectionTimers();
    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.
      }
    }
  }
}
