import type { Resource } from './resource.js';

/**
 * Per-chain native-asset semantics.
 *
 * Most EVM chains have an ETH-style native gas coin sent via `msg.value` (the
 * `evm-native` policy). A small number express their "native" coin as an
 * ERC-20 token: on `as-erc20` chains (Tempo) no `msg.value` coin exists at
 * all, while on `native-mirrored-erc20` chains (Arc) a real `msg.value` coin
 * exists but is canonically routed through an ERC-20 facade that mirrors the
 * native balance (`balanceOf == native wei / nativeScale`, with no balance
 * storage of its own). Code that needs to lower or simulate a `Resource` of
 * kind `"native"` should consult `getChainCapabilities(chainId)` rather than
 * hardcoding chain IDs.
 *
 * The compose compiler uses this registry to transparently normalise native
 * resources into ERC-20 resources on both ERC-20-canonical kinds at
 * schema-decode time (see `normalizeResource` below and the `ResourceSchema`
 * transform in `flowSchema.ts`).
 *
 * The two ERC-20-canonical kinds behave identically at the resource level —
 * `hasErc20CanonicalNative` is the predicate for that shared behaviour. They
 * diverge only at the simulation layer: `as-erc20` balances live in ordinary
 * token storage, while `native-mirrored-erc20` balances have no storage slot
 * and are satisfied by a native balance override scaled by `nativeScale`
 * (see compose-core's `rewritePreconditions`).
 *
 * This union is the extension point for future native-asset policies. A chain
 * with no canonical native asset would get a `reject-native` arm, under which a
 * `{ kind: "native" }` resource becomes a validation error rather than being
 * rewritten. No such chain exists yet, so the arm is not defined here.
 */
export type ChainCapabilities =
  | { readonly kind: 'evm-native'; readonly chainId: number }
  | {
      readonly kind: 'as-erc20';
      readonly chainId: number;
      readonly nativeErc20: NativeErc20;
    }
  | {
      readonly kind: 'native-mirrored-erc20';
      readonly chainId: number;
      readonly nativeErc20: NativeErc20;
      /** Native wei per 1 unit of the facade ERC-20 (1e12 on Arc: 18-dec native, 6-dec USDC). */
      readonly nativeScale: bigint;
    };

export interface NativeErc20 {
  readonly token: `0x${string}`;
  readonly symbol: string;
  readonly decimals: number;
}

/**
 * The zero-address sentinel that represents the native gas coin on
 * EVM-native chains. Exported so tests and call-sites can reference it
 * by name rather than inlining 40 zeros.
 *
 * Inlined as a literal rather than imported from `@lifi/utils`: `compose-spec`
 * is the wire-format leaf package and carries no `@lifi/*` dependencies
 * (enforced by `scripts/check-compose-boundaries.mjs`).
 */
export const EVM_NATIVE_SENTINEL: `0x${string}` =
  // eslint-disable-next-line @lifi/prefer-utils-constants -- compose-spec is the wire-format leaf and must not import @lifi/utils (enforced by scripts/check-compose-boundaries.mjs); the literal is intentional here
  '0x0000000000000000000000000000000000000000';

/**
 * Whether `address` is the EVM zero address (the native sentinel), compared
 * case-insensitively. Inlined comparison: `compose-spec` cannot import
 * `toAddress` from `@lifi/utils` (see `EVM_NATIVE_SENTINEL`).
 */
export const isZeroAddress = (address: string): boolean =>
  address.toLowerCase() === EVM_NATIVE_SENTINEL.toLowerCase();

export const TEMPO_CHAIN_ID = 4217;

export const TEMPO_NATIVE_ERC20: NativeErc20 = {
  token: '0x20C0000000000000000000000000000000000000',
  symbol: 'pathUSD',
  decimals: 6,
};

export const ARC_CHAIN_ID = 5042;

/**
 * Arc's native gas coin is USDC (18-decimal wei at the EVM level). The USDC
 * ERC-20 at this address is a view over native balances: `balanceOf` returns
 * `native wei / 1e12` and has no balance storage slot; allowances live in
 * regular storage. The composer interacts with USDC exclusively through this
 * facade, never via `msg.value`.
 */
export const ARC_NATIVE_ERC20: NativeErc20 = {
  token: '0x3600000000000000000000000000000000000000',
  symbol: 'USDC',
  decimals: 6,
};

// Derived from the facade's decimals so a decimal-count change cannot leave
// the scale silently wrong. Native wei is 18-decimal at the EVM level.
export const ARC_NATIVE_SCALE = 10n ** BigInt(18 - ARC_NATIVE_ERC20.decimals);

// Arc Testnet runs the same USDC facade at the same address, so it reuses
// Arc's facts rather than carrying a second copy.
export const ARC_TESTNET_CHAIN_ID = 5042002;

const REGISTRY: ReadonlyMap<number, ChainCapabilities> = new Map<
  number,
  ChainCapabilities
>([
  [
    TEMPO_CHAIN_ID,
    {
      kind: 'as-erc20',
      chainId: TEMPO_CHAIN_ID,
      nativeErc20: TEMPO_NATIVE_ERC20,
    },
  ],
  [
    ARC_CHAIN_ID,
    {
      kind: 'native-mirrored-erc20',
      chainId: ARC_CHAIN_ID,
      nativeErc20: ARC_NATIVE_ERC20,
      nativeScale: ARC_NATIVE_SCALE,
    },
  ],
  [
    ARC_TESTNET_CHAIN_ID,
    {
      kind: 'native-mirrored-erc20',
      chainId: ARC_TESTNET_CHAIN_ID,
      nativeErc20: ARC_NATIVE_ERC20,
      nativeScale: ARC_NATIVE_SCALE,
    },
  ],
]);

/**
 * Every chain with a non-default policy, in registration order. The registry
 * itself stays private so runtime callers go through `getChainCapabilities`;
 * this is the enumeration surface for tooling that must check *all* registered
 * chains against an external source (the slot-finder parity spec), where
 * scanning exported `*_CHAIN_ID` constants would silently miss a chain that
 * skipped the naming convention.
 *
 * @internal Exported only so `chainCapabilitiesSlotFinderParity.spec.ts` can
 * enumerate the registry. Not part of the package barrel.
 */
export const registeredChainCapabilities = (): readonly ChainCapabilities[] => [
  ...REGISTRY.values(),
];

export const getChainCapabilities = (chainId: number): ChainCapabilities =>
  REGISTRY.get(chainId) ?? { kind: 'evm-native', chainId };

/**
 * Structural fold over the `ChainCapabilities` union — the capabilities
 * counterpart of `foldResource`/`foldRef`. Dispatches on `kind` and hands each
 * case its narrowed fields, so consumers that must branch on the native-asset
 * policy (e.g. compose-core's `rewritePreconditions`) do so through one
 * combinator whose exhaustiveness the compiler enforces: adding a new arm to
 * the union above turns every `foldChainCapabilities` call into a type error
 * until it handles the new case.
 */
export const foldChainCapabilities = <R>(
  caps: ChainCapabilities,
  cases: {
    readonly evmNative: (chainId: number) => R;
    readonly asErc20: (nativeErc20: NativeErc20, chainId: number) => R;
    readonly nativeMirroredErc20: (
      nativeErc20: NativeErc20,
      nativeScale: bigint,
      chainId: number,
    ) => R;
  },
): R => {
  switch (caps.kind) {
    case 'evm-native':
      return cases.evmNative(caps.chainId);
    case 'as-erc20':
      return cases.asErc20(caps.nativeErc20, caps.chainId);
    case 'native-mirrored-erc20':
      return cases.nativeMirroredErc20(
        caps.nativeErc20,
        caps.nativeScale,
        caps.chainId,
      );
  }
};

/**
 * What a wire-level native-balance check (`nativeBalanceGte`) must become on
 * a chain, decided once here from the native-asset policy:
 *
 * - `keep` — `evm-native`: the native read is the right read.
 * - `rewrite` — `as-erc20` (Tempo): no `msg.value` coin exists, so the check
 *   becomes an `erc20BalanceGte` of `token`, the stand-in ERC-20. Amounts were
 *   always facade-denominated, so `minAmount` carries over verbatim.
 * - `reject` — `native-mirrored-erc20` (Arc): a native read returns real
 *   18-decimal wei, `nativeScale`× the facade's units, so no interpretation of
 *   `minAmount` is safe — reusing it on a facade read is 1e12 too strict for a
 *   wei-denominated check, keeping the native read lets a facade-denominated
 *   check pass 1e12 too easily. The check must be authored as
 *   `erc20BalanceGte` of the facade; `reason` says so.
 *
 * Consumers (the `AssertedPredicateSchema` decode and compose-core's derive
 * backstop) are adapters over this result, so the unit rule lives in one place
 * and the fold's exhaustiveness reaches every site.
 */
export type NativeCheckPolicy =
  | { readonly kind: 'keep' }
  | { readonly kind: 'rewrite'; readonly token: `0x${string}` }
  | { readonly kind: 'reject'; readonly reason: string };

export const nativeCheckPolicy = (chainId: number): NativeCheckPolicy =>
  foldChainCapabilities<NativeCheckPolicy>(getChainCapabilities(chainId), {
    evmNative: () => ({ kind: 'keep' }),
    asErc20: (nativeErc20) => ({ kind: 'rewrite', token: nativeErc20.token }),
    nativeMirroredErc20: (nativeErc20) => ({
      kind: 'reject',
      reason:
        `nativeBalanceGte is not accepted on chain ${chainId}: its canonical ` +
        `native asset is an ERC-20 facade whose units differ from native wei — ` +
        `author the check as erc20BalanceGte of ${nativeErc20.token}`,
    }),
  });

/**
 * Exact-kind check for `as-erc20` (currently Tempo only) — the rare case that
 * genuinely means "no `msg.value` coin exists on this chain". Most consumers
 * want `hasErc20CanonicalNative` instead, which also covers
 * `native-mirrored-erc20` chains (Arc), where the composer's ERC-20-only
 * policy applies even though `msg.value` works. Code that must treat the two
 * ERC-20-native kinds differently goes through `foldChainCapabilities` or
 * `nativeCheckPolicy`, never a second exact-kind predicate.
 */
export const isAsErc20Chain = (chainId: number): boolean =>
  getChainCapabilities(chainId).kind === 'as-erc20';

/**
 * The chain's stand-in native ERC-20 when its canonical native asset is an
 * ERC-20 (`as-erc20` and `native-mirrored-erc20`), `undefined` on plain
 * `evm-native` chains. Module-local narrowing helper behind the exported
 * predicates and rewrites below.
 */
const erc20CanonicalNative = (
  caps: ChainCapabilities,
): NativeErc20 | undefined =>
  caps.kind === 'as-erc20' || caps.kind === 'native-mirrored-erc20'
    ? caps.nativeErc20
    : undefined;

/**
 * Whether the chain's canonical native asset is an ERC-20 — true for both
 * `as-erc20` chains (Tempo: no `msg.value` coin exists) and
 * `native-mirrored-erc20` chains (Arc: `msg.value` exists but is never used).
 * This is the predicate for the shared resource-level behaviour: native
 * resources are rewritten to the ERC-20, native routing edges are dropped, and
 * a surviving native resource is a compile error.
 */
export const hasErc20CanonicalNative = (chainId: number): boolean =>
  erc20CanonicalNative(getChainCapabilities(chainId)) !== undefined;

/**
 * The address that represents the chain's native asset.
 *
 * On EVM-native chains this is the zero-address sentinel `0x0…0`. On chains
 * whose canonical native asset is an ERC-20 it is the chain's stand-in token
 * (PathUSD on Tempo, the USDC facade on Arc).
 */
export const canonicalNativeAddress = (chainId: number): `0x${string}` =>
  erc20CanonicalNative(getChainCapabilities(chainId))?.token ??
  EVM_NATIVE_SENTINEL;

/**
 * Whether `address` represents the native asset of `chainId`.
 *
 * On EVM-native chains, this is the case-insensitive zero-address check. On
 * chains whose canonical native asset is an ERC-20, the literal zero address
 * returns `false` — only the chain's stand-in ERC-20 address matches.
 */
export const isNativeAddressForChain = (
  chainId: number,
  address: string,
): boolean => {
  const target = canonicalNativeAddress(chainId);
  return address.toLowerCase() === target.toLowerCase();
};

/**
 * Whether `address` on `chainId` is the genuine `msg.value`-style native coin:
 * an `evm-native` chain's zero-address sentinel.
 *
 * This is the single predicate that gates `msg.value` semantics — choosing a
 * `NativeBalance` over an `Erc20Balance` simulation requirement, and skipping
 * the ERC-20 approval a native input would otherwise need. It returns `false`
 * for every address on a chain whose canonical native asset is an ERC-20
 * (including the zero sentinel): on `as-erc20` chains the "native" coin is a
 * real ERC-20 moved via `transferFrom`, never `msg.value`, and on
 * `native-mirrored-erc20` chains `msg.value` works but the composer's policy
 * is to move the coin exclusively through the ERC-20 facade. Use this rather
 * than re-deriving the check at call sites, and rather than
 * `isNativeAddressForChain`, which returns `true` for the stand-in ERC-20
 * (PathUSD on Tempo) and would wrongly route it to `msg.value`.
 */
export const isMsgValueNative = (chainId: number, address: string): boolean =>
  !hasErc20CanonicalNative(chainId) && isZeroAddress(address);

/**
 * Rewrite a single `Resource` according to its chain's capabilities.
 *
 * On chains with the default `evm-native` policy, every resource is returned
 * unchanged. On chains whose canonical native asset is an ERC-20 (`as-erc20`
 * Tempo, `native-mirrored-erc20` Arc), a resource of kind `"native"` is
 * rewritten into the equivalent ERC-20 resource pointing at the chain's
 * stand-in token (PathUSD on Tempo, the USDC facade on Arc).
 *
 * This is the rewrite primitive behind the `ResourceSchema` decode transform
 * (see `flowSchema.ts`), which is THE chokepoint: it runs every time a
 * `Resource` is parsed — flow inputs via `FlowSchema`, op configs via
 * `decodeConfig` — so every downstream pass (`normalizeFlow`, `resolve`,
 * `lower`, `simulate`) sees only ERC-20 resources on those chains.
 *
 * The function preserves referential identity when nothing changes (returns the
 * input `r` unchanged on evm-native chains and for ERC-20 resources) and is
 * idempotent: running it on an already-rewritten resource is a no-op.
 */
export const normalizeResource = (r: Resource): Resource => {
  if (r.kind !== 'native') return r;
  const erc20 = erc20CanonicalNative(getChainCapabilities(r.chainId));
  if (erc20 === undefined) return r;
  return {
    kind: 'erc20',
    chainId: r.chainId,
    token: erc20.token,
  };
};

/**
 * Address-level counterpart of `normalizeResource` for wire fields that carry a
 * native asset as a bare token string (a continuation outcome's `token`). On
 * chains whose canonical native asset is an ERC-20, the native sentinel is
 * rewritten to the chain's stand-in ERC-20; every other address passes through.
 */
export const normalizeNativeTokenAddress = (
  token: string,
  chainId: number,
): string =>
  hasErc20CanonicalNative(chainId) && isZeroAddress(token)
    ? canonicalNativeAddress(chainId)
    : token;
