import type { VerificationDescriptor } from './descriptor.js';
import type { InputSpec, Precondition } from './flow.js';
import type { Flow, ForwardTo } from './flowSchema.js';
import type { Outputs } from './output.js';
import type { Resource } from './resource.js';
import type { SettlementWire } from './zodSchemas.js';

export type SimulationPolicy = 'strict' | 'allow-revert';

export interface ComposeRun {
  readonly inputs: Record<string, InputSpec>;
  readonly preconditions?: readonly Precondition[];
  readonly signer: string;
  readonly assumptions?: Record<string, bigint>;
  readonly referrer?: string;
  readonly maxPriceImpactBps?: number;
  // Sugar for `flow.epilogue.remainder`; zap-backend desugars it before the
  // compile.
  readonly sweepTo?: ForwardTo;
  readonly simulationPolicy?: SimulationPolicy;
  /**
   * Also simulate the final user-facing transaction. Defaults to `false`;
   * reverts honour `simulationPolicy` and a success is echoed back as
   * `userProgramSimulation`.
   */
  readonly simulateUserProgram?: boolean;
  readonly checkOnChainAllowances?: boolean;
}

export interface ComposeCompileRequest {
  readonly flow: Flow;
  readonly run: ComposeRun;
}

export interface PriceImpact {
  readonly inputValueUsd: number;
  readonly outputValueUsd: number;
  readonly impactBps: number;
  readonly unpricedInputs: readonly string[];
  readonly unpricedOutputs: readonly string[];
}

export interface ApprovalEntry {
  readonly token: string;
  readonly spender: string;
  readonly amount: string;
  readonly transactionRequest: {
    readonly to: string;
    readonly data: string;
    readonly value: '0';
  };
}

export interface SimulationRevert {
  readonly code: number;
  readonly rawErrorBytes: string;
  readonly decodeResult?: {
    readonly errorCandidates?: readonly {
      readonly decodedErrorSignature: string;
      readonly decodedParams: readonly string[];
    }[];
    readonly error?: string;
  };
}

export interface ComposeTransactionRequest {
  readonly to: string;
  readonly chainId: number;
  readonly data: string;
  readonly value: string;
  readonly gasLimit?: string;
}

// Hand-mirrored from `ComposeActionSchema`, the OpenAPI source of truth in
// `@lifi/api-schemas`. Discriminated on `purpose`; the settlement-specific
// actions (`fundEscrow`, `signOrder`) name their settle node. Narrow on `kind`
// before reading `transactionRequest`.
export type ComposeAction =
  | {
      readonly kind: 'transaction';
      readonly purpose: 'approval' | 'execute';
      readonly submitter: 'signer' | 'anyone';
      readonly transactionRequest: ComposeTransactionRequest;
    }
  | {
      readonly kind: 'transaction';
      readonly purpose: 'fundEscrow';
      readonly submitter: 'signer' | 'anyone';
      readonly transactionRequest: ComposeTransactionRequest;
      readonly nodeId: string;
    }
  | {
      readonly kind: 'typedData';
      readonly purpose: 'signOrder';
      readonly submitter: 'signer';
      readonly nodeId: string;
      readonly typedData: readonly unknown[];
    };

// Continuation fields shared by the success and partial-error responses, so the
// two shapes cannot drift. `settlements` reuses the Zod-inferred wire type from
// `zodSchemas.ts`, pinning it to the server contract.
interface ComposeContinuationData {
  // How each `continuation.settle` node settles, keyed by node id. Absent for
  // a flow with no settle node.
  readonly settlements?: Record<string, SettlementWire>;
}

// One funding leg the compiled fill consumes: the resource input's name, its
// token (native → zero address) and chain, and the statically resolved amount
// as a decimal string (verified continuations, plan GD-8, seam C5). `nodeId`
// names the `continuation.settle` node this input funds (the `settlements` /
// `actions` key); absent when the input funds no settle leg (e.g. a plain
// swap's input).
export interface SpendEntry {
  readonly input: string;
  readonly token: string;
  readonly chainId: number;
  readonly amount: string;
  readonly nodeId?: string;
}

// The optional user-program simulation result, present only when the request
// opted in via `run.simulateUserProgram` and the simulation succeeded.
// Hand-mirrored from api-schemas' `ComposeUserProgramSimulationOkSchema`.
export interface ComposeUserProgramSimulation {
  readonly status: 'ok';
  readonly returnData: string;
}

// One advisory finding the compiler raised without failing the compile, e.g. a
// tight slippage bound on a highly volatile token. Hand-mirrored from
// api-schemas' `ComposeWarningSchema`. `path`, `port`, and `fix` mean what they
// mean on a compile error. `kind` is an open set: a new kind ships in a patch
// release, so a reader must tolerate a kind it does not know.
export interface ComposeWarning {
  readonly kind: string;
  readonly message: string;
  readonly path?: string;
  readonly port?: string;
  readonly fix?: string;
}

// The solver-extractable fill (verified continuations, GD-8/GD-6, seam C5),
// present on every compiled success. Hand-mirrored to api-schemas' `fill`
// object (the OpenAPI source of truth; this package cannot depend on it).
// `spends` is the amount the fill may spend of each funding input — the exact
// amount, or the pull cap of a non-exact deposit whose realised deposit is
// measured on-chain; `validUntilMs` is the fill freshness bound (earliest
// prepared-node expiry) — ABSENT = no expiry.
// The fill is transaction-scoped; the leg-scoped C4 verification echo lives in
// the sibling `verificationByNode` record.
export interface ComposeFill {
  readonly spends: readonly SpendEntry[];
  readonly validUntilMs?: number;
}

// One named epilogue forward as executed: the proxy's whole balance of
// `resource`, moved to `to`, as the simulation measured it. Hand-mirrored from
// api-schemas' `ExecutedForwardSchema`; the SDK decodes `amount` to `bigint`.
export interface ExecutedForward {
  readonly resource: Resource;
  readonly to: string;
  readonly amount: bigint;
}

// The flow's epilogue as executed. The remainder is not measured: it reports
// its resolved address only, and its effect on `outputs` is a re-owned
// `owner`. Absent when the flow has no epilogue (and never on a partial
// result, which measured nothing).
export interface ExecutedEpilogue {
  readonly forwards: readonly ExecutedForward[];
  readonly remainder?: string;
}

export interface ComposeCompileSuccessData extends ComposeContinuationData {
  // Every linear resource output port, consumed or terminal, keyed
  // `<nodeId>.<portName>`, and every resource input no node spends, keyed
  // `input.<name>`. See `Output` for the per-entry rules. Hand-mirrored
  // from api-schemas' `OutputSchema` (the OpenAPI source of truth; this
  // package cannot depend on it); the SDK decodes the wire strings to `bigint`.
  readonly outputs: Outputs;
  readonly epilogue?: ExecutedEpilogue;
  // The OpenAPI source of truth documents the optionality and funding modes.
  readonly transactionRequest?: ComposeTransactionRequest;
  readonly actions?: readonly ComposeAction[];
  readonly userProxy: string;
  readonly priceImpact?: PriceImpact;
  readonly approvals?: readonly ApprovalEntry[];
  // The optional user-program simulation echo, present only when the request
  // opted in via `run.simulateUserProgram` and the simulation succeeded.
  readonly userProgramSimulation?: ComposeUserProgramSimulation;
  // GD-8 settlement-fill surface (seam C5): the solver-extractable `fill`,
  // present on every success response — the funding legs it consumes and the
  // freshness bound (absent = no expiry).
  readonly fill?: ComposeFill;
  // The C4 verification echo, keyed by the flow node that carried the
  // commitment (the `continuation.commitment` node on a settlement
  // re-submission, each committing `continuation.settle` node on
  // authoring-time provider verification). Present only when the compile
  // committed a validation program; one entry per committing node, so a
  // fan-out across committed settles carries several.
  readonly verificationByNode?: Record<string, VerificationDescriptor>;
  // Advisory findings in the order the compiler raised them. Absent when it
  // raised none; never an empty array.
  readonly warnings?: readonly ComposeWarning[];
}

export interface ComposeCompilePartialData extends ComposeContinuationData {
  // Mirrors `ComposeCompileSuccessData.outputs`. A revert measured nothing, so
  // estimates are quotes and minimums are op-sourced.
  readonly outputs: Outputs;
  readonly transactionRequest: ComposeTransactionRequest;
  readonly userProxy: string;
  readonly simulationRevert: SimulationRevert;
  readonly approvals?: readonly ApprovalEntry[];
  readonly actions?: readonly ComposeAction[];
  // The optional user-program simulation echo, present only when the request
  // opted in via `run.simulateUserProgram` and the simulation succeeded.
  readonly userProgramSimulation?: ComposeUserProgramSimulation;
  // Mirrors `ComposeCompileSuccessData.warnings`: a reverted compile keeps the
  // warnings its compile raised.
  readonly warnings?: readonly ComposeWarning[];
}

export type ComposeCompileResult =
  | (ComposeCompileSuccessData & { readonly status: 'success' })
  | (ComposeCompilePartialData & {
      readonly status: 'partial';
      readonly error: { readonly kind: string; readonly message: string };
    });
