/**
 * Client-side reachability over the zap-pack catalog.
 *
 * `GET /compose/zap-packs` lists single routing edges. `POST /compose/route`
 * chains up to the server's hop budget of them, so the set of routable pairs
 * is the closure of the catalog, not the catalog itself. This module computes
 * that closure locally with the planner's admissibility rule, so an integrator
 * can offer every pair `route` connects without a request per pair.
 *
 * The rule, mirrored from the server's route search:
 *
 * - every edge except the last must leave its output in the proxy for the
 *   next edge to consume: no `availability`, no `recipient: 'required'`
 * - the last edge must be synchronous, or `availability: 'future'` when the
 *   caller opts into `allowAsyncRoutes`
 * - a route never visits the same token twice
 *
 * Amount bounds (`inAmountMin` / `inAmountMax`) on an intermediate edge
 * cannot be checked without an amount, so a pair reported here is routable
 * structurally, exactly as a listed edge is. Routes that open with a
 * `lifi.swap` are not enumerable and are not reported. The server also
 * drops blacklisted tokens as intermediates, which is server-side config
 * this module cannot see, so a reported pair may still answer
 * `no_route_error`.
 */

import type { ZapPackEdge, ZapPackOverview } from './discovery.js';

/** A token identified by address and chain. */
export interface TokenRef {
  readonly address: string;
  readonly chainId: number;
}

/** A from/to pair `POST /compose/route` can connect through the catalog. */
export interface RoutablePair {
  readonly in: TokenRef;
  readonly out: TokenRef;
  /** Catalog edges on the shortest admissible route; `1` is a listed edge. */
  readonly hops: number;
}

export interface ReachabilityOptions {
  /**
   * Hop budget. The server's `no_route_error` reports its effective value in
   * `details.maxHops`; the deployment default is 2.
   */
  readonly maxHops?: number;
  /**
   * Admit a route whose last edge has `availability: 'future'`. Mirrors the
   * `allowAsyncRoutes` request option; such a pair is a `no_route_error`
   * without it.
   */
  readonly allowAsyncRoutes?: boolean;
}

export interface Reachability {
  readonly maxHops: number;
  /** Whether `route` can connect `from` to `to` through the catalog. */
  readonly canRoute: (from: TokenRef, to: TokenRef) => boolean;
  /** Every pair starting at `from`, shortest routes first. */
  readonly routableFrom: (from: TokenRef) => readonly RoutablePair[];
  /** Every routable pair in the catalog. */
  readonly pairs: () => readonly RoutablePair[];
}

const DEFAULT_MAX_HOPS = 2;

const tokenKey = (token: TokenRef): string =>
  `${token.chainId}:${token.address.toLowerCase()}`;

const isSync = (edge: ZapPackEdge): boolean => edge.availability === undefined;

// The output stays in the proxy, so a following edge can consume it.
const isProxyHeld = (edge: ZapPackEdge): boolean =>
  isSync(edge) && edge.recipient !== 'required';

// One edge out of a frontier token. Records the pair it completes, and returns
// its output when a further hop may consume it (proxy-held) and no shorter
// path already expanded that token.
const visitEdge = ({
  edge,
  from,
  depth,
  sourceKey,
  isTerminal,
  found,
  expanded,
}: {
  readonly edge: ZapPackEdge;
  readonly from: TokenRef;
  readonly depth: number;
  readonly sourceKey: string;
  readonly isTerminal: (edge: ZapPackEdge) => boolean;
  readonly found: Map<string, RoutablePair>;
  readonly expanded: Set<string>;
}): TokenRef | undefined => {
  const key = tokenKey(edge.out);
  if (key === sourceKey) return undefined;
  if (isTerminal(edge) && !found.has(key)) {
    found.set(key, { in: from, out: edge.out, hops: depth });
  }
  if (!isProxyHeld(edge) || expanded.has(key)) return undefined;
  expanded.add(key);
  return edge.out;
};

// Every pair reachable from one token within `maxHops`, breadth-first so the
// recorded hop count is the shortest one.
const closureFrom = ({
  byIn,
  from,
  maxHops,
  isTerminal,
}: {
  readonly byIn: ReadonlyMap<string, readonly ZapPackEdge[]>;
  readonly from: TokenRef;
  readonly maxHops: number;
  readonly isTerminal: (edge: ZapPackEdge) => boolean;
}): Map<string, RoutablePair> => {
  const sourceKey = tokenKey(from);
  const found = new Map<string, RoutablePair>();
  const expanded = new Set<string>([sourceKey]);
  let frontier: readonly TokenRef[] = [from];
  for (let depth = 1; depth <= maxHops && frontier.length > 0; depth++) {
    const next: TokenRef[] = [];
    for (const node of frontier) {
      for (const edge of byIn.get(tokenKey(node)) ?? []) {
        const out = visitEdge({
          edge,
          from,
          depth,
          sourceKey,
          isTerminal,
          found,
          expanded,
        });
        if (out) next.push(out);
      }
    }
    frontier = next;
  }
  return found;
};

const indexByIn = (
  packs: readonly ZapPackOverview[],
): Map<string, ZapPackEdge[]> => {
  const byIn = new Map<string, ZapPackEdge[]>();
  for (const pack of packs) {
    for (const edge of pack.edges) {
      const key = tokenKey(edge.in);
      const list = byIn.get(key);
      if (list) list.push(edge);
      else byIn.set(key, [edge]);
    }
  }
  return byIn;
};

/**
 * Builds a reachability index over the packs returned by
 * {@link ComposeClient.getZapPacks}. Per-source closures are computed on
 * first use and memoised, so `canRoute` on a handful of pairs stays cheap
 * while `pairs()` enumerates everything.
 */
export const buildReachability = (
  packs: readonly ZapPackOverview[],
  options: ReachabilityOptions = {},
): Reachability => {
  const maxHops = options.maxHops ?? DEFAULT_MAX_HOPS;
  const allowAsync = options.allowAsyncRoutes ?? false;
  const isTerminal = (edge: ZapPackEdge): boolean =>
    isSync(edge) || (allowAsync && edge.availability === 'future');

  const byIn = indexByIn(packs);
  const memo = new Map<string, Map<string, RoutablePair>>();
  const closure = (from: TokenRef): Map<string, RoutablePair> => {
    const key = tokenKey(from);
    const cached = memo.get(key);
    if (cached) return cached;
    const computed = closureFrom({ byIn, from, maxHops, isTerminal });
    memo.set(key, computed);
    return computed;
  };

  return {
    maxHops,
    canRoute: (from, to) => closure(from).has(tokenKey(to)),
    routableFrom: (from) => [...closure(from).values()],
    pairs: () => {
      const sources = new Map<string, TokenRef>();
      for (const pack of packs) {
        for (const edge of pack.edges) sources.set(tokenKey(edge.in), edge.in);
      }
      const all: RoutablePair[] = [];
      for (const source of sources.values()) {
        all.push(...closure(source).values());
      }
      return all;
    },
  };
};
