import { Schema } from 'effect';

import { normalizeResource } from './chainCapabilities.js';
import {
  DECIMAL_UINT,
  EVM_ADDRESS_HEX,
  MAX_DATE_MS,
  MAX_UINT256,
} from './hexPatterns.js';

export const SolTypeSchema = Schema.Literal(
  'uint8',
  'uint16',
  'uint32',
  'uint64',
  'uint128',
  'uint256',
  'int128',
  'int256',
  'address',
  'bool',
  'bytes',
  'bytes4',
  'bytes32',
  'string',
);

// A positive integer chain id. Single source of truth on the Effect side
// (`continuation.ts` imports it; `zodSchemas.ts` mirrors it as `chainIdZod`).
export const ChainIdSchema = Schema.Number.pipe(
  Schema.int(),
  Schema.positive(),
);

// The one wire rule for an EVM address in flow documents and op configs.
// Compose ops import it from here, so every address field fails with the same
// message and advertises the same pattern in the manifest.
export const EVMAddressString = Schema.String.pipe(
  Schema.pattern(EVM_ADDRESS_HEX, {
    message: () => 'expected a 0x-prefixed 20-byte EVM address',
  }),
).annotations({
  description: 'EVM address: 0x followed by 40 hex characters',
});

// An epoch-millisecond timestamp a `Date` can represent. Pure and
// clock-independent, so it holds at decode; whether it is still in the future
// is the consumer's registration-time check.
export const EpochMsSchema = Schema.Number.pipe(
  Schema.int(),
  Schema.between(-MAX_DATE_MS, MAX_DATE_MS),
);

// The one wire rule for a raw-unit uint256 amount carried as a decimal string
// (JSON has no bigint). Compose ops import it from here, as they do
// `EVMAddressString`.
//
// Effect's JSONSchema emitter drops a filter with no `jsonSchema` annotation,
// so the constraint never reaches `manifest.json` or the generated SDK types.
// Annotating it churns the generated artifacts and `manifestHash`: tracked as
// COM-1717.
export const IntegerString = Schema.String.pipe(
  // Both checks live in one filter so the uint256-bound test only ever runs
  // `BigInt` on a string the digit check already accepted — order-independent
  // and never throws on malformed input.
  Schema.filter((value) => {
    if (!DECIMAL_UINT.test(value)) {
      return 'amount must be a decimal integer string';
    }
    if (BigInt(value) > MAX_UINT256) {
      return 'amount must not exceed uint256 max';
    }
    return undefined;
  }),
);

const RawResourceSchema = Schema.Union(
  Schema.Struct({ kind: Schema.Literal('native'), chainId: ChainIdSchema }),
  Schema.Struct({
    kind: Schema.Literal('erc20'),
    token: EVMAddressString,
    chainId: ChainIdSchema,
  }),
);

/**
 * THE chain-capabilities chokepoint.
 *
 * `ResourceSchema` is a decode transform: it parses the plain `native | erc20`
 * wire union (`RawResourceSchema`) and then runs `normalizeResource`, so on
 * `as-erc20` chains (e.g. Tempo) a `{ kind: "native", chainId }` resource is
 * rewritten to its ERC-20 form (PathUSD) before any application code sees it.
 * Because every Resource-bearing schema embeds this one — `FlowSchema` for flow
 * inputs, op `configSchema`s for op configs — making the schema itself
 * chain-aware covers every parsed entry point in one place.
 *
 * The `encode` direction is the identity: the ERC-20 form is itself valid wire
 * format, and the rewrite is deliberately not reversible (we never want to
 * re-introduce a `native` resource when serialising). `JSONSchema.make` derives
 * the published wire format from the encoded (`from`) side, so the manifest
 * keeps advertising the plain union with both arms.
 */
export const ResourceSchema = Schema.transform(
  RawResourceSchema,
  Schema.typeSchema(RawResourceSchema),
  {
    strict: true,
    decode: (raw) => normalizeResource(raw),
    encode: (resource) => resource,
  },
);

export const ResourceInputSchema = Schema.Struct({
  name: Schema.String,
  resource: ResourceSchema,
});

export const HandleInputSchema = Schema.Struct({
  name: Schema.String,
  type: SolTypeSchema,
});

export const FlowInputSchema = Schema.Union(
  ResourceInputSchema,
  HandleInputSchema,
);

export const RefSchema = Schema.Struct({
  $ref: Schema.String.pipe(
    Schema.filter((s) => s.indexOf('.') > 0, {
      message: () =>
        '$ref must be a dotpath like "input.name" or "nodeId.port"',
    }),
  ),
});

export const LiteralBindingSchema = Schema.Struct({
  kind: SolTypeSchema,
  value: Schema.String,
});

export const BindValueSchema = Schema.Union(RefSchema, LiteralBindingSchema);

export const AppliedGuardSchema = Schema.Struct(
  { kind: Schema.String },
  { key: Schema.String, value: Schema.Unknown },
);

// A node id keys the compiler's and the response's per-node records. Those are
// plain objects, and `__proto__` there sets the prototype instead of adding a
// key; the response serializer's `z.record` also drops a `__proto__` key. So
// the id can never round-trip, and the one flow schema rejects it for every
// flow it decodes, including an embedded `continuationFlow`.
//
// The empty id is rejected for the same reason: it names a node that no `$ref`
// can address (`node.` + `.` + port is unparseable) and that the compile
// response cannot carry — `fill.spends[].nodeId` is a non-empty string — so a
// settle node with an empty id failed response serialisation with a 500.
const NodeIdSchema = Schema.String.pipe(
  Schema.filter((id) => id !== '__proto__', {
    message: () => 'node id "__proto__" is reserved; choose another node id',
  }),
  Schema.filter((id) => id.length > 0, {
    message: () => 'node id must not be empty',
  }),
);

export const CallSchema = Schema.Struct({
  id: NodeIdSchema,
  op: Schema.String,
  bind: Schema.optionalWith(
    Schema.Record({ key: Schema.String, value: BindValueSchema }),
    { default: () => ({}) },
  ),
  config: Schema.optionalWith(
    Schema.Record({ key: Schema.String, value: Schema.Unknown }),
    { default: () => ({}) },
  ),
  guards: Schema.optional(Schema.Array(AppliedGuardSchema)),
});

// A canonical lowercase UUID, the identity zap-backend mints per HTTP request
// and returns as `X-Flow-Id`.
export const UuidSchema = Schema.String.pipe(
  Schema.pattern(/^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/),
);

// Journey lineage of a non-atomic flow (COM-1253). The server writes it into
// every flow it hands out for a later compile — today an intent-factory
// committed action — so a journey's legs share one id without the caller
// carrying anything. A root flow has no `lineage`.
//
// It has no program semantics: nothing lowers it and nothing executes it. Only
// the compile pipeline (which turns it into the on-chain `ProgramExecution`
// word) and the request-tracking scrub read it.
//
// Trust: a caller may hand-write or copy a stamp and the system accepts it.
// The link is server-asserted where the flow is committed (intent-factory
// registers the stamped blob) and telemetry-grade on any flow the caller
// posts with a stamp it wrote itself.
export const LineageSchema = Schema.Struct({
  journeyId: UuidSchema,
  parentRequestId: UuidSchema,
});

// Where a post-graph forward sends a balance: a literal address or a ref the
// compiler resolves. The compiler admits `context.sender` only.
export const ForwardToSchema = Schema.Union(EVMAddressString, RefSchema);

export const EpilogueForwardSchema = Schema.Struct({
  resource: ResourceSchema,
  to: ForwardToSchema,
});

// The flow's post-graph forwards, run after the last node. A named forward
// moves the proxy's whole balance of one resource to one address; the
// remainder moves every other proxy-held terminal resource to one address.
// `run.sweepTo: X` is sugar for `{ remainder: X }`.
export const EpilogueSchema = Schema.Struct({
  forwards: Schema.optional(Schema.NonEmptyArray(EpilogueForwardSchema)),
  remainder: Schema.optional(ForwardToSchema),
}).pipe(
  Schema.filter((e) => e.forwards !== undefined || e.remainder !== undefined, {
    message: () => 'epilogue needs forwards, a remainder, or both',
  }),
);

export const FlowSchema = Schema.Struct({
  version: Schema.Literal(1),
  id: Schema.String,
  chainId: ChainIdSchema,
  inputs: Schema.Array(FlowInputSchema),
  nodes: Schema.Array(CallSchema),
  lineage: Schema.optional(LineageSchema),
  epilogue: Schema.optional(EpilogueSchema),
});

export type SolType = typeof SolTypeSchema.Type;
export type ResourceInput = typeof ResourceInputSchema.Type;
export type HandleInput = typeof HandleInputSchema.Type;
export type FlowInput = typeof FlowInputSchema.Type;
export type Ref = typeof RefSchema.Type;
export type LiteralBinding = typeof LiteralBindingSchema.Type;
export type BindValue = typeof BindValueSchema.Type;
export type AppliedGuard = typeof AppliedGuardSchema.Type;
export type Call = typeof CallSchema.Type;
export type Lineage = typeof LineageSchema.Type;
export type ForwardTo = typeof ForwardToSchema.Type;
export type EpilogueForward = typeof EpilogueForwardSchema.Type;
export type Epilogue = typeof EpilogueSchema.Type;
export type Flow = typeof FlowSchema.Type;
