import { ParseResult, Schema } from 'effect';

import { AssertionSpecSchema, decodeNativeBalanceGte } from './continuation.js';
import type { AssertionSpec } from './continuation.js';
import { BYTES32_LOWER_HEX } from './hexPatterns.js';

// The neutral per-leg verification descriptor (verified continuations, plan
// GD-3, seam C4). It is the wire-visible statement of what a committed
// validation program enforces, so a user funding phase 1 can give informed
// consent (PRD goal G8). It is backend-neutral (G7): no validator address, no
// constraint, no settlement-backend vocabulary — the only escrow-ish term is the
// symbolic owner `"escrow"` (`AssertionOwnerSchema`), explicitly allowlisted by
// the boundary check.
//
// The design trick that makes disclosure trustworthy-by-construction:
// `assertedPredicate[]` is NOT a new DSL. It is the canonical JSON serialization
// of the same `AssertionSpec[]` the validation program is derived from, so
// disclosure cannot drift from enforcement — both are projections of one array.

// The `validationProgramHash` (GD-2, seam C1): `keccak256` over the canonical
// program body. Strict 32-byte lowercase hex (`BYTES32_LOWER_HEX`) — see the
// rationale in `hexPatterns.ts`.
export const Bytes32HexSchema = Schema.String.pipe(
  Schema.pattern(BYTES32_LOWER_HEX),
);

// The disclosed/committed predicate: an `AssertionSpec` with `nativeBalanceGte`
// handled via `decodeNativeBalanceGte`, so settlement derives the identical
// program. Idempotent on already-normalized predicates; normalizes or refuses a
// hand-forged committed action that embeds a raw native check.
export const AssertedPredicateSchema = Schema.transformOrFail(
  AssertionSpecSchema,
  Schema.typeSchema(AssertionSpecSchema),
  {
    strict: true,
    decode: (pred, _options, ast) =>
      pred.kind === 'nativeBalanceGte'
        ? decodeNativeBalanceGte(pred, ast)
        : ParseResult.succeed(pred),
    encode: (pred) => ParseResult.succeed(pred),
  },
);

export const VerificationDescriptorSchema = Schema.Struct({
  validationProgramHash: Bytes32HexSchema,
  // The C5 echo's second hash (verified continuations, plan GD-8): `keccak256`
  // over the canonical params vector (`paramsHash`, GD-2 seam C1). Required and
  // jointly necessary with `validationProgramHash` — the program hash is
  // value-blind (it never binds the delivery address or amounts), so a descriptor
  // that enforces only it is a fund-redirect hole. Empty params still yield a
  // present `0x00…00`, so a real descriptor never omits it. Strict 32-byte
  // lowercase hex, same rule as `validationProgramHash`.
  paramsHash: Bytes32HexSchema,
  assertedPredicate: Schema.Array(AssertedPredicateSchema),
});

// Deterministic, key-order-pinned JSON serialization of an `AssertionSpec[]`.
// Canonicalization rules:
// - Object keys are emitted in recursive lexicographic order (sorted).
// - Compact separators — no whitespace between tokens (a string value such as
//   a `call` signature keeps its own spaces).
// - Array element order is PRESERVED, never sorted: it is semantic (derivation
//   order, and a `call` member's `args` are positional) and is a faithful
//   projection of the program's assertion order.
//
// All `AssertionSpec` leaf values are JSON-safe (strings, positive-int
// `chainId`), so lexicographic key sorting is total and stable with no
// number-canonicalization edge cases, and is self-maintaining when members
// gain fields. Embedding this string per fixture vector pins the serialization
// cross-repo (GD-5's consumer asserts it reproduces the string).
//
// Boundary-forced local mirror of `@lifi/utils`'s `canonicalJson`: compose-spec
// is the wire-format leaf and may not import `@lifi/utils` (enforced by the
// compose boundary check), so do not "fix" this duplication by importing across
// the boundary.
const canonicalJson = (value: unknown): string => {
  if (Array.isArray(value)) {
    return `[${value.map(canonicalJson).join(',')}]`;
  }
  if (value !== null && typeof value === 'object') {
    const record = value as Record<string, unknown>;
    const entries = Object.keys(record)
      .sort()
      .map((key) => `${JSON.stringify(key)}:${canonicalJson(record[key])}`);
    return `{${entries.join(',')}}`;
  }
  return JSON.stringify(value);
};

export const canonicalAssertedPredicate = (
  specs: readonly AssertionSpec[],
): string => canonicalJson(specs);

export type VerificationDescriptor = typeof VerificationDescriptorSchema.Type;

// The disclosed predicate is an `AssertionSpec`; the alias names its role in
// the descriptor.
export type AssertedPredicate = AssertionSpec;
