import type { ClientMessage, GameMessage, HostMessage, PeerId, PeerInfo } from "@psx/shared";
import { validateClientMessage, validateHostMessage } from "@psx/shared";
import { PeerLink, type PeerLinkState } from "./PeerLink.js";
import { SignalingClient } from "./SignalingClient.js";

/**
 * Transport layer for a co-op session — GDD §8.
 *
 * Topology is a star centred on the host, not a mesh. The host is
 * authoritative, so a guest-to-guest link would carry nothing either side is
 * permitted to act on; every guest holds exactly one link, to peer 0.
 *
 * This class is role-agnostic: it moves validated messages and reports
 * membership. What to *do* with a message is `HostAuthority`'s or the guest
 * session's problem.
 */

export const HOST_PEER_ID = 0;

export class NetSession {
  private readonly signaling: SignalingClient;
  private readonly links = new Map<PeerId, PeerLink>();
  private readonly peers = new Map<PeerId, PeerInfo>();

  localPeerId: PeerId = -1;
  isHost = false;

  /** Host side: a guest sent input or an action. Already validated. */
  onClientMessage: ((message: ClientMessage, from: PeerId) => void) | null = null;
  /** Guest side: the host sent authoritative state. Already validated. */
  onHostMessage: ((message: HostMessage) => void) | null = null;
  onPeersChanged: ((peers: PeerInfo[]) => void) | null = null;
  onLinkStateChanged: ((peerId: PeerId, state: PeerLinkState) => void) | null = null;
  onFatal: ((message: string) => void) | null = null;

  /**
   * World-level peer lifecycle, distinct from the transport-level membership
   * in `onPeersChanged`. `Game` uses these to spawn and despawn bodies, and
   * only wants them once the peer is actually reachable.
   */
  onPeerJoinedWorld: ((peerId: PeerId) => void) | null = null;
  onPeerLeftWorld: ((peerId: PeerId) => void) | null = null;

  constructor(
    signalingUrl: string,
    private readonly iceServers?: RTCIceServer[],
  ) {
    this.signaling = new SignalingClient(signalingUrl, {
      onWelcome: (peerId, isHost, peers) => {
        this.localPeerId = peerId;
        this.isHost = isHost;
        for (const peer of peers) this.peers.set(peer.peerId, peer);

        // The host opens connections to everyone already present; a guest
        // waits to be offered, so both sides never offer simultaneously.
        if (isHost) {
          for (const peer of peers) {
            if (peer.peerId !== peerId) this.openLink(peer.peerId, true);
          }
        }
        this.onPeersChanged?.(this.peerList());
      },

      onPeerJoined: (peer) => {
        this.peers.set(peer.peerId, peer);
        if (this.isHost) this.openLink(peer.peerId, true);
        this.onPeersChanged?.(this.peerList());
      },

      onPeerLeft: (peerId) => {
        this.peers.delete(peerId);
        this.links.get(peerId)?.close();
        this.links.delete(peerId);
        this.onPeerLeftWorld?.(peerId);
        this.onPeersChanged?.(this.peerList());
      },

      onPeerUpdated: (peer) => {
        this.peers.set(peer.peerId, peer);
        this.onPeersChanged?.(this.peerList());
      },

      onSignal: (from, payload) => {
        // A guest learns of the host by being offered, so create on demand.
        const link = this.links.get(from) ?? this.openLink(from, false);
        void link.handleSignal(payload);
      },

      onStart: () => {
        /* Room transitions are driven by the host over the data channel. */
      },

      onError: (message) => this.onFatal?.(message),
      onClose: () => {
        /* Data channels outlive the signalling socket; not fatal on its own. */
      },
    });
  }

  connect(token: string, lobbyCode: string): Promise<void> {
    return this.signaling.connect(token, lobbyCode);
  }

  private openLink(peerId: PeerId, isInitiator: boolean): PeerLink {
    const existing = this.links.get(peerId);
    if (existing) return existing;

    const link = new PeerLink({
      peerId,
      isInitiator,
      sendSignal: (payload) => this.signaling.sendSignal(peerId, payload),
      ...(this.iceServers ? { iceServers: this.iceServers } : {}),
    });

    link.onMessage = (message, from) => this.route(message, from);
    link.onStateChange = (state, id) => {
      // Spawn a body only once the channel is actually usable — announcing on
      // `peer-joined` would create a body for a peer that may never connect.
      if (state === "connected" && this.isHost) this.onPeerJoinedWorld?.(id);
      if (state === "closed" || state === "failed") this.onPeerLeftWorld?.(id);
      this.onLinkStateChanged?.(id, state);
    };

    this.links.set(peerId, link);
    return link;
  }

  /**
   * Validate before dispatch. The host must never act on unvalidated guest
   * input, and a guest should not be crashable by a malformed host frame.
   */
  private route(message: GameMessage, from: PeerId): void {
    if (this.isHost) {
      const result = validateClientMessage(message);
      if (result.ok) this.onClientMessage?.(result.value, from);
      return;
    }

    // Guests accept authoritative state only from the host's link.
    if (from !== HOST_PEER_ID) return;
    const result = validateHostMessage(message);
    if (result.ok) this.onHostMessage?.(result.value);
  }

  /** Host: unreliable broadcast, for state superseded by the next frame. */
  broadcastState(message: HostMessage): void {
    for (const link of this.links.values()) link.sendState(message);
  }

  /** Host: reliable broadcast, for state that must not be dropped. */
  broadcastEvent(message: HostMessage): void {
    for (const link of this.links.values()) link.sendEvent(message);
  }

  sendToPeer(peerId: PeerId, message: HostMessage): void {
    this.links.get(peerId)?.sendEvent(message);
  }

  /** Guest: input goes on the unreliable channel, actions on the reliable one. */
  sendInput(message: ClientMessage): void {
    this.links.get(HOST_PEER_ID)?.sendState(message);
  }

  sendAction(message: ClientMessage): void {
    this.links.get(HOST_PEER_ID)?.sendEvent(message);
  }

  setReady(isReady: boolean): void {
    this.signaling.setReady(isReady);
  }

  peerList(): PeerInfo[] {
    return [...this.peers.values()].sort((a, b) => a.peerId - b.peerId);
  }

  get connectedPeerCount(): number {
    return [...this.links.values()].filter((link) => link.isOpen).length;
  }

  close(): void {
    for (const link of this.links.values()) link.close();
    this.links.clear();
    this.peers.clear();
    this.signaling.close();
  }
}
