// The real Connect-RPC + FlatBuffers transport. Every unary op rides the single
// Execute envelope (message_type + FlatBuffers payload); the live stream is
// Subscribe. The session token rides in the Authorization header; domain outcomes
// come back in result_code, edge failures as Connect error codes — both normalised to
// a thrown GatewayError. In dev the Vite proxy forwards the RPC path to the h2c
// gateway; in a packaged app VITE_GATEWAY_URL points at the real origin.

import { createClient } from '@connectrpc/connect';
import { createConnectTransport } from '@connectrpc/connect-web';
import { Gateway } from '../gen/edge/v1/edge_pb';
import { GatewayError, type GatewayClient } from './client';
import * as codec from './codec';
import { browserOffset } from './profileValidation';
import { platformSubtype } from './platform';
import { registerProbe, reportOffline, reportOnline } from './connection.svelte';
import { offlineMode } from './offline.svelte';
import { maintenanceRecovered, registerMaintenanceProbe, reportMaintenance } from './maintenance.svelte';
import { maintenanceRetryMs } from './maintenance';
import { backoffMs, isConnectionCode, retryable, toGatewayError } from './retry';
import { UPDATE_REQUIRED, reportUpdateRecommended, reportUpdateRequired } from './update.svelte';

const MAX_RETRIES = 6;
const sleep = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms));

// The offline kill switch: in deliberate offline mode every network operation is refused before it
// leaves the device, so offline truly means offline regardless of any UI affordance that slips
// through. The local (device-only) game path never uses this transport, so it is unaffected.
function assertOnline(): void {
  if (offlineMode.active) throw new GatewayError('offline');
}

export function createTransport(baseUrl: string): GatewayClient {
  const origin = baseUrl || (typeof location !== 'undefined' ? location.origin : '');
  const transport = createConnectTransport({
    baseUrl: origin,
    useBinaryFormat: true,
    // Observe the soft-tier version nudge: a served unary response may carry X-Update-Recommended (the
    // additive header the edge sets for a client at or above the hard minimum but below the recommended
    // version). Reading it in an interceptor keeps it off every call site; the stream path is not
    // soft-gated. It never fails the call — the nudge is non-blocking.
    interceptors: [
      (next) => async (req) => {
        const res = await next(req);
        if (!res.stream && res.header.get('x-update-recommended') === '1') reportUpdateRecommended();
        return res;
      },
    ],
  });
  const client = createClient(Gateway, transport);
  let token: string | null = null;

  // Every call carries the build version so the edge's client-version gate can turn away a build
  // too old to speak the current wire contract, before it decodes the payload (the header rides the
  // outermost stable layer; see docs/ARCHITECTURE.md §2).
  const headers = (): Record<string, string> => {
    const h: Record<string, string> = { 'x-client-version': __APP_VERSION__ };
    if (token) h.authorization = `Bearer ${token}`;
    return h;
  };

  // The reachability probe the connection watcher fires while offline: a cheap authenticated read
  // (it must reject when there is no session, so the watcher keeps waiting rather than reporting up).
  const reachabilityProbe = async (): Promise<void> => {
    if (!token) throw new Error('no session');
    // Exempt from the offline kill switch: the probe IS the reachability check that decides whether to
    // return online, and it fires only deliberately — the connection watcher is guarded off in offline
    // mode, and checkReachable runs it on an online event — so it must reach the gateway while offline.
    await client.execute({ messageType: 'profile.get', payload: codec.empty(), requestId: '' }, { headers: headers() });
  };
  registerProbe(reachabilityProbe);
  // The maintenance overlay reuses the same cheap read to poll for the end of a deploy
  // window; the first success lifts the overlay (maintenance.svelte.ts).
  registerMaintenanceProbe(reachabilityProbe);

  // exec runs one unary op, auto-retrying transient transport failures with capped backoff (so a
  // dropped connection or a rate-limit recovers seamlessly) and driving the global Connecting
  // indicator. A successful round-trip marks the gateway reachable; a domain result_code is final.
  async function exec(
    messageType: string,
    payload: Uint8Array,
    signal?: AbortSignal,
    opts?: { silent?: boolean; allowOffline?: boolean },
  ): Promise<Uint8Array> {
    // allowOffline lets the background guest-reconciliation call reach the gateway while the app is
    // still in auto-offline mode (that call IS the reachability check); every other call honours the
    // kill switch. silent suppresses the terminal update overlay on update_required (the caller — the
    // reconciliation — swallows it and stays a local guest); foreground calls still raise it.
    if (!opts?.allowOffline) assertOnline();
    for (let attempt = 0; ; attempt++) {
      let res;
      try {
        res = await client.execute({ messageType, payload, requestId: '' }, { headers: headers(), signal });
      } catch (e) {
        if (signal?.aborted) throw e; // an intentional cancel (e.g. the tiles moved) — do not retry
        const maintMs = maintenanceRetryMs(e);
        if (maintMs !== null) {
          // A planned deploy window (the edge 503 carried X-Scrabble-Maintenance): raise the
          // overlay and fail fast — its own poll drives recovery — instead of burning the
          // retry budget on every read for the length of the window.
          reportMaintenance(maintMs);
          throw toGatewayError(e);
        }
        const err = toGatewayError(e);
        // A too-old client turned away on a foreground call raises the terminal update overlay; a
        // silent (background reconciliation) call swallows it and stays a local guest.
        if (err.code === UPDATE_REQUIRED && !opts?.silent) reportUpdateRequired();
        if (retryable(err.code, messageType) && attempt < MAX_RETRIES) {
          reportOffline();
          await sleep(backoffMs(attempt + 1));
          continue;
        }
        if (isConnectionCode(err.code)) reportOffline();
        throw err;
      }
      reportOnline();
      // A read got through: if the maintenance overlay was up, the deploy window has ended —
      // reload to pick up the (possibly incompatible) fresh client (maintenance.svelte.ts).
      maintenanceRecovered();
      if (res.resultCode && res.resultCode !== 'ok') {
        if (res.resultCode === UPDATE_REQUIRED && !opts?.silent) reportUpdateRequired();
        // Carry the envelope's optional human-readable message (e.g. an operator's payment-unavailable
        // explanation) so a caller that shows it to the user has the localized text.
        throw new GatewayError(res.resultCode, res.message || undefined);
      }
      return res.payload;
    }
  }

  return {
    setToken(t) {
      token = t;
    },

    async fetchDict(variant, version, opts) {
      if (!token) throw new Error('fetchDict: no session');
      assertOnline();
      // Low priority so the browser schedules the (large) dictionary behind the game's own
      // requests — the move eval, state and live events — on a slow link (EDGE). Ignored
      // where the Priority Hints API is unsupported (iOS WebKit), which is harmless. The
      // signal aborts a stalled download so it stops holding the channel; reload (the debug
      // "clear") bypasses the browser HTTP cache to force a fresh copy.
      const res = await fetch(`${origin}/dict/${encodeURIComponent(variant)}/${encodeURIComponent(version)}`, {
        headers: { authorization: `Bearer ${token}` },
        priority: 'low',
        signal: opts?.signal,
        cache: opts?.reload ? 'reload' : undefined,
      } as RequestInit);
      if (!res.ok) throw new Error(`fetchDict ${variant}/${version}: HTTP ${res.status}`);
      return res.arrayBuffer();
    },

    async reportLocalEval(counts) {
      if (!token) throw new Error('reportLocalEval: no session');
      assertOnline();
      // keepalive so a batch flushed as the app is backgrounded still reaches the edge.
      const res = await fetch(`${origin}/metrics/local-eval`, {
        method: 'POST',
        headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' },
        body: JSON.stringify(counts),
        keepalive: true,
      });
      if (!res.ok) throw new Error(`reportLocalEval: HTTP ${res.status}`);
    },

    async authTelegram(initData) {
      return codec.decodeSession(await exec('auth.telegram', codec.encodeTelegramLogin(initData, browserOffset(), platformSubtype())));
    },
    async authVK(params, displayName) {
      return codec.decodeSession(await exec('auth.vk', codec.encodeVKLogin(params, browserOffset(), displayName)));
    },
    async authGuest(locale) {
      return codec.decodeSession(await exec('auth.guest', codec.encodeGuestLogin(locale ?? '', browserOffset(), platformSubtype())));
    },
    async authGuestSilent(locale) {
      // Background reconciliation of a native local guest gaining the network: it runs while the app is
      // still in auto-offline mode (allowOffline bypasses the kill switch) and must never raise the
      // terminal update overlay (silent) — a too-old client stays a local guest instead of being
      // interrupted mid-play (docs/ARCHITECTURE.md §2, the gate×offline rule).
      return codec.decodeSession(
        await exec('auth.guest', codec.encodeGuestLogin(locale ?? '', browserOffset(), platformSubtype()), undefined, {
          silent: true,
          allowOffline: true,
        }),
      );
    },
    async authEmailRequest(email, language, pwa) {
      await exec('auth.email.request', codec.encodeEmailRequest(email, browserOffset(), language, pwa));
    },
    async confirmEmailLink(token) {
      return codec.decodeConfirmLinkResult(await exec('auth.email.confirm_link', codec.encodeEmailConfirmLink(token)));
    },
    async authEmailLogin(email, code) {
      return codec.decodeSession(await exec('auth.email.login', codec.encodeEmailLogin(email, code, platformSubtype())));
    },

    async profileGet() {
      return codec.decodeProfile(await exec('profile.get', codec.empty()));
    },
    async blockStatus() {
      return codec.decodeBlockStatus(await exec('account.block_status', codec.empty()));
    },
    async gamesList() {
      return codec.decodeGameList(await exec('games.list', codec.empty()));
    },

    async lobbyEnqueue(variant, multipleWords, vsAi) {
      return codec.decodeMatchResult(await exec('lobby.enqueue', codec.encodeEnqueue(variant, multipleWords, vsAi)));
    },
    async lobbyPoll() {
      return codec.decodeMatchResult(await exec('lobby.poll', codec.empty()));
    },
    async lobbyCancel() {
      await exec('lobby.cancel', codec.empty());
    },

    async gameState(id, includeAlphabet) {
      return codec.decodeStateView(await exec('game.state', codec.encodeStateRequest(id, includeAlphabet)));
    },
    async gameHistory(id) {
      return codec.decodeHistory(await exec('game.history', codec.encodeGameAction(id)));
    },
    async submitPlay(id, tiles, variant) {
      return codec.decodeMoveResult(await exec('game.submit_play', codec.encodeSubmitPlay(id, tiles, variant)));
    },
    async pass(id) {
      return codec.decodeMoveResult(await exec('game.pass', codec.encodeGameAction(id)));
    },
    async exchange(id, tiles, variant) {
      return codec.decodeMoveResult(await exec('game.exchange', codec.encodeExchange(id, tiles, variant)));
    },
    async resign(id) {
      return codec.decodeMoveResult(await exec('game.resign', codec.encodeGameAction(id)));
    },
    async hint(id) {
      return codec.decodeHintResult(await exec('game.hint', codec.encodeGameAction(id)));
    },
    async evaluate(id, tiles, variant, signal) {
      return codec.decodeEvalResult(await exec('game.evaluate', codec.encodeEval(id, tiles, variant), signal));
    },
    async checkWord(id, word, variant) {
      return codec.decodeWordCheck(await exec('game.check_word', codec.encodeCheckWord(id, word, variant)));
    },
    async complaint(id, word, note) {
      await exec('game.complaint', codec.encodeComplaint(id, word, note));
    },
    async hideGame(id) {
      await exec('game.hide', codec.encodeGameAction(id));
    },
    async draftGet(id) {
      return codec.decodeDraftView(await exec('draft.get', codec.encodeGameAction(id)));
    },
    async draftSave(id, json) {
      await exec('draft.save', codec.encodeDraftSave(id, json));
    },

    async chatPost(id, body) {
      return codec.decodeChatMessage(await exec('chat.post', codec.encodeChatPost(id, body)));
    },
    async chatList(id) {
      return codec.decodeChatList(await exec('chat.list', codec.encodeGameAction(id)));
    },
    async nudge(id) {
      return codec.decodeChatMessage(await exec('chat.nudge', codec.encodeGameAction(id)));
    },
    async markChatRead(id) {
      await exec('chat.read', codec.encodeGameAction(id));
    },
    async feedbackSubmit(body, attachment, attachmentName, channel) {
      // The app build (Vite define) and the device's detected UTC offset ride with the report
      // so the operator sees which version it came from and the local time it was filed; the
      // caller need not pass them.
      await exec('feedback.submit', codec.encodeFeedbackSubmit(body, attachment, attachmentName, channel, __APP_VERSION__, browserOffset()));
    },
    async feedbackGet() {
      return codec.decodeFeedbackState(await exec('feedback.get', codec.empty()));
    },
    async feedbackUnread() {
      return codec.decodeFeedbackUnread(await exec('feedback.unread', codec.empty()));
    },

    async wallet() {
      return codec.decodeWallet(await exec('wallet.get', codec.empty()));
    },
    async catalog() {
      return codec.decodeCatalog(await exec('wallet.catalog', codec.empty()));
    },
    async walletBuy(productId: string) {
      return codec.decodeWallet(await exec('wallet.buy', codec.encodeWalletBuy(productId)));
    },
    async walletOrder(productId: string) {
      return codec.decodeWalletOrder(await exec('wallet.order', codec.encodeWalletOrder(productId)));
    },
    async walletReward(nonce: string) {
      return codec.decodeWallet(await exec('wallet.reward', codec.encodeWalletReward(nonce)));
    },

    async friendsList() {
      return codec.decodeFriendList(await exec('friends.list', codec.empty()));
    },
    async friendsIncoming() {
      return codec.decodeIncomingList(await exec('friends.incoming', codec.empty()));
    },
    async friendsOutgoing() {
      return codec.decodeOutgoingList(await exec('friends.outgoing', codec.empty()));
    },
    async friendRequest(accountId, gameId) {
      await exec('friends.request', codec.encodeTarget(accountId, gameId));
    },
    async friendRespond(requesterId, accept) {
      await exec('friends.respond', codec.encodeFriendRespond(requesterId, accept));
    },
    async friendCancel(accountId) {
      await exec('friends.cancel', codec.encodeTarget(accountId));
    },
    async unfriend(accountId) {
      await exec('friends.unfriend', codec.encodeTarget(accountId));
    },
    async friendCodeIssue() {
      return codec.decodeFriendCode(await exec('friends.code.issue', codec.empty()));
    },
    async friendCodeRedeem(code) {
      return codec.decodeRedeemResult(await exec('friends.code.redeem', codec.encodeRedeemCode(code)));
    },

    async blocksList() {
      return codec.decodeBlockList(await exec('blocks.list', codec.empty()));
    },
    async block(accountId, gameId) {
      await exec('blocks.add', codec.encodeTarget(accountId, gameId));
    },
    async unblock(accountId) {
      await exec('blocks.remove', codec.encodeTarget(accountId));
    },

    async invitationsList() {
      return codec.decodeInvitationList(await exec('invitation.list', codec.empty()));
    },
    async invitationCreate(inviteeIds, settings) {
      return codec.decodeInvitation(await exec('invitation.create', codec.encodeCreateInvitation(inviteeIds, settings)));
    },
    async invitationAccept(invitationId) {
      return codec.decodeInvitation(await exec('invitation.accept', codec.encodeInvitationAction(invitationId)));
    },
    async invitationDecline(invitationId) {
      return codec.decodeInvitation(await exec('invitation.decline', codec.encodeInvitationAction(invitationId)));
    },
    async invitationCancel(invitationId) {
      await exec('invitation.cancel', codec.encodeInvitationAction(invitationId));
    },

    async profileUpdate(p) {
      return codec.decodeProfile(await exec('profile.update', codec.encodeUpdateProfile(p)));
    },
    async linkEmailRequest(email) {
      await exec('link.email.request', codec.encodeLinkEmailRequest(email));
    },
    async linkEmailConfirm(email, code) {
      return codec.decodeLinkResult(await exec('link.email.confirm', codec.encodeLinkEmailConfirm(email, code)));
    },
    async linkEmailMerge(email, code) {
      return codec.decodeLinkResult(await exec('link.email.merge', codec.encodeLinkEmailConfirm(email, code)));
    },
    async linkTelegram(data) {
      return codec.decodeLinkResult(await exec('link.telegram.confirm', codec.encodeLinkTelegram(data)));
    },
    async linkTelegramMerge(data) {
      return codec.decodeLinkResult(await exec('link.telegram.merge', codec.encodeLinkTelegram(data)));
    },
    async linkVK(code, deviceId, codeVerifier) {
      return codec.decodeLinkResult(await exec('link.vk.confirm', codec.encodeLinkVK(code, deviceId, codeVerifier)));
    },
    async linkVKMerge(code, deviceId, codeVerifier) {
      return codec.decodeLinkResult(await exec('link.vk.merge', codec.encodeLinkVK(code, deviceId, codeVerifier)));
    },
    async linkUnlink(kind) {
      return codec.decodeLinkResult(await exec('link.unlink', codec.encodeLinkUnlink(kind)));
    },
    async changeEmailRequest(email) {
      await exec('link.email.change.request', codec.encodeLinkEmailRequest(email));
    },
    async changeEmailConfirm(email, code) {
      return codec.decodeLinkResult(await exec('link.email.change.confirm', codec.encodeLinkEmailConfirm(email, code)));
    },
    async deleteRequest() {
      return codec.decodeDeleteRequestResult(await exec('account.delete.request', codec.empty()));
    },
    async deleteConfirm(code, phrase) {
      await exec('account.delete.confirm', codec.encodeAccountDeleteConfirm(code, phrase));
    },
    async statsGet() {
      return codec.decodeStats(await exec('stats.get', codec.empty()));
    },
    async exportGcg(gameId) {
      return codec.decodeGcg(await exec('game.gcg', codec.encodeGameAction(gameId)));
    },
    async exportUrl(gameId, kind, dateLocale, actionLabels, timeZone) {
      return codec.decodeExportUrl(
        await exec('game.export_url', codec.encodeExportUrlRequest(gameId, kind, dateLocale, actionLabels, timeZone)),
      );
    },

    subscribe(onEvent, onError) {
      // No live stream in offline mode (the kill switch); return an inert unsubscribe.
      if (offlineMode.active) return () => {};
      const ctrl = new AbortController();
      void (async () => {
        try {
          for await (const ev of client.subscribe({}, { headers: headers(), signal: ctrl.signal })) {
            const pe = codec.decodeEvent(ev.kind, ev.payload);
            if (pe) onEvent(pe);
          }
        } catch (e) {
          if (!ctrl.signal.aborted) {
            const maintMs = maintenanceRetryMs(e);
            if (maintMs !== null) reportMaintenance(maintMs);
            const err = toGatewayError(e);
            if (err.code === UPDATE_REQUIRED) reportUpdateRequired();
            onError?.(err);
          }
        }
      })();
      return () => ctrl.abort();
    },
  };
}
