import { type Effect, ParseResult, Schema, type SchemaAST } from 'effect';

import {
  isZeroAddress,
  nativeCheckPolicy,
  normalizeNativeTokenAddress,
} from './chainCapabilities.js';
import {
  ChainIdSchema,
  EpochMsSchema,
  EVMAddressString,
  FlowSchema,
  IntegerString,
} from './flowSchema.js';

// The op id of the self-describing commitment carrier node embedded in a
// persisted committed continuation action (verified continuations, plan GD-8,
// seam C5). It is wire vocabulary — the node's `op` value inside a re-submitted
// `Flow` — so it lives here as the single source of truth. The op definition
// (compose-builtins) and the settlement-echo trigger (compose-core) both import
// this constant; a drift between them would make the echo fail open (a genuine
// settlement fill answered as an ordinary flow with no descriptor).
export const CONTINUATION_COMMITMENT_OP_ID = 'continuation.commitment';

// A single outcome of a deferred settlement: `token` must be delivered to
// `destination` on `chainId`. Amounts are decimal strings on the wire because
// JSON has no bigint; `chainId` reuses the shared `ChainIdSchema` from
// `flowSchema.ts`. `token` becomes a `Resource` in `continuation.settle`'s
// output and `destination` its owner, so both take the address rule.
//
// `minAmount` is the floor the author commits to. An author may omit it: a
// committed provider proves the floor from the settle's `continuationFlow`,
// and an authored value can only raise what the proof delivers. A provider
// that proves nothing requires it. A zero `minAmount` decodes (`IntegerString`
// admits 0) and the pipeline reads it as omitted: the committed floor is the
// larger of the authored and the proven floor, and a floor of 0 is rejected.
//
// The decode transform mirrors `ResourceSchema`: `token` never flows through
// `ResourceSchema`, so on `as-erc20` chains the native sentinel is rewritten to
// the chain's ERC-20 here — otherwise downstream would treat the delivery asset
// as native. Encode is the identity (the ERC-20 form is valid wire input).
// Field order is wire-visible: a committed action serializes the decoded
// struct, so both structs below keep `minAmount` second.
const outcomeFields = <
  M extends Schema.Schema.All | Schema.PropertySignature.All,
>(
  minAmount: M,
) => ({
  token: EVMAddressString,
  minAmount,
  destination: EVMAddressString,
  chainId: ChainIdSchema,
});

const normalizingOutcome = <
  A extends { readonly token: string; readonly chainId: number },
  I,
>(
  raw: Schema.Schema<A, I>,
) =>
  Schema.transform(raw, Schema.typeSchema(raw), {
    strict: true,
    decode: (outcome) => ({
      ...outcome,
      token: normalizeNativeTokenAddress(outcome.token, outcome.chainId),
    }),
    encode: (outcome) => outcome,
  });

// The authored outcome: `minAmount` optional.
export const ContinuationOutcomeSchema = normalizingOutcome(
  Schema.Struct(outcomeFields(Schema.optional(IntegerString))),
);

// The committed outcome: the floor the provider registered, always present.
// The `continuation.commitment` node and every provider's `prepare()` read
// this shape.
export const CommittedOutcomeSchema = normalizingOutcome(
  Schema.Struct(outcomeFields(IntegerString)),
);

// Backend-neutral config for the `continuation.settle` op. Note: the funding
// input is NOT a config field — the deferred step's funding resource/amount is
// wired via the node's `bind.input` (see M3b). Only the committed terms below
// (`outcomes`/`continuationFlow`/`validity`/`provider`) are the
// node's `config`.
//
// `continuationFlow` is an inlined Flow document that the settlement backend
// stores and runs at settlement time against the deferred proceeds (used by the
// cross-chain path). It is independent of the Flow's top-level `continuation`
// pointer. `FlowSchema` lives in the same package, so importing it here keeps
// `compose-spec` dependency-free.
export const ContinuationIntentSchema = Schema.Struct({
  // Zero outcomes are admitted only for an exact settle, whose bound leg is its
  // only enforcement; compose-core's first two capability gates
  // (`resolveContinuationProvider.ts:CAPABILITY_CHECKS`) enforce that pairing
  // and the one-outcome maximum, since the schema cannot see `exact`.
  outcomes: Schema.Array(ContinuationOutcomeSchema),
  continuationFlow: Schema.optional(FlowSchema),
  validity: Schema.Struct({ expiresAtMs: EpochMsSchema }),
  provider: Schema.optional(Schema.String),
  // Funding-path mode. The HTTP wire contract is documented by
  // `ComposeActionsSchema` in `@lifi/api-schemas`. A settle funded by a
  // bridge delivery (`'delivered'` on the artifact) is inferred from its
  // binding and never authored.
  funding: Schema.optional(Schema.Literal('inline', 'external')),
  // The address on the escrow's chain that receives the escrow balance on
  // expiry; defaults to the signer. The zero address would burn that balance.
  refund: Schema.optional(
    EVMAddressString.pipe(
      Schema.filter((address) => !isZeroAddress(address), {
        message: () => 'refund must not be the zero address',
      }),
    ),
  ),
  // Bind the settlement to the leg's compiled bytes: the fill runs exactly the
  // calldata the compile proved, so the solver chooses nothing. Needs a
  // `continuationFlow` and a provider that advertises the capability.
  exact: Schema.optional(Schema.Boolean),
});

// A `0x`-prefixed string, prefix checked only. Continuation vocabulary no
// longer uses it for addresses (those take `EVMAddressString`); it remains
// for the escrow and binding records below, which the settlement service
// returns, and for op configs not yet tightened. `zodSchemas.ts` mirrors it
// as `hexStringZod`.
export const HexStringSchema = Schema.String.pipe(Schema.startsWith('0x'));

// The escrow a settlement provider registered for a settle node, disclosed on
// the `transaction` artifact and projected onto the wire as
// `settlements[nodeId].escrow`. Present only when the provider registered one;
// providers that fund no escrow never set it. Every field is present whenever
// the record is. Mirrored by `SettlementEscrowZod`.
//
// - `chainId` + `address` — the escrow and its chain. Every registration gets
//   a fresh escrow, so the pair identifies this one settlement; never fund it
//   for another.
// - `token` + `amount` — the funding asset (native → `EVM_NATIVE_SENTINEL`)
//   and the raw amount the escrow was sized from. The program transfers the
//   amount realised at execution, which can differ when an upstream op
//   supplies the funding.
// - `cap` — the committed funding allocation: the most a fill may spend from
//   the escrow. A balance above it stays in the escrow.
// - `floor` — the registered funding floor: the least balance that arms a
//   fill. A smaller balance waits for expiry and is refunded.
// - `owner` — the account that controls the escrow and can sweep it.
// - `refund` — where the escrow balance returns when the settlement expires.
// - `expiresAtMs` — when the settlement expires: the effective expiry the
//   settlement service stores, which can be earlier than the authored
//   `validity.expiresAtMs`; after it the escrow is never filled and its
//   balance is refunded.
const Phase1EscrowSchema = Schema.Struct({
  chainId: ChainIdSchema,
  address: HexStringSchema,
  token: HexStringSchema,
  amount: Schema.String,
  cap: Schema.String,
  floor: Schema.String,
  owner: HexStringSchema,
  refund: HexStringSchema,
  expiresAtMs: Schema.Number.pipe(Schema.int(), Schema.positive()),
});

// The executor binding of an `exact` settle, disclosed on the `transaction`
// artifact and projected onto the wire as `settlements[nodeId].binding`.
// Absent unless the settle is `exact`. Every field is present whenever the
// record is. Mirrored by `SettlementBindingZod`.
//
// - `executionTarget` — the executor that runs the fill.
// - `payload` — the executor call the settlement service hashed into the
//   escrow's execute constraint; a fill that runs anything else is rejected.
// - `payloadHash` — `keccak256(payload)`, the committed hash.
// - `calldata` — what the executor's proxy runs: the leg's compiled bytes.
// - `approvals` — the allowances the executor grants before it runs
//   `calldata`.
const Phase1BindingSchema = Schema.Struct({
  executionTarget: HexStringSchema,
  payload: HexStringSchema,
  payloadHash: HexStringSchema,
  calldata: HexStringSchema,
  approvals: Schema.Array(
    Schema.Struct({ token: HexStringSchema, spender: HexStringSchema }),
  ),
});

// Internal phase-1 artifact. The HTTP layer projects its `escrow` and
// `binding` onto `settlements` and publishes external-funding calldata and
// typed data through `ComposeActionsSchema`. The internal `transactionRequest`
// remains optional because inline funding does not produce a submittable
// transfer, and `delivered` funding (a bridge delivers into the escrow)
// produces none either.
export const Phase1ArtifactSchema = Schema.Union(
  Schema.Struct({
    kind: Schema.Literal('transaction'),
    funding: Schema.Literal('inline', 'external', 'delivered'),
    transactionRequest: Schema.optional(
      Schema.Struct({
        to: Schema.String,
        data: Schema.String,
        value: Schema.String,
        chainId: Schema.Number,
      }),
    ),
    escrow: Schema.optional(Phase1EscrowSchema),
    binding: Schema.optional(Phase1BindingSchema),
  }),
  Schema.Struct({
    kind: Schema.Literal('signables'),
    typedData: Schema.Array(Schema.Unknown),
  }),
  Schema.Struct({ kind: Schema.Literal('none') }),
);

// The members of `AssertionSpec` below: each is an absolute predicate over
// on-chain state that a derived validation program enforces at settlement.
// Every register operand of a member (an owner, a call argument, a threshold)
// becomes a committed validation param; the constants a member bakes into the
// program (a token, a call target, a function signature) are committed by the
// program hash. Amounts are decimal strings on the wire because JSON has no
// bigint.
//
// - `erc20BalanceGte` — `owner`'s balance of `token` on `chainId` is at least
//   `minAmount`.
// - `nativeBalanceGte` — `owner`'s native balance on `chainId` is at least
//   `minAmount`.
// - `call` — a static call to `to` on `chainId` of `signature` with `args`,
//   whose `uint256` return compares against `threshold` using `comparator`.
//
// Addresses (`token`/`to`) take `EVMAddressString`, `owner` takes
// `AssertionOwnerSchema` (below), and amounts
// (`minAmount`/`threshold`) take `IntegerString`, so a malformed value fails at
// decode instead of in lowering. Amounts are not positive-only: a persisted
// descriptor re-decodes these members, and a zero threshold is well-formed
// (just vacuous).

// A balance owner: a concrete address, or one of the two symbolic owners
// `"escrow"` / `"delivery"`. The symbolic owners are thunk terms: a committed
// thunk carries one when it is assembled by hand (the uc1 fixtures) or echoed
// back from the commitment, and the derivation resolves each to a
// validator-injected register (see the verified-continuations derivation). An
// op's `asserts` hook cannot emit one: in compose-core its spec type is
// `AssertionSpecOf<H>`, so an owner is always an operand the hook received.
// The descriptor discloses the same values the program derives from.
export const AssertionOwnerSchema = Schema.Union(
  EVMAddressString,
  Schema.Literal('escrow', 'delivery'),
);
export type AssertionOwner = typeof AssertionOwnerSchema.Type;

// The three absolute members are exported by name so `AssertionSpecSchema` and
// the descriptor's predicate union share one declaration.
export const Erc20BalanceGteSpecSchema = Schema.Struct({
  kind: Schema.Literal('erc20BalanceGte'),
  chainId: ChainIdSchema,
  token: EVMAddressString,
  owner: AssertionOwnerSchema,
  minAmount: IntegerString,
});

export const NativeBalanceGteSpecSchema = Schema.Struct({
  kind: Schema.Literal('nativeBalanceGte'),
  chainId: ChainIdSchema,
  owner: AssertionOwnerSchema,
  minAmount: IntegerString,
});

// `signature` is the ethers human-readable form, e.g.
// `function balanceOf(address) returns (uint256)`, with exactly one `uint256`
// return and only `address` / `uint256` parameters. `args` has one entry per
// parameter, each written as that parameter's canonical string (a 20-byte hex
// address, a decimal integer). The derivation parses the signature once and
// rejects anything else; this schema is a shape check only.
export const CallCheckSpecSchema = Schema.Struct({
  kind: Schema.Literal('call'),
  chainId: ChainIdSchema,
  to: EVMAddressString,
  signature: Schema.String,
  args: Schema.Array(Schema.String),
  comparator: Schema.Literal('gte', 'eq', 'lte'),
  threshold: IntegerString,
});

type Erc20BalanceGteSpec = typeof Erc20BalanceGteSpecSchema.Type;
type NativeBalanceGteSpec = typeof NativeBalanceGteSpecSchema.Type;

// The equivalent `erc20BalanceGte` of a `nativeBalanceGte` spec: `token` is
// the chain's stand-in ERC-20 (PathUSD on Tempo), every other field carried
// through.
const asErc20BalanceGteCheck = (
  check: NativeBalanceGteSpec,
  token: `0x${string}`,
): Erc20BalanceGteSpec => ({
  kind: 'erc20BalanceGte',
  chainId: check.chainId,
  token,
  owner: check.owner,
  minAmount: check.minAmount,
});

// Decode adapter over `nativeCheckPolicy` (`chainCapabilities.ts` holds the
// unit reasoning): a `nativeBalanceGte` check is kept on an evm-native chain,
// rewritten to `erc20BalanceGte` of the stand-in ERC-20 on an `as-erc20`
// chain, and rejected on a `native-mirrored-erc20` chain. Used by the
// descriptor's `AssertedPredicateSchema` so the disclosed and the committed
// predicate derive the same program (authoring↔settlement hash parity).
export const decodeNativeBalanceGte = (
  check: NativeBalanceGteSpec,
  ast: SchemaAST.AST,
): Effect.Effect<
  NativeBalanceGteSpec | Erc20BalanceGteSpec,
  ParseResult.ParseIssue
> => {
  const policy = nativeCheckPolicy(check.chainId);
  switch (policy.kind) {
    case 'keep':
      return ParseResult.succeed(check);
    case 'rewrite':
      return ParseResult.succeed(asErc20BalanceGteCheck(check, policy.token));
    case 'reject':
      return ParseResult.fail(new ParseResult.Type(ast, check, policy.reason));
  }
};

// The derivation vocabulary (verified continuations, plan GD-1). An
// `AssertionSpec` is the structured, backend-neutral form of one invariant a
// derived validation program must enforce against the executor's re-quoted
// fill: one of the three members above, reused verbatim.
export const AssertionSpecSchema = Schema.Union(
  Erc20BalanceGteSpecSchema,
  NativeBalanceGteSpecSchema,
  CallCheckSpecSchema,
);

export type ContinuationOutcome = typeof ContinuationOutcomeSchema.Type;
export type CommittedOutcome = typeof CommittedOutcomeSchema.Type;
export type ContinuationIntent = typeof ContinuationIntentSchema.Type;
export type Phase1Artifact = typeof Phase1ArtifactSchema.Type;
export type AssertionSpec = typeof AssertionSpecSchema.Type;
export type CallCheckSpec = typeof CallCheckSpecSchema.Type;

// The outcome a `continuation.settle` node's single `output` port stands for.
// The wire format admits several outcomes, but the op produces one resource,
// discloses one owner, and every shipped provider rejects a multi-outcome
// intent, so the first outcome is the settled one everywhere. `undefined`
// means a zero-outcome exact settle: the bound leg consumes the funding and
// delivers nothing, so the `output` port carries no resource. Keep this the
// only place that picks `[0]`: a multi-outcome design changes one accessor,
// not a scatter of `[0]`s. Generic over the intent so a `CommittedIntent`
// yields a `CommittedOutcome`.
export const settledOutcome = <
  I extends { readonly outcomes: readonly unknown[] },
>(
  intent: I,
): I['outcomes'][number] | undefined => intent.outcomes[0];
