import type { Call } from './flowSchema.js';
import type { OpOutputPort, ResourceOutputPort } from './zodSchemas.js';

// An output *family* is a declared resource output carrying `countFrom`. When a
// call's config is bound, the family expands into one ordinary port per
// instance. `config[countFrom]` sets the instance count: an array gives one
// instance per element, and a non-negative integer gives that many instances.
// This module is the single definition of that expansion and of instance
// naming, shared by the compiler and the SDK so the two cannot disagree on
// port names.

// A family is marked by the `countFrom` field itself, which is also how it
// reaches SDK clients in the manifest JSON, so `isOutputFamily` narrows any
// port, whether built by `resourceOutput` or parsed from the wire.
export type OutputFamilyPort = ResourceOutputPort & {
  readonly countFrom: string;
};

export const isOutputFamily = (port: OpOutputPort): port is OutputFamilyPort =>
  port.kind === 'resource_output' && port.countFrom !== undefined;

// `parseRef` splits a ref at its first dot, so `node.parts.1` addresses port
// `parts.1` of node `node`. Declared port names never contain a dot, so an
// instance name cannot equal a fixed port name.
export const instancePortName = (family: string, index: number): string =>
  `${family}.${index}`;

// The number of instances a family has under a call's config: the length of
// an array, or the value of a non-negative integer. The compiler decodes the
// config before expansion, so there any other value is an op-definition bug;
// the SDK sizes handles from the undecoded config the author wrote.
export const familySize = (
  family: Pick<OutputFamilyPort, 'name' | 'countFrom'>,
  config: Call['config'],
): number => {
  const source = config[family.countFrom];
  if (Array.isArray(source)) return source.length;
  if (Number.isSafeInteger(source) && (source as number) >= 0) {
    return source as number;
  }
  throw new Error(
    `Output family '${family.name}' counts from config '${family.countFrom}', which is neither an array nor a non-negative integer`,
  );
};

const expandFamily = (
  port: OutputFamilyPort,
  config: Call['config'],
): ResourceOutputPort[] => {
  const { countFrom: _countFrom, ...instance } = port;
  return Array.from({ length: familySize(port, config) }, (_, index) => ({
    ...instance,
    name: instancePortName(port.name, index),
  }));
};

// Expand a declared output list against a call's decoded config. Fixed ports
// pass through unchanged; each family becomes its instances, in index order,
// at the family's position. A list without a family is returned as is.
export const expandOutputPorts = (
  declared: readonly OpOutputPort[],
  config: Call['config'],
): readonly OpOutputPort[] =>
  declared.some(isOutputFamily)
    ? declared.flatMap((port) =>
        isOutputFamily(port) ? expandFamily(port, config) : [port],
      )
    : declared;
