import z from 'zod';

import {
  BYTES32_LOWER_HEX,
  DECIMAL_UINT,
  EVM_ADDRESS_HEX,
  MAX_UINT256,
} from './hexPatterns.js';

// A positive integer chain id. Zod mirror of the Effect `ChainIdSchema` in
// `flowSchema.ts`, single-sourced so the wire schemas stay consistent.
export const chainIdZod = z.number().int().positive();

// Zod mirrors of `EVMAddressString` and `IntegerString` in `flowSchema.ts`,
// built from the same `hexPatterns.ts` constants.
// `continuationParity.spec.ts` holds the two sides in lockstep.
const evmAddressZod = z.string().regex(EVM_ADDRESS_HEX);
// One refinement, like `IntegerString`'s filter: Zod runs later checks after
// a failed `.regex`, so a separate bound check would hand `BigInt` a
// non-digit string and throw.
const uintStringZod = z
  .string()
  .refine((value) => DECIMAL_UINT.test(value) && BigInt(value) <= MAX_UINT256, {
    message: 'expected a uint256 decimal integer string',
  });

const SolTypeZod = z.enum([
  'uint8',
  'uint16',
  'uint32',
  'uint64',
  'uint128',
  'uint256',
  'int128',
  'int256',
  'address',
  'bool',
  'bytes',
  'bytes4',
  'bytes32',
  'string',
]);

export const ResourcePortZod = z.object({
  kind: z.literal('resource'),
  name: z.string(),
  accepts: z.enum(['erc20', 'native', 'any']),
  mode: z.enum(['linear', 'copy']),
  optional: z.boolean().optional(),
});

export const HANDLE_UNITS = [
  'raw',
  'wad',
  'ray',
  'bps',
  'token-decimals',
] as const;

// NOTE: the uint members below must stay in sync with the `UintN` union in
// `ts/packages/lifi_ir1_ts/src/types/ValueHandle.ts`. When adding a new
// uintN width, update both locations.
export const STATIC_SOL_TYPES = [
  'uint256',
  'uint128',
  'uint64',
  'uint32',
  'uint16',
  'uint8',
  'address',
  'bool',
  'bytes32',
] as const;

export const HandleUnitsZod = z.enum(HANDLE_UNITS);

export const StaticSolTypeZod = z.enum(STATIC_SOL_TYPES);

const STATIC_SOL_TYPE_SET: ReadonlySet<string> = new Set(STATIC_SOL_TYPES);

export const isStaticSolType = (value: string): value is StaticSolType =>
  STATIC_SOL_TYPE_SET.has(value);

export const HandlePortZod = z.object({
  kind: z.literal('handle'),
  name: z.string(),
  type: SolTypeZod,
  mode: z.enum(['linear', 'copy']),
  expose: z.boolean().optional(),
  units: HandleUnitsZod.optional(),
  optional: z.boolean().optional(),
});

export const InputPortZod = z.discriminatedUnion('kind', [
  ResourcePortZod,
  HandlePortZod,
]);

export const ResourceOutputPortZod = z.object({
  kind: z.literal('resource_output'),
  name: z.string(),
  mode: z.enum(['linear', 'copy']),
  availability: z.enum(['now', 'future']).optional(),
  providesMinimum: z.boolean().optional(),
  omitIfZero: z.boolean().optional(),
  deliveryAddressInput: z.string().optional(),
  // Declares an output *family*: the port expands, when a call's config is
  // bound, into one instance per element of the config array named here, or
  // into as many instances as the non-negative integer named here. Instances
  // are ordinary ports named `<name>.<index>`; see
  // `outputFamilies.ts:expandOutputPorts`.
  countFrom: z.string().optional(),
});

export const OutputPortZod = z.discriminatedUnion('kind', [
  ResourceOutputPortZod,
  HandlePortZod,
]);

export const ManifestOperationZod = z.object({
  id: z.string(),
  description: z.string().optional(),
  inputs: z.array(InputPortZod),
  outputs: z.array(OutputPortZod),
  configSchema: z.unknown().optional(),
});

const PortKindEnum = z.enum(['resource', 'resource_output', 'handle']);

const SelectorMatchZod = z.object({
  kind: z.union([PortKindEnum, z.array(PortKindEnum)]),
  mode: z.enum(['linear', 'copy']).optional(),
  type: z.enum(['erc20', 'native', 'any']).optional(),
});

const ConfigSelectionZod = z.object({
  kind: z.literal('config'),
  configKey: z.string(),
  cardinality: z.enum(['one', 'many']),
});

const AllMatchingSelectionZod = z.object({
  kind: z.literal('all_matching'),
});

const SelectorSelectionZod = z.discriminatedUnion('kind', [
  ConfigSelectionZod,
  AllMatchingSelectionZod,
]);

export const GuardSelectorZod = z.object({
  binding: z.string(),
  source: z.enum(['inputs', 'outputs']),
  match: SelectorMatchZod,
  selection: SelectorSelectionZod,
});

export const GuardCompatibilityZod = z.object({
  selectors: z.array(GuardSelectorZod),
});

export const ManifestGuardZod = z.object({
  kind: z.string(),
  description: z.string().optional(),
  configSchema: z.unknown().optional(),
  compatibility: GuardCompatibilityZod.optional(),
});

export const ManifestMaterialiserZod = z.object({
  kind: z.string(),
  description: z.string().optional(),
  accepts: z.enum(['resource', 'handle', 'any']),
  configSchema: z.unknown().optional(),
});

export const ManifestPreconditionZod = z.object({
  type: z.string(),
  description: z.string().optional(),
  configSchema: z.unknown().optional(),
});

// The deployment's planning bounds for `POST /compose/route`. `maxRouteHops`
// is the hop ceiling, swap included; `1` means the deployment never chains.
// `swapHops` is where a planned route may contain an aggregator swap: only as
// its first hop (`head`), or nowhere (`none`). The bounds are necessary, not
// sufficient: a pair inside them can still return `no_route_error`.
export const ManifestRoutingZod = z.object({
  maxRouteHops: z.number().int().min(1),
  swapHops: z.enum(['head', 'none']),
});

export const ComposeManifestZod = z.object({
  manifestVersion: z.number(),
  manifestHash: z.string(),
  flowSchema: z.object({}).passthrough(),
  operations: z.array(ManifestOperationZod),
  guards: z.array(ManifestGuardZod),
  materialisers: z.array(ManifestMaterialiserZod),
  preconditions: z.array(ManifestPreconditionZod).optional(),
  // Deployment data, not catalog data: `GET /compose/manifest` sets it from
  // compose 0.10.2 on, the static catalog manifest never does, and
  // `manifestHash` does not cover it. Absent means unknown bounds, not a
  // default: a client must not reject a pair on bounds it was not given.
  routing: ManifestRoutingZod.optional(),
});

// Prefix-only `0x` check, mirroring `HexStringSchema`; used only by the escrow
// and binding records, which the settlement service returns.
const hexStringZod = z.string().startsWith('0x');

// Mirror of `Phase1EscrowSchema` (continuation.ts): the escrow a settlement
// provider registered for a settle node, disclosed as named fields so a client
// reads the terms without decoding the `fundEscrow` calldata. `chainId` +
// `address` identify the funding user's escrow on that chain. Amounts are
// raw-unit decimal strings. `expiresAtMs` is the effective expiry in epoch
// milliseconds; `fill.validUntilMs` is never later than it.
export const SettlementEscrowZod = z.object({
  chainId: chainIdZod,
  address: hexStringZod,
  token: hexStringZod,
  amount: z.string(),
  cap: z.string(),
  floor: z.string(),
  owner: hexStringZod,
  refund: hexStringZod,
  expiresAtMs: z.number().int().positive(),
});

// Mirror of `Phase1BindingSchema` (continuation.ts): the executor binding of
// an `exact` settle. The settlement service hashed `payload` into the escrow's
// execute constraint, so a fill runs only that executor call;
// `payloadHash === keccak256(payload)`. `calldata` is what the executor's
// proxy runs (the leg's compiled bytes) and `approvals` the allowances it
// grants first. Absent unless the settle is `exact`. `approvals` is
// `.readonly()` so the inferred type matches the readonly artifact type
// without a copy at the handler.
export const SettlementBindingZod = z.object({
  executionTarget: hexStringZod,
  payload: hexStringZod,
  payloadHash: hexStringZod,
  calldata: hexStringZod,
  approvals: z
    .array(z.object({ token: hexStringZod, spender: hexStringZod }))
    .readonly(),
});

// Mirror of `AssertionOwnerSchema` (continuation.ts): a concrete address or
// one of the two symbolic owners resolved at settlement.
const assertionOwnerZod = z.union([
  evmAddressZod,
  z.enum(['escrow', 'delivery']),
]);

// HTTP-layer mirror of `AssertionSpecSchema` (continuation.ts): the two
// balance members and the `call` member. Amounts are decimal strings on the
// wire; the `call` member's `signature` / `args` contract is documented on
// `CallCheckSpecSchema`, and its `args` is `.readonly()` so the inferred type
// matches the readonly spec type without a copy at the handler. It is also the
// descriptor's `assertedPredicate` element (`AssertedPredicateSchema` decodes
// the same shape).
export const AssertionSpecZod = z.discriminatedUnion('kind', [
  z.object({
    kind: z.literal('erc20BalanceGte'),
    chainId: chainIdZod,
    token: evmAddressZod,
    owner: assertionOwnerZod,
    minAmount: uintStringZod,
  }),
  z.object({
    kind: z.literal('nativeBalanceGte'),
    chainId: chainIdZod,
    owner: assertionOwnerZod,
    minAmount: uintStringZod,
  }),
  z.object({
    kind: z.literal('call'),
    chainId: chainIdZod,
    to: evmAddressZod,
    signature: z.string(),
    args: z.array(z.string()).readonly(),
    comparator: z.enum(['gte', 'eq', 'lte']),
    threshold: uintStringZod,
  }),
]);

export type AssertionSpecWire = z.infer<typeof AssertionSpecZod>;

export const VerificationDescriptorZod = z.object({
  validationProgramHash: z.string().regex(BYTES32_LOWER_HEX),
  // The C5 echo's second hash (GD-8): the params-vector content hash
  // (`paramsHash`, C1). Required and jointly necessary with the value-blind
  // `validationProgramHash`.
  paramsHash: z.string().regex(BYTES32_LOWER_HEX),
  assertedPredicate: z.array(AssertionSpecZod).readonly(),
});

export type VerificationDescriptorWire = z.infer<
  typeof VerificationDescriptorZod
>;

// What the response says about how one `continuation.settle` node settles.
// `escrow` is present when the provider registered an escrow and `binding`
// when the settle is `exact`; a settle node that discloses neither is an empty
// entry. Carries nothing to submit or sign: that lives in `actions`.
// `binding.calldata` is what the executor runs, disclosed for checking.
export const SettlementZod = z.object({
  escrow: SettlementEscrowZod.optional(),
  binding: SettlementBindingZod.optional(),
});

// An amount that cannot cover what a step needs, carried by a compose error
// whose cause is that gap: `required` is the least amount that would clear
// the step, `available` the amount the flow had, both decimal strings in the
// token's units. The one schema for the field: api-schemas declares it on
// every error body that can carry it, the SDK parses it with it.
export const ShortfallZod = z.object({
  required: z.string(),
  available: z.string(),
});

export type ResourcePort = z.infer<typeof ResourcePortZod>;
export type HandlePort = z.infer<typeof HandlePortZod>;
export type HandleUnits = z.infer<typeof HandleUnitsZod>;
export type StaticSolType = z.infer<typeof StaticSolTypeZod>;
export type OpInputPort = z.infer<typeof InputPortZod>;
export type ResourceOutputPort = z.infer<typeof ResourceOutputPortZod>;
export type OpOutputPort = z.infer<typeof OutputPortZod>;
export type ManifestOperation = z.infer<typeof ManifestOperationZod>;
export type GuardSelector = z.infer<typeof GuardSelectorZod>;
export type GuardCompatibility = z.infer<typeof GuardCompatibilityZod>;
export type ManifestGuard = z.infer<typeof ManifestGuardZod>;
export type ManifestMaterialiser = z.infer<typeof ManifestMaterialiserZod>;
export type ManifestPrecondition = z.infer<typeof ManifestPreconditionZod>;
export type ManifestRouting = z.infer<typeof ManifestRoutingZod>;
export type ComposeManifest = z.infer<typeof ComposeManifestZod>;
export type SettlementEscrowWire = z.infer<typeof SettlementEscrowZod>;
export type SettlementBindingWire = z.infer<typeof SettlementBindingZod>;
export type SettlementWire = z.infer<typeof SettlementZod>;
export type Shortfall = z.infer<typeof ShortfallZod>;
