import { z } from "zod";
import type { TContactAttributeKey } from "./contact-attribute-key";
import type { TEmbeddedData, TEmbeddedDataType, TSurveyEmbeddedData } from "./embedded-data";
import { type TEmbeddedFieldsSurvey, getIngestedEmbeddedFields } from "./embedded-data-fields";
import type { TI18nString } from "./i18n";
import type { TResponse, TResponseData, TResponseVariables } from "./responses";
import { formatFieldNameToTitleCase } from "./safe-identifier";
import type { TSurveyBlocks } from "./surveys/blocks";
import { getTextContent } from "./surveys/validation";

/**
 * What a resolved Embedded Data value can be. A `date` field resolves to its ISO 8601 string, not a
 * `Date` — machine-facing values stay ISO/UTC; display formatting is the consumer's job. One gap to
 * inherit consciously (ENG-1837/1839): today's recall formatters recognize date-ONLY strings
 * (`isValidDateString` in packages/surveys; `formatStoredDateForDisplay` in apps/web, which runs
 * only on the responseData branch), so a datetime resolved from a `Date` renders verbatim until the
 * consumers learn to format it. Booleans come from `boolean`-dataType stored fields (legal on
 * ingested rows) as well as reserved reads; {@link projectReservedValues} stringifies them for the
 * recall/logic maps, and direct resolver callers own their own boolean handling.
 */
export type TResolvedEmbeddedValue = string | number | boolean;

/**
 * The slice of a response the read seam consumes. A full `TResponse` is assignable, but resolvers
 * and reserved-catalog accessors are typed against this slice so they can never depend on fields
 * the seam doesn't own (contact, tags, display bookkeeping) — and so tests and future callers that
 * only hold partial data don't have to fabricate them.
 */
export type TEmbeddedValueResponse = Pick<
  TResponse,
  | "id"
  | "surveyId"
  | "createdAt"
  | "updatedAt"
  | "finished"
  | "language"
  | "data"
  | "variables"
  | "ttc"
  | "meta"
>;

/**
 * The slice a client holds **mid-survey**, while the respondent is still answering.
 *
 * What it omits is the point: `id`, `createdAt` and `updatedAt` are assigned by the database, and
 * `finished` is only true once the respondent reaches the end — so none of them exist, or are
 * final, at the moment a survey wants to recall a reserved value into visible copy. Typing the
 * client seam against this narrower slice is what makes {@link projectClientReservedValues} able to
 * refuse a server-only accessor at compile time instead of fabricating `id: ""`,
 * `createdAt: new Date()` and `finished: false` to satisfy the wider type — fabrications that would
 * resolve to values no response ever carried.
 */
export type TClientEmbeddedValueResponse = Pick<
  TEmbeddedValueResponse,
  "surveyId" | "language" | "data" | "variables" | "ttc" | "meta"
>;

/**
 * What a reserved-catalog accessor may return. Confined to scalars and `Date` on purpose: an entry
 * that could return `meta` or `data` wholesale would leak objects into the value maps, and the
 * compiler stops that here rather than a runtime check discovering it per response.
 */
export type TReservedFieldRawValue = string | number | boolean | Date | null | undefined;

/**
 * **When** a reserved field's value can be known — not who is allowed to see it.
 *
 * - `client` — knowable in the browser while the respondent is still answering.
 * - `server` — only knowable once the request reaches the API, or once the row exists.
 * - `both` — knowable on either side, and both sides agree.
 *
 * This gates what the mid-survey surfaces may offer: the recall and logic pickers inside a running
 * survey can only list fields the renderer can actually resolve at that moment (ENG-1840), and
 * {@link projectClientReservedValues} is the seam that enforces it. Server-side readers — exports,
 * filters, summaries — ignore this and read the whole catalog, because by then everything is known.
 */
export type TReservedFieldAvailability = "client" | "server" | "both";

/**
 * What the "Anonymize responses" toggle does to a reserved field at ingest.
 *
 * - `keep` — carries no information about who or where the respondent is; stored unchanged.
 * - `drop` — not captured at all while anonymizing.
 * - `redactQuery` — captured, but with the query string stripped, because that is where the
 *   identifying part hides (a `?email=` or `?uid=` carried in a page URL) while the path itself is
 *   the part analytics needs.
 *
 * Declared here rather than at the ingest routes so the classification lives next to the field it
 * describes and a new entry cannot be added without deciding it, and so no surface applying the
 * policy needs a per-field list of its own to drift from.
 *
 * Two surfaces apply it, and they apply it at different times for different reasons:
 *
 * - the "Anonymize responses" toggle, at ingest, gated on the survey's setting — it decides what is
 *   *captured*, and `drop` only means anything there;
 * - {@link projectReservedValues} / {@link projectClientReservedValues}, at read, unconditionally —
 *   `redactQuery` narrows what recall and logic may forward, because a recall token can end up in a
 *   redirect URL or an email. Storage is untouched by that one.
 */
export type TReservedFieldPrivacy = "keep" | "drop" | "redactQuery";

/**
 * How prominently a **human-facing** surface should list a reserved field (ENG-2540).
 *
 * Declared on the entry rather than decided per surface, because the alternative is what this field
 * exists to end: the response card rendered seven names as individual JSX branches and the response
 * table held its own `METADATA_FIELDS` array, so three lists — the catalog, the card, the table — had
 * to agree, and ENG-1841's twelve auto-captured fields ended up visible in none of them.
 *
 * - `primary` — always listed on the response card, and a visible column by default. Exactly the set
 *   both surfaces already showed, so an existing response renders as it did before.
 * - `secondary` — auto-captured context. Behind a disclosure on the card, and a column that exists
 *   and is toggleable but starts hidden, so no author's table grows a dozen columns unasked.
 * - `none` — never listed as a field. The response's own identity and timing, which the card header
 *   and the table's fixed columns already render, or a machine id no author reads as data.
 *
 * This is about **prominence**, not privacy — `privacy` is a separate axis and the Anonymize toggle
 * is what acts on it. `ipAddress` is `secondary` for prominence reasons (it is PII and already gated
 * on `isCaptureIpEnabled`), not because anything here suppresses it.
 */
export type TReservedFieldDisplay = "primary" | "secondary" | "none";

/**
 * What every reserved field declares regardless of which side can read it.
 *
 * A reserved field is auto-captured system metadata every survey can reference without declaring
 * anything (see `ZEmbeddedDataSource` — reserved fields are never stored as rows).
 */
interface TReservedFieldCatalogEntryBase {
  /**
   * The key consumers reference the field by — the recall token id, the logic operand, the key in
   * the projected value map. This is the "storageKey" of a reserved field, except nothing is
   * stored: the name only ever addresses catalog reads.
   */
  name: string;
  dataType: TEmbeddedDataType;
  privacy: TReservedFieldPrivacy;
  /** See {@link TReservedFieldDisplay}. Required, so a new entry cannot be added without deciding. */
  display: TReservedFieldDisplay;
}

/**
 * A field only the server can read, because its accessor needs part of a persisted response.
 */
export interface TServerReservedFieldCatalogEntry extends TReservedFieldCatalogEntryBase {
  availability: Extract<TReservedFieldAvailability, "server">;
  /**
   * Reads the raw value off a response. Coercion to `dataType` is the resolver's job, not the
   * accessor's. Accessors should be total functions; one that throws is treated as "nothing
   * captured" by the resolver rather than crashing the caller.
   */
  read: (response: TEmbeddedValueResponse) => TReservedFieldRawValue;
}

/**
 * A field a client can read mid-survey. Its accessor is typed against
 * {@link TClientEmbeddedValueResponse}, so marking an entry `client`/`both` while reading `finished`
 * or `createdAt` is a **compile error** rather than a value that silently resolves to whatever the
 * caller happened to fabricate. That is the whole reason the entry type is a union: the availability
 * claim and the accessor's real dependencies cannot drift apart.
 *
 * A narrower parameter also means such an accessor stays callable with a full response, so
 * {@link resolveEmbeddedValue} and {@link projectReservedValues} treat both variants identically.
 */
export interface TClientReservedFieldCatalogEntry extends TReservedFieldCatalogEntryBase {
  // Everything that is not `server` is client-readable, spelled as the complement rather than a
  // second literal list so a fourth availability value cannot be added without landing in one of the
  // two variants — and therefore without deciding which response slice its accessor may read.
  availability: Exclude<TReservedFieldAvailability, "server">;
  read: (response: TClientEmbeddedValueResponse) => TReservedFieldRawValue;
}

/**
 * One reserved field.
 *
 * The response location is a typed accessor rather than a dot-path string. Reserved fields are a
 * static catalog in code, so the "path" can be code too — which makes an entry that points at a
 * nonexistent response field a compile error instead of a silent `undefined`, needs no path-walking
 * machinery whose edge cases would have to be tested separately, and lets an entry compute (unit
 * conversion, redaction) instead of only fetching.
 */
export type TReservedFieldCatalogEntry = TServerReservedFieldCatalogEntry | TClientReservedFieldCatalogEntry;

/**
 * **The production reserved-field catalog — Tier 1.** Auto-captured system metadata every survey can
 * reference by name without declaring anything. A static list in code, never rows in the
 * `EmbeddedData` table and never a per-survey link: the list is identical for every workspace and
 * keeps growing, so adding a field stays a code change rather than a data migration, and there is
 * nothing to migrate anyway — the values already sit on every response ever stored.
 *
 * Every entry therefore resolves against historical responses too, which is why each accessor
 * tolerates the field being absent rather than assuming today's ingest shape.
 *
 * `name` collisions are real and deliberate: a survey may already declare a hidden field called
 * `country` or `url`, and `RESERVED_FIELD_NAMES` (reserved-field-names.ts) keeps only *new*
 * declarations off these names. Existing surveys keep resolving their own field — see the per-survey
 * precedence rule this catalog is paired with.
 *
 * Not in Tier 1, on purpose:
 * - `status` — `Response` has no status column, and `finished` already carries the only distinction
 *   that exists (complete vs. partial). Deriving a second spelling of the same bit would give two
 *   names for one fact.
 *
 * The browser-runtime block at the end of the list arrived with ENG-1841, which gave `ZResponseMeta`
 * a home for those values and taught the renderer to snapshot them at display time. They are all
 * `client`: the renderer reads them itself, so a mid-survey picker can offer them and the renderer
 * really can resolve them. Responses collected before that shipped carry none of them and resolve as
 * unset — expected, and the reason every accessor tolerates absence.
 */
export const RESERVED_FIELD_CATALOG: readonly TReservedFieldCatalogEntry[] = [
  /** How the response was collected — `link`, `app`, … Set by the client on the response input. */
  {
    name: "source",
    dataType: "string",
    availability: "client",
    privacy: "keep",
    display: "primary",
    read: (r) => r.meta.source,
  },
  /**
   * The page the survey ran on. `redactQuery`, not `drop`: the path is what analytics needs, while a
   * query string is where an identifier rides along (`?email=`, `?uid=`).
   */
  {
    name: "url",
    dataType: "string",
    availability: "client",
    privacy: "redactQuery",
    display: "primary",
    read: (r) => r.meta.url,
  },
  /**
   * Geo-IP country, resolved from the request in the ingest routes — nothing client-side knows it.
   */
  {
    name: "country",
    dataType: "string",
    availability: "server",
    privacy: "drop",
    display: "primary",
    read: (r) => r.meta.country,
  },
  /** The action that triggered an app survey. */
  {
    name: "action",
    dataType: "string",
    availability: "client",
    privacy: "keep",
    display: "primary",
    read: (r) => r.meta.action,
  },
  /**
   * browser/os/deviceType are `server` because that is where they come from: `UAParser` runs over
   * the `user-agent` request header in the ingest routes (see the v1/v2 client response routes), and
   * nothing client-side produces them on this branch. Marking them `client` would let a mid-survey
   * picker offer a field the renderer cannot resolve. They flip to `both` only once a client
   * actually captures them.
   */
  {
    name: "browser",
    dataType: "string",
    availability: "server",
    privacy: "drop",
    display: "primary",
    read: (r) => r.meta.userAgent?.browser,
  },
  {
    name: "os",
    dataType: "string",
    availability: "server",
    privacy: "drop",
    display: "primary",
    read: (r) => r.meta.userAgent?.os,
  },
  {
    name: "deviceType",
    dataType: "string",
    availability: "server",
    privacy: "drop",
    display: "primary",
    read: (r) => r.meta.userAgent?.device,
  },
  /** Only captured when the survey has IP capture enabled, so unset on most responses. */
  {
    name: "ipAddress",
    dataType: "string",
    availability: "server",
    privacy: "drop",
    display: "secondary",
    read: (r) => r.meta.ipAddress,
  },
  /**
   * Complete vs. partial. `server`, because mid-survey the answer is always "not yet" — offering it
   * to a running survey would mean offering a constant `false`.
   */
  {
    name: "finished",
    dataType: "boolean",
    availability: "server",
    privacy: "keep",
    display: "none",
    read: (r) => r.finished,
  },
  /** The language the respondent is answering in; known on both sides and agreed between them. */
  {
    name: "language",
    dataType: "string",
    availability: "both",
    privacy: "keep",
    display: "none",
    read: (r) => r.language,
  },
  /**
   * responseId/surveyId are `server` by decision, not by limitation — a client does know its survey
   * id. Internal identifiers have no business being recalled into copy a respondent reads, and
   * `availability` is what the mid-survey pickers filter on. They stay in the catalog because
   * server-side readers (exports, filters, webhooks) legitimately want them as columns.
   */
  {
    name: "responseId",
    dataType: "string",
    availability: "server",
    privacy: "keep",
    display: "none",
    read: (r) => r.id,
  },
  {
    name: "surveyId",
    dataType: "string",
    availability: "server",
    privacy: "keep",
    display: "none",
    read: (r) => r.surveyId,
  },
  /**
   * Total time to complete. **Only meaningful on finished responses**: `calculateTtcTotal` is the
   * only writer of `ttc._total`, and every call site guards it behind `finished ?` (e.g.
   * apps/web/app/api/v2/client/[workspaceId]/responses/lib/response.ts:64, the v1 client and
   * management routes, and apps/web/lib/response/service.ts). On a partial response the key is
   * absent and this resolves as unset — deliberately, rather than summing the per-element entries to
   * invent a "duration so far" that no other surface reports.
   *
   * The stored `ttc` values are **milliseconds** (see `MAX_RESPONSE_TTC` in responses.ts), so the
   * accessor converts. The field is named and typed in seconds, and a typed accessor is exactly what
   * lets the catalog honor that instead of publishing a `durationSeconds` holding milliseconds.
   */
  {
    name: "durationSeconds",
    dataType: "number",
    availability: "server",
    privacy: "keep",
    display: "none",
    read: (r) => {
      const totalMs = r.ttc?._total;
      return typeof totalMs === "number" ? Math.round(totalMs / 1000) : undefined;
    },
  },
  /**
   * startedAt/finishedAt map onto the row's timestamps: `createdAt` is when the response record was
   * opened, `updatedAt` when it was last written — which for a finished response is its submission.
   * Both resolve to ISO strings, never `Date` objects (see {@link TResolvedEmbeddedValue}).
   *
   * `finishedAt` is `updatedAt` and therefore only means "finished at" on a finished response; on a
   * partial one it is the last partial write. The pair is the closest honest reading of the columns
   * that exist — `Response` stores no separate completion timestamp.
   */
  {
    name: "startedAt",
    dataType: "date",
    availability: "server",
    privacy: "keep",
    display: "none",
    read: (r) => r.createdAt,
  },
  {
    name: "finishedAt",
    dataType: "date",
    availability: "server",
    privacy: "keep",
    display: "none",
    read: (r) => r.updatedAt,
  },
  /**
   * **Browser-runtime context (ENG-1841).** Captured by the renderer itself and frozen at display,
   * which is why every one of these is `client`: unlike browser/os/deviceType — which only exist
   * because the ingest route parses a request header — the values below are read in the page and
   * travel in on the response input, and that is exactly what makes them resolvable mid-survey.
   *
   * Both link and app surveys render through the same component, so all twelve are captured for
   * both (the visit fields further down are the exception). What they *describe* differs: on a link survey `pagePath`/`pageReferrer`/`utm*` are about
   * the Formbricks-hosted survey page and how the respondent reached it; on an app survey they are
   * about the host page the survey was triggered on.
   */
  /**
   * The page the response was answered on, without the query string — the field to group on when you
   * want the page rather than the visit. It needs no redaction because it never carries an
   * identifier; the full URL lives on `url`, which is `redactQuery` for exactly that reason.
   *
   * There is deliberately no `pageUrl`: it read `location.href`, which is the same expression `url`
   * already reads in the same snapshot, so the two were byte-identical on every response rather
   * than merely similar. `url` plus `pagePath` covers it with nothing duplicated.
   */
  {
    name: "pagePath",
    dataType: "string",
    availability: "client",
    privacy: "keep",
    display: "secondary",
    read: (r) => r.meta.pagePath,
  },
  /**
   * Where the respondent came from. `redactQuery`: a referrer URL is as capable of carrying a token
   * or an email in its query string as any other, and the referring *page* is the whole signal.
   */
  {
    name: "pageReferrer",
    dataType: "string",
    availability: "client",
    privacy: "redactQuery",
    display: "secondary",
    read: (r) => r.meta.pageReferrer,
  },
  /**
   * Campaign attribution, parsed from the page's own `utm_*` query params. `keep`: these exist to be
   * read — a campaign name is marketing metadata the respondent's own link advertised, not something
   * they disclosed about themselves. A param that was absent or empty is absent here, never `""`.
   */
  {
    name: "utmSource",
    dataType: "string",
    availability: "client",
    privacy: "keep",
    display: "secondary",
    read: (r) => r.meta.utmSource,
  },
  {
    name: "utmMedium",
    dataType: "string",
    availability: "client",
    privacy: "keep",
    display: "secondary",
    read: (r) => r.meta.utmMedium,
  },
  {
    name: "utmCampaign",
    dataType: "string",
    availability: "client",
    privacy: "keep",
    display: "secondary",
    read: (r) => r.meta.utmCampaign,
  },
  {
    name: "utmTerm",
    dataType: "string",
    availability: "client",
    privacy: "keep",
    display: "secondary",
    read: (r) => r.meta.utmTerm,
  },
  {
    name: "utmContent",
    dataType: "string",
    availability: "client",
    privacy: "keep",
    display: "secondary",
    read: (r) => r.meta.utmContent,
  },
  /**
   * Screen and viewport, in CSS pixels. `number`, not string, so a logic condition can compare them
   * (`viewportWidth < 768`) instead of comparing digit strings. Screen is the device; viewport is
   * the window the survey was actually rendered into — the pair is what distinguishes a phone from a
   * narrow window on a large monitor.
   */
  {
    name: "screenWidth",
    dataType: "number",
    availability: "client",
    privacy: "keep",
    display: "secondary",
    read: (r) => r.meta.screenWidth,
  },
  {
    name: "screenHeight",
    dataType: "number",
    availability: "client",
    privacy: "keep",
    display: "secondary",
    read: (r) => r.meta.screenHeight,
  },
  {
    name: "viewportWidth",
    dataType: "number",
    availability: "client",
    privacy: "keep",
    display: "secondary",
    read: (r) => r.meta.viewportWidth,
  },
  {
    name: "viewportHeight",
    dataType: "number",
    availability: "client",
    privacy: "keep",
    display: "secondary",
    read: (r) => r.meta.viewportHeight,
  },
  /**
   * The respondent's IANA time zone (`Europe/Berlin`), not an offset — it survives DST and is what a
   * "best hour to send" question is actually asking about. Distinct from `language`, which is the
   * language they are answering in: a zone is where they are, a language is how they read.
   */
  {
    name: "timezone",
    dataType: "string",
    availability: "client",
    privacy: "keep",
    display: "secondary",
    read: (r) => r.meta.timezone,
  },
  /**
   * How the respondent's device is configured (`de-AT`), from `navigator.language`. Deliberately a
   * different field from `language`, which is the language they *answered* in: a German speaker
   * taking an English-only survey has `locale: "de-DE"` and `language: "en"`, and the gap between
   * the two is the reason to capture both — it is what "should we translate this survey?" asks.
   *
   * `keep`: a UI language preference is a device setting the browser advertises to every site, not
   * something the respondent disclosed about themselves. Same call as `timezone`, which it sits
   * beside in every runtime that can report either.
   */
  {
    name: "locale",
    dataType: "string",
    availability: "client",
    privacy: "keep",
    display: "secondary",
    read: (r) => r.meta.locale,
  },
  /**
   * **The visit (ENG-3926).** Recorded by the web SDK's visit store and handed to the renderer, which
   * freezes it at display like the context above. App surveys on websites only: a link survey and a
   * mobile app have no visit, so these stay unset there. A visit is one browser tab.
   *
   * `visitEntryReferrer` is `redactQuery` for the same reason as `pageReferrer`. `visitUrls` holds
   * paths only, so it has no query to strip.
   */
  {
    name: "visitPagesViewed",
    dataType: "number",
    availability: "client",
    privacy: "keep",
    display: "secondary",
    read: (r) => r.meta.visitPagesViewed,
  },
  {
    name: "visitUniquePagesViewed",
    dataType: "number",
    availability: "client",
    privacy: "keep",
    display: "secondary",
    read: (r) => r.meta.visitUniquePagesViewed,
  },
  {
    name: "visitTimeOnSite",
    dataType: "number",
    availability: "client",
    privacy: "keep",
    display: "secondary",
    read: (r) => r.meta.visitTimeOnSite,
  },
  {
    name: "visitEntryReferrer",
    dataType: "string",
    availability: "client",
    privacy: "redactQuery",
    display: "secondary",
    read: (r) => r.meta.visitEntryReferrer,
  },
  {
    name: "visitUrls",
    dataType: "string",
    availability: "client",
    privacy: "keep",
    display: "secondary",
    read: (r) => r.meta.visitUrls,
  },
  /**
   * **Opened by creative (ENG-4001).** The creative whose click opened the survey, stamped by
   * the ingest routes once they have checked it is in the workspace and opens this survey — which is
   * why both are `server` even though the renderer knows the id: an unchecked id is not a fact yet.
   * The name is the one the creative had when the response was created. `keep`: both are the
   * workspace's own copy, nothing the respondent disclosed. `secondary`, so a survey no creative
   * opens does not grow an empty default column.
   */
  {
    name: "openedByCreativeId",
    dataType: "string",
    availability: "server",
    privacy: "keep",
    display: "secondary",
    read: (r) => r.meta.openedByCreativeId,
  },
  {
    name: "openedByCreativeName",
    dataType: "string",
    availability: "server",
    privacy: "keep",
    display: "secondary",
    read: (r) => r.meta.openedByCreativeName,
  },
];

/**
 * The slice of a stored field definition the resolver needs — `TEmbeddedData` minus the ownership
 * and bookkeeping columns. `source` stays the full enum even though `ZEmbeddedData` rejects
 * `"reserved"` rows: narrowing it here would force every caller holding a parsed row to re-prove
 * at runtime what the schema already guaranteed. A row that still claims `"reserved"` resolves to
 * `undefined` (see {@link resolveEmbeddedValue}).
 */
export type TResolvableEmbeddedField = Pick<TEmbeddedData, "source" | "dataType" | "defaultValue" | "locked">;

/** The slice of the survey link the read seam needs: the key the value is stored under in the response. */
export type TEmbeddedDataLink = Pick<TSurveyEmbeddedData, "storageKey">;

/**
 * A reference to one embedded value on a response. Two shapes because the data model has two:
 * a stored field is only addressable through the survey link that carries its `storageKey`, while
 * a reserved field has no link and no storage — only a catalog entry. Modeling this as a union
 * makes the mismatch unrepresentable: there is no way to hand the resolver a catalog entry with a
 * storage key, or a stored field without one.
 *
 * The `?: never` exclusion props are what make that claim actually hold. Against a bare union,
 * TypeScript's excess-property check admits keys from any constituent, so a mixed
 * `{ field, link, entry }` object would compile and the resolver would have to pick a winner
 * silently; with the exclusions it is a compile error instead.
 */
export type TEmbeddedValueRef =
  | { field: TResolvableEmbeddedField; link: TEmbeddedDataLink; entry?: never }
  | { entry: TReservedFieldCatalogEntry; field?: never; link?: never };

/**
 * A stored field definition paired with the survey link that addresses it — the unit
 * {@link listReadableFields} enumerates and `embeddedFieldsFromLegacyInput` synthesizes. The pair
 * is assignable to {@link TEmbeddedValueRef}, so whatever a caller lists it can also resolve,
 * without repackaging.
 *
 * `key` and `id` are what make the pair writable as well as readable (ENG-3228): the survey write
 * path takes these same pairs back, and `key !== null` is how an entry says it links a shared
 * library row rather than one the survey owns. `id` is optional because a pair built from legacy
 * input describes no stored row. Mirrored by `ZLinkedEmbeddedField` (embedded-data.ts),
 * which carries the reasoning for what is and is not in this shape.
 */
export interface TLinkedEmbeddedField {
  field: TResolvableEmbeddedField & Pick<TEmbeddedData, "name" | "key"> & Partial<Pick<TEmbeddedData, "id">>;
  link: TEmbeddedDataLink;
}

/**
 * Mirrors the date rule `ZEmbeddedData` pins for `date` default values (kept private there on
 * purpose — this module owns read-side semantics, that one owns the row schema).
 */
const ZIsoDateOrDateTime = z.union([z.iso.date(), z.iso.datetime()]);

/** A `Date` as an ISO string, or `undefined` for an invalid one. */
const dateToIso = (value: Date): string | undefined =>
  Number.isNaN(value.getTime()) ? undefined : value.toISOString();

const coerceToString = (value: unknown): string | undefined => {
  if (typeof value === "string") return value;
  if (typeof value === "number") return Number.isFinite(value) ? String(value) : undefined;
  if (typeof value === "boolean") return String(value);
  if (value instanceof Date) return dateToIso(value);
  return undefined;
};

const coerceToNumber = (value: unknown): number | undefined => {
  if (typeof value === "number") return Number.isFinite(value) ? value : undefined;
  if (typeof value !== "string" || value.trim() === "") return undefined;
  const parsed = Number(value);
  return Number.isFinite(parsed) ? parsed : undefined;
};

const coerceToBoolean = (value: unknown): boolean | undefined => {
  if (typeof value === "boolean") return value;
  if (typeof value !== "string") return undefined;
  const normalized = value.trim().toLowerCase();
  if (normalized === "true") return true;
  if (normalized === "false") return false;
  return undefined;
};

const coerceToDate = (value: unknown): string | undefined => {
  if (value instanceof Date) return dateToIso(value);
  if (typeof value === "string") return ZIsoDateOrDateTime.safeParse(value).success ? value : undefined;
  return undefined;
};

/** The read-side coercion of each `dataType`, for {@link coerceToEmbeddedDataType}. */
const EMBEDDED_DATA_COERCERS: Record<
  TEmbeddedDataType,
  (value: unknown) => TResolvedEmbeddedValue | undefined
> = {
  string: coerceToString,
  number: coerceToNumber,
  boolean: coerceToBoolean,
  date: coerceToDate,
};

// Looked up through a Map, so only the four data types have a coercer and a prototype key has none.
// Not `Object.hasOwn`: this package compiles against ES2021.
const EMBEDDED_DATA_COERCER_MAP = new Map(Object.entries(EMBEDDED_DATA_COERCERS));

/**
 * Coerces a raw stored value to a field's `dataType`, returning `undefined` when the value cannot
 * honestly represent one. This is the single vocabulary of read-side coercion — every tier of
 * {@link resolveEmbeddedValue} (stored value, reserved read, default value) goes through it, so a
 * resolved value always agrees with its declared `dataType` no matter which tier produced it.
 *
 * The rules, and why:
 * - `null`, `undefined` and non-scalars (`string[]`, `Record<string, string>`) are missing. Response
 *   data shares one map with question answers, so a multi-select array or matrix record under the
 *   storage key means the key collided with an element id — joining it into a string would invent a
 *   value the respondent never provided for this field.
 * - `string`: strings pass through unchanged, including `""` — an ingested empty string is a present
 *   value, and whether to display something else is the consumer's fallback logic, not data
 *   semantics. Numbers, booleans and valid dates stringify losslessly.
 * - `number`: finite numbers and non-blank numeric strings. Blank strings are missing, never `0`
 *   (`Number("") === 0` is a coercion artifact, not data).
 * - `boolean`: booleans, and exactly `"true"`/`"false"` (case-insensitive, trimmed) — the URL-param
 *   spelling. `1`/`"yes"`/`"on"` stay uncoercible: guessing truthiness is write-side ingest policy
 *   (ENG-1845), and the read seam must not resolve a value ingest would have rejected.
 * - `date`: `Date` instances become ISO strings; strings must be an ISO 8601 date (`2026-08-06`)
 *   or UTC datetime (`2026-08-06T10:30:00Z`) — the exact subset `ZEmbeddedData` pins for date
 *   defaults. That deliberately excludes offset (`+02:00`) and zone-less datetimes, and, unlike
 *   the number and boolean arms, tolerates no surrounding whitespace — write-side ingest
 *   (ENG-1845) must normalize to this same subset, or consciously widen both rules together.
 *   Accepted strings pass through as-is, so a date-only value is not silently promoted to a
 *   midnight-UTC datetime. Epoch numbers stay uncoercible — nothing upstream produces them
 *   intentionally.
 */
export const coerceToEmbeddedDataType = (
  value: unknown,
  dataType: TEmbeddedDataType
): TResolvedEmbeddedValue | undefined => {
  if (value === null || value === undefined) return undefined;
  // An unknown `dataType` (a prototype key included) coerces nothing, as the old switch's missing arm did.
  return EMBEDDED_DATA_COERCER_MAP.get(dataType)?.(value);
};

/**
 * Resolves one catalog entry against whatever response slice its accessor asks for.
 *
 * A throwing accessor reads as missing rather than escalating: one dirty response fed to a computing
 * accessor (URL parsing, unit conversion) must degrade like every other dirty input here — one field
 * unset — not abort a caller's whole render or export loop over the catalog.
 *
 * Generic over the slice so "how a reserved read resolves" has exactly one definition shared by the
 * server seam ({@link resolveEmbeddedValue}) and the mid-survey one
 * ({@link projectClientReservedValues}), which is what keeps the two from drifting on coercion or on
 * error handling.
 */
const resolveCatalogEntry = <TSlice>(
  entry: { dataType: TEmbeddedDataType; read: (response: TSlice) => TReservedFieldRawValue },
  response: TSlice
): TResolvedEmbeddedValue | undefined => {
  try {
    return coerceToEmbeddedDataType(entry.read(response), entry.dataType);
  } catch {
    return undefined;
  }
};

/**
 * What `URL` reports as the origin of a scheme that has no host — `data:`, `blob:`, `mailto:`. It is
 * the literal string `"null"`, so concatenating origin and pathname for those would produce garbage
 * like `"nulltext/plain,hi"`.
 */
const OPAQUE_URL_ORIGIN = "null";

/**
 * Strips the identifying tail off a URL, keeping origin + path — the redaction
 * `privacy: "redactQuery"` names.
 *
 * Query strings are where an identifier rides along in practice (`?email=`, `?uid=`, `?token=`) while
 * the path is the part analytics actually wants — that is the whole reason the catalog classifies
 * these fields `redactQuery` rather than `drop`.
 *
 * **The fragment goes too.** `#` is not merely SPA routing: the OAuth implicit flow puts
 * `access_token` in the fragment, and any hand-rolled link can do the same.
 *
 * Total by construction — it never throws. A string that does not parse as a URL, or parses to an
 * opaque origin, is still cut at the first `?` or `#` rather than returned intact, because failing
 * *open* on an unparseable string would be a privacy hole rather than a graceful degradation. A string
 * with neither separator comes back unchanged.
 *
 * Used by both surfaces that apply the policy: this module's projections at read time, and the
 * "Anonymize responses" toggle at ingest (`apps/web/lib/response/anonymize.ts`). One definition on
 * purpose — two would let a privacy rule drift between capture and read.
 */
export const redactUrlQuery = (url: string): string => {
  try {
    const parsed = new URL(url);
    if (parsed.origin !== OPAQUE_URL_ORIGIN) {
      return `${parsed.origin}${parsed.pathname}`;
    }
  } catch {
    // Not an absolute URL. Fall through to the cut, which needs no parser and cannot throw.
  }

  const separatorIndex = url.search(/[?#]/);
  return separatorIndex === -1 ? url : url.slice(0, separatorIndex);
};

/**
 * The shared body of the two projections: entry name → resolved value, absent values omitted,
 * booleans stringified because the recall/logic map types have no boolean slot.
 *
 * `privacy: "redactQuery"` is honoured HERE, on every projection, not only when the "Anonymize
 * responses" toggle is on. The projection is a *forwarding* surface in a way storage is not: a
 * reserved value reaches a recall token, and a recall token can be interpolated into an ending card's
 * redirect URL (`ending-card.tsx`) or a follow-up email body. Projecting `url` verbatim therefore
 * hands a third party whatever the survey URL carried — including a link survey's single-use
 * `suToken`, which is a credential. Stripping the query costs an author nothing that was ever a
 * documented capability (query params surface as their own `utm*` entries), so the safe form is the
 * only form recall and logic ever see.
 *
 * Storage is deliberately untouched: `response.meta.url` still holds the full href unless the
 * Anonymize toggle redacted it at ingest. This is a read-side narrowing, not a capture change.
 */
const projectEntries = <TSlice>(
  entries: readonly {
    name: string;
    dataType: TEmbeddedDataType;
    privacy: TReservedFieldPrivacy;
    read: (response: TSlice) => TReservedFieldRawValue;
  }[],
  response: TSlice
): Record<string, string | number> => {
  const values: Record<string, string | number> = {};
  for (const entry of entries) {
    const value = resolveCatalogEntry(entry, response);
    if (value === undefined) continue;
    const projected = typeof value === "boolean" ? String(value) : value;
    values[entry.name] =
      entry.privacy === "redactQuery" && typeof projected === "string"
        ? redactUrlQuery(projected)
        : projected;
  }
  return values;
};

/**
 * The single read seam for Embedded Data: returns one field's value from a response, or `undefined`
 * when the field has no value there. Every downstream surface (recall, logic, export, pickers)
 * will read through this once ENG-1837 repoints them, so "where does a field's value live" is
 * answered exactly once:
 *
 * - `computed` → `response.variables[storageKey]` (written by the logic engine)
 * - `ingested` → `response.data[storageKey]` (written from URL params / SDK)
 * - reserved catalog entry → wherever its typed accessor points (`meta.*`, `ttc._total`, …)
 *
 * A `locked` ingested field ignores `response.data` entirely — locking means outside writes are
 * refused, so the default IS the value; honoring a stored value here would let a crafted URL
 * override what locking promised. Missing or uncoercible values fall back to the field's
 * `defaultValue` (`null` means "no default"), which is coerced through the same rules, so the
 * result always agrees with the field's `dataType` or is `undefined`. Reserved entries have no
 * default tier: they are captured metadata, and a default would fake a capture that never happened.
 *
 * A stored row whose `source` still claims `"reserved"` resolves to `undefined` — such a row cannot
 * pass `ZEmbeddedData`, so this arm only defends against data that skipped the schema.
 *
 * ENG-1837 swap checklist — two consumer behaviors this seam deliberately does not reproduce; the
 * repointed call sites inherit these deltas and must do so consciously. The mismatched state is
 * realistic today: `performCalculation`'s `assign` (packages/surveys/src/lib/logic.ts) stores raw
 * strings into number variables unconditionally.
 * (a) `getVariableValue` in that same file evaluates a number variable as `Number(value) || 0` (its
 *     text arm collapses falsy values to `""`), so a non-numeric or empty string stored in
 *     `response.variables` is `0` to logic today — here that state is a coercion failure and
 *     resolves to defaultValue-or-`undefined`.
 * (b) Both recall paths (`replaceRecallInfo` in packages/surveys, `parseRecallInfo` in apps/web)
 *     render whatever sits in the lookup maps with no dataType awareness, so the same stored
 *     `"abc"` renders verbatim in recall today — here it resolves to defaultValue-or-`undefined`.
 * (c) On a key present in both maps, today's consumers disagree with each other —
 *     `replaceRecallInfo` lets `responseData` win (its data check runs last), `parseRecallInfo`
 *     lets `variables` win (checked first). Here the declared source is exclusive: computed reads
 *     only `variables`, ingested reads only `data`.
 * (d) A response missing a variable's key entirely (stored before the variable was added, or
 *     API-created) is `0` / `""` to logic and fallback text to recall today — here it resolves to
 *     the field's `defaultValue`, which for §8-derived pairs is the variable's declared value.
 */
export const resolveEmbeddedValue = (
  ref: TEmbeddedValueRef,
  response: TEmbeddedValueResponse
): TResolvedEmbeddedValue | undefined => {
  // Definedness, not `"entry" in ref`: the `entry?: never` exclusion prop keeps the `in` operator
  // from narrowing the union, and this way a degenerate `{ field, link, entry: undefined }` object
  // still resolves through its field instead of crashing on `undefined.read`.
  if (ref.entry !== undefined) return resolveCatalogEntry(ref.entry, response);

  const { field, link } = ref;
  if (field.source === "reserved") return undefined;

  let storedValue: unknown;
  if (field.source === "computed") storedValue = response.variables[link.storageKey];
  else if (!field.locked) storedValue = response.data[link.storageKey];

  const coerced = coerceToEmbeddedDataType(storedValue, field.dataType);
  if (coerced !== undefined) return coerced;
  if (field.defaultValue === null) return undefined;
  return coerceToEmbeddedDataType(field.defaultValue, field.dataType);
};

/**
 * Finds a computed field by the key its value is stored under in `response.variables`.
 *
 * Returns `undefined` when nothing matches, which is a state that reaches production: a logic
 * condition or a calculate action outlives the field it names whenever a variable is renamed or
 * deleted and the rule keeps the old storage key.
 */
export const findComputedEmbeddedField = (
  computedFields: readonly TLinkedEmbeddedField[],
  storageKey: string
): TLinkedEmbeddedField | undefined => computedFields.find((field) => field.link.storageKey === storageKey);

/**
 * The declared type of the computed field an operand names, or `undefined` when it names none.
 *
 * The optional chain is the point: both logic engines consult this to decide whether to coerce a
 * hidden-field operand to a number, and that decision is made BEFORE the operator switch. Reading
 * `.dataType` off a missing field throws there, and `evaluateSingleCondition`'s try/catch turns the
 * throw into a silent `false` — so a stale operand would quietly change which branch a respondent
 * takes, or what a quota counts, with no error anywhere. Unknown type means the coercion simply does
 * not fire and evaluation falls through exactly as it does for a text variable.
 */
export const getComputedFieldDataType = (
  computedFields: readonly TLinkedEmbeddedField[],
  storageKey: string
): TEmbeddedDataType | undefined => findComputedEmbeddedField(computedFields, storageKey)?.field.dataType;

/**
 * What the logic engines read a computed field's value as — **not** {@link resolveEmbeddedValue}.
 *
 * ENG-1837 repointed the *definition* lookup onto the EmbeddedData tables and deliberately left this
 * value expression alone. `resolveEmbeddedValue` would coerce a non-numeric stored value to the
 * field's declared default instead of `0`, and render a text field holding `0` as `"0"` rather than
 * `""` — both of which change what already-stored responses evaluate to, and responses are never
 * migrated (see the swap checklist on {@link resolveEmbeddedValue}, deltas (a) and (d)).
 *
 * Shared by `packages/surveys/src/lib/logic.ts` (the renderer) and `apps/web/lib/surveyLogic/utils.ts`
 * (quotas, summaries, follow-up conditions), which are near-copies of each other. It lives here so
 * the rule has one definition rather than two that can drift apart — the engines evaluating the same
 * survey differently is its own bug class.
 *
 * A true/false field (ENG-6973) reads as `"true"` / `"false"`, the spelling conditions compare it with
 * and an ingested true/false field is stored as, and as `""` while unset: a stored `false` must not
 * collapse into "unset" the way the text arm's `|| ""` would.
 */
export const getLogicVariableValue = (
  computedFields: readonly TLinkedEmbeddedField[],
  storageKey: string,
  variablesData: TResponseVariables
): string | number | undefined => {
  const field = findComputedEmbeddedField(computedFields, storageKey);
  if (!field) return undefined;
  const variableValue = variablesData[storageKey];
  if (field.field.dataType === "boolean") {
    const coerced = coerceToEmbeddedDataType(variableValue, "boolean");
    return coerced === undefined ? "" : String(coerced);
  }
  // A stored boolean (a field changed from true/false to number) is not a number: `Number(true)` would
  // read as `1`, while `"true"` reads as `0`.
  if (field.field.dataType === "number") {
    return typeof variableValue === "boolean" ? 0 : Number(variableValue) || 0;
  }
  return typeof variableValue === "boolean" ? String(variableValue) : variableValue || "";
};

/**
 * Resolves every catalog entry into a plain map keyed by entry name — the piece that lets reserved
 * fields ride through recall and logic with zero per-consumer special-casing. Those consumers
 * already read two maps (`variables[...]`, `responseData[...]`); merging this projection into
 * either one makes reserved values reachable by name exactly like every other field, which matters
 * because `response.meta` is not otherwise passed into the recall/logic resolvers at all.
 *
 * The value type is deliberately `string | number` so the result is assignable into both existing
 * maps: absent values are omitted (recall then falls back to its fallback text and logic sees
 * `undefined`, exactly like an absent hidden field today), and booleans are stringified to
 * `"true"`/`"false"` — what `String()` would render anyway, in a map type that has no boolean slot.
 *
 * An entry name that matches an element id or hidden field name shadows it in the merged map, which
 * is why the caller — not this function — owns precedence. `FORBIDDEN_IDS` never guarded these names
 * (only `source` overlaps), so surveys stored today can and do declare a field called `country` or
 * `url`; `RESERVED_FIELD_NAMES` (reserved-field-names.ts) stops only *new* declarations, and a
 * consumer merging this map must let an existing declared field win inside its own survey.
 */
export const projectReservedValues = (
  entries: readonly TReservedFieldCatalogEntry[],
  response: TEmbeddedValueResponse
): Record<string, string | number> => projectEntries(entries, response);

/**
 * The mid-survey counterpart of {@link projectReservedValues}: what a **client** can project while
 * the respondent is still answering.
 *
 * Two things make it a separate function rather than a flag:
 *
 * 1. It takes {@link TClientEmbeddedValueResponse}, the shape a running survey actually holds. The
 *    persisted-only fields are not optional here, they are absent — so a caller cannot be tempted to
 *    pass `id: ""`, `createdAt: new Date()` or `finished: false` and get values back that describe
 *    the fabrication rather than the response.
 * 2. It drops every `server` entry, and the type system guarantees the survivors never needed those
 *    fields in the first place (see {@link TClientReservedFieldCatalogEntry}). A server-only accessor
 *    is filtered out before it is ever invoked, so nothing throws and nothing resolves from a stub.
 *
 * Same output contract as {@link projectReservedValues} — absent values omitted, booleans
 * stringified — so a consumer can merge either one into the same recall/logic map.
 */
export const projectClientReservedValues = (
  entries: readonly TReservedFieldCatalogEntry[],
  response: TClientEmbeddedValueResponse
): Record<string, string | number> =>
  projectEntries(
    entries.filter((entry): entry is TClientReservedFieldCatalogEntry => entry.availability !== "server"),
    response
  );

/**
 * **The grandfather rule, second half.** Reserved values go in FIRST so `responseData` spreads over
 * them and wins on every colliding key.
 *
 * `FORBIDDEN_IDS` never guarded the reserved names, so surveys stored today legitimately declare a
 * hidden field called `country` or `url`. Its value lives at `response.data["country"]`, and
 * `#recall:country#` in such a survey must keep resolving from there — unchanged, forever.
 * `RESERVED_FIELD_NAMES` (reserved-field-names.ts) stops only *new* declarations, so the collision
 * set is frozen but non-empty.
 *
 * **This is no longer the whole rule, and on its own it was never enough (ENG-2538).** A spread only
 * wins for keys that *exist*: an absent declared field overwrites nothing, so the reserved value
 * survived and a survey declaring an optional `url` rendered the page's own address wherever the
 * respondent left it blank — respondent-facing, and the normal case for a hidden field. The rule is
 * "declared **owns the name**", not "declared wins if it has a value", so the reserved entry must be
 * dropped from the projection before it ever reaches this merge: see
 * {@link dropShadowedReservedEntries}, which every caller applies first.
 *
 * What this expression still carries is the case a filter cannot see from the survey definition
 * alone — a key present in `responseData` that the declared-name list did not predict — and the
 * falsy-value guarantee: `""` and `0` are answers, so a `??`-style merge would get them wrong.
 * Flipping the two spreads remains a regression, which is why it stays one line with one test.
 */
export const mergeReservedValues = (
  reservedValues: Record<string, string | number>,
  responseData: TResponseData
): TResponseData => ({ ...reservedValues, ...responseData });

/**
 * The map a recall token or a logic operand is looked up in: what the survey knows about every name
 * it can address, right now.
 *
 * The response layer goes on first and the defaults last, which reads backwards and is the point:
 * {@link projectIngestedDefaults} has already decided, per field, whether the response holds
 * anything usable. It emits a key only when the response does not, so spreading it last overrides
 * nothing that was supplied — while spreading it first would let the response layer put an
 * uncoercible value (`?pts=name`) straight back over the default that replaced it.
 *
 * Reserved entries sit inside the response layer, under the response itself, for the reason
 * {@link mergeReservedValues} gives. They cannot collide with a default: a declared field's name is
 * dropped from the reserved projection by {@link dropShadowedReservedEntries} before it gets here.
 *
 * It exists as a function so the order is pinned by a test rather than by two identical spreads in a
 * component, which is where it lived and where nothing could fail on it. Callers pass the response
 * data they want read — mid-block logic passes the in-flight answers, recall passes the committed
 * ones — and this never writes anything back: the record the response queue submits is built
 * elsewhere and must not carry defaults (see {@link projectIngestedDefaults}).
 */
export const buildEmbeddedLookup = (
  survey: TEmbeddedFieldsSurvey,
  reservedValues: Record<string, string | number>,
  responseData: TResponseData
): TResponseData => ({
  ...mergeReservedValues(reservedValues, responseData),
  ...projectIngestedDefaults(survey, responseData),
});

/** One reserved field as a human-facing surface renders it: the entry, plus the value it resolved to. */
export interface TDisplayableReservedField {
  entry: TReservedFieldCatalogEntry;
  /** Always a rendered string. Booleans and dates are stringified by the projection. */
  value: string;
}

/**
 * **The one read a human-facing surface needs (ENG-2540).** Every catalog entry of the requested
 * prominence that this response actually carries a value for, in catalog order.
 *
 * Absent values are omitted rather than rendered blank, and that is what makes the surfaces behave
 * correctly for free in two cases they used to need their own rules for:
 *
 * - a response collected before ENG-1841 carries none of the browser-runtime fields, so it renders
 *   exactly as it did before — no empty rows, no placeholders;
 * - with "Anonymize responses" on, the `drop` fields are absent from `meta` at ingest, so nothing
 *   here invents a row for a key that is not there. Read-time filtering would be the wrong tool:
 *   `anonymize.ts` already decided this at capture, and duplicating the policy is how the two drift.
 *
 * Deliberately does **not** take the survey and does **not** apply
 * {@link dropShadowedReservedEntries}. A display surface is describing what was captured, not
 * resolving a name: if a survey declares its own `country`, the author needs to see *both* — their
 * field in its own section, and the auto-captured one here — where recall and logic must pick one.
 */
export const listDisplayableReservedFields = (
  entries: readonly TReservedFieldCatalogEntry[],
  response: TEmbeddedValueResponse,
  display: TReservedFieldDisplay
): TDisplayableReservedField[] => {
  const wanted = entries.filter((entry) => entry.display === display);
  // Widened to include `undefined`: projectEntries omits a key whose value resolved to undefined, so
  // the lookup below really can miss — the Record index signature alone would call that impossible.
  const values: Record<string, string | number | undefined> = projectEntries(wanted, response);

  return wanted
    .filter((entry) => values[entry.name] !== undefined)
    .map((entry) => ({ entry, value: String(values[entry.name]) }));
};

/**
 * **The grandfather rule, first half: a declared name owns itself.** Drops every catalog entry whose
 * name the survey already declares, so the reserved read of that name never happens for that survey
 * — not in a picker, and not in a value map.
 *
 * This used to live inside {@link listMidSurveyReservedEntries}, which meant only the *pickers*
 * applied it. The value maps relied on {@link mergeReservedValues}'s spread instead, and a spread
 * only loses to a key that exists — so a declared field with no value let the reserved value through
 * to recall, logic, quotas and every display surface (ENG-2538). Pulling the filter out is what lets
 * both kinds of consumer share one definition of "shadowed".
 *
 * `declaredStorageKeys` must count **all three** declaration kinds — ingested fields, variables and
 * element ids — because all three land in the same read namespace and any of them resolves ahead of
 * a reserved entry. Element ids matter more than they look: a question whose id is `url` is only in
 * `response.data` once it has been answered, so without it here `#recall:url#` would render the page
 * address until the respondent reaches that question and the author's fallback afterwards.
 *
 * Matching is exact, not case-insensitive. `RESERVED_FIELD_NAMES` refuses new declarations under any
 * casing, and for the legacy names that predate it the read namespace is itself case-sensitive:
 * `response.data["Country"]` and a reserved `country` are two different keys, so dropping the entry
 * for a survey declaring `Country` would lose a value that resolves today.
 */
export const dropShadowedReservedEntries = (
  entries: readonly TReservedFieldCatalogEntry[],
  declaredStorageKeys: readonly string[]
): TReservedFieldCatalogEntry[] => {
  const declared = new Set(declaredStorageKeys);
  return entries.filter((entry) => !declared.has(entry.name));
};

/**
 * The `declaredStorageKeys` argument {@link dropShadowedReservedEntries} and
 * {@link listMidSurveyReservedEntries} expect: every name a survey's own definitions already own in
 * the read namespace.
 *
 * Takes resolved fields rather than a survey so the choice of which read a caller makes stays at the
 * call site, where it is visible. Every caller now passes {@link getSurveyEmbeddedFields} — the
 * editor included, since ENG-2628 made its working copy rows-native — and the one remaining reason
 * to pass anything else is a survey that has never been written and therefore has no rows at all
 * (see `embeddedFieldsFromLegacyInput`).
 *
 * What is *not* the caller's choice is which kinds count. All three do, and the doc for
 * {@link dropShadowedReservedEntries} says why element ids are the easy one to forget.
 */
export const listShadowingNames = (
  embeddedFields: readonly TLinkedEmbeddedField[],
  elementIds: readonly string[]
): string[] => [...embeddedFields.map(({ link }) => link.storageKey), ...elementIds];

/**
 * Which reserved entries a **mid-survey** picker may offer for one survey (ENG-1840). Two filters,
 * and a reviewer should be able to check them separately:
 *
 * 1. `availability !== "server"` — recall and logic evaluate in the browser while the respondent is
 *    answering, so offering `country` or `durationSeconds` would let an author build a condition
 *    that can never be true. Filtering on the catalog's own field (rather than a list here) means
 *    entries added later light up automatically, and none can be offered without declaring when it
 *    is knowable.
 * 2. {@link dropShadowedReservedEntries} — if a survey declares its own `country`, that name already
 *    resolves to the declared value, so listing the reserved entry too would show two
 *    identically-named rows with no way to tell them apart and the reserved one would be a lie. The
 *    declared field is already offered by its own group.
 *
 * Only the availability gate is the picker's own; the shadow gate is shared with the value maps,
 * which is the whole point of it being a separate function.
 *
 * Pass the survey's declared storage keys (ingested fields, variables and element ids) as
 * `declaredStorageKeys`.
 */
export const listMidSurveyReservedEntries = (
  entries: readonly TReservedFieldCatalogEntry[],
  declaredStorageKeys: readonly string[]
): TReservedFieldCatalogEntry[] =>
  dropShadowedReservedEntries(
    entries.filter((entry) => entry.availability !== "server"),
    declaredStorageKeys
  );

/** One referenceable field, carrying the key a consumer must use to address it. */
export interface TReadableField {
  /** The reference key: element id, link `storageKey`, catalog entry name, or contact attribute key. */
  key: string;
  /** Display label for pickers. Falls back to the key when nothing better exists. */
  label: string;
  /**
   * A second, dimmer string a picker may render beside the label — set only for a **shared**
   * Embedded Data field, where it carries the workspace library `key` (ENG-1853).
   *
   * A shared field's name is workspace-wide prose ("Plan tier") while its key is the identifier an
   * integration or a URL parameter actually spells (`plan_tier`), and the two are edited
   * independently. Someone who knows only the key would otherwise have no way to find the field in
   * a picker that labels by name alone. A survey-only field has no library key and therefore no
   * secondary string — one row, one label — which is why this is optional rather than falling back
   * to `storageKey`: repeating the storage key under every local field's name would be noise on the
   * common case.
   */
  secondaryLabel?: string;
}

/**
 * Everything a survey can reference, grouped. All four groups are always present (empty arrays
 * included) so consumers render stable sections instead of probing for keys. Contact attributes
 * stay their own clearly-labelled group — they describe the person, not the response, and the
 * unified picker must not blur that line.
 */
export interface TReadableFields {
  question: TReadableField[];
  embeddedData: TReadableField[];
  reserved: TReadableField[];
  contactAttribute: TReadableField[];
}

/**
 * Inputs are explicit: the field/link pairs don't live on `TSurvey` until ENG-1837 inlines them,
 * contact attribute keys are workspace-level, the reserved catalog is code — and `blocks`, which
 * does live on `TSurvey`, is taken alone so the function needs no survey object. Passing them in
 * keeps this pure and lets a never-written survey participate via `embeddedFieldsFromLegacyInput`.
 */
export interface TListReadableFieldsInput {
  /** The survey's blocks — elements live here (the legacy `questions` model is not enumerated). */
  blocks: TSurveyBlocks;
  embeddedData: readonly TLinkedEmbeddedField[];
  reservedEntries: readonly TReservedFieldCatalogEntry[];
  contactAttributeKeys: readonly Pick<TContactAttributeKey, "key" | "name">[];
  /** Language for element headlines; falls back to each headline's `default` entry. */
  languageCode?: string;
}

/**
 * Matches one full recall token (`#recall:<id>/fallback:<text>#`) — the editor's storage syntax.
 * `.replace()` only: `.test()`/`.exec()` would carry `lastIndex` across calls on this shared instance.
 */
const RECALL_TOKEN_REGEX = /#recall:[A-Za-z0-9_-]+\/fallback:[^#]*#/g;

/**
 * A blank label draws a row with nothing to read or click (the same reasoning behind
 * `ZEmbeddedData`'s name rule), and not every source guarantees a non-blank name — legacy variable
 * names and contact attribute display names are plain strings. The reference key always exists, so
 * it is the fallback, applied uniformly to all four groups.
 */
const labelOrKey = (label: string, key: string): string => (label.trim() === "" ? key : label);

/**
 * Headline → picker label: localized, HTML stripped so rich-text markup never shows raw, and recall
 * tokens flattened to `___` so storage syntax never leaks into a picker (what the apps/web pickers
 * achieve via `replaceRecallInfoWithUnderline`). Localization follows packages/surveys'
 * `getLocalizedValue` — a blank or missing locale entry falls back to the `default` entry. That is
 * deliberately NOT today's apps/web picker behavior, whose `getLocalizedValue` has no default
 * fallback, so an untranslated headline labels there as the bare element id; ENG-1840/1853 inherit
 * this as a conscious label improvement when they swap pickers onto {@link listReadableFields}.
 */
const toElementLabel = (headline: TI18nString, languageCode: string): string => {
  const localized = headline[languageCode];
  const fallback = typeof headline.default === "string" ? headline.default : "";
  const raw = typeof localized === "string" && localized.trim() !== "" ? localized : fallback;
  return getTextContent(raw).replace(RECALL_TOKEN_REGEX, "___").trim();
};

/**
 * Enumerates everything referenceable from a survey — the one list recall pickers, logic builders
 * and export columns will all read (ENG-1840/1853), so "what can I reference and by which key"
 * has a single answer. Each entry's `key` is the exact string {@link resolveEmbeddedValue} and the
 * existing map lookups address the value by:
 *
 * - question → the element id (label from its headline; the id itself when the headline is empty)
 * - embeddedData → the link's `storageKey` (never the definition's library `key` — the storage key
 *   is what recall tokens and response maps use, and the two can differ)
 * - reserved → the catalog entry name (title-cased; rendering callers relabel, see `reserved` below)
 * - contactAttribute → the contact attribute key (label from its display name when one is set)
 */
export const listReadableFields = (input: TListReadableFieldsInput): TReadableFields => {
  const languageCode = input.languageCode ?? "default";

  const question = input.blocks
    // A stored block can lack `elements` (an unvalidated draft or migrated block): it adds no fields.
    // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- stored blocks are not re-validated, ENG-2497
    .flatMap((block) => block.elements ?? [])
    .map((element) => ({
      key: element.id,
      label: labelOrKey(toElementLabel(element.headline, languageCode), element.id),
    }));

  const embeddedData = input.embeddedData.map(({ field, link }) => ({
    key: link.storageKey,
    label: labelOrKey(field.name, link.storageKey),
    // `key` is null for a survey-owned field and the library name for a shared one, so this is the
    // shared/local distinction itself rather than a display choice made here. `?? undefined` keeps
    // the property absent instead of null, so a consumer can test it with a plain truthiness check.
    secondaryLabel: field.key ?? undefined,
  }));

  const reserved = input.reservedEntries.map((entry) => ({
    key: entry.name,
    // English, derived from the catalog name. `packages/types` has no translator, so a *rendering*
    // caller overrides this with `getReservedFieldLabel` (apps/web), which is localized and knows
    // that `url` is "URL" rather than "Url". This stays as the label a non-rendering caller — an
    // export header, a test — gets without one.
    label: labelOrKey(formatFieldNameToTitleCase(entry.name), entry.name),
  }));

  const contactAttribute = input.contactAttributeKeys.map((attributeKey) => ({
    key: attributeKey.key,
    label: labelOrKey(attributeKey.name ?? "", attributeKey.key),
  }));

  return { question, embeddedData, reserved, contactAttribute };
};

// Defined in `embedded-data-fields` to keep them free of this module's runtime imports; re-exported
// so callers keep importing them from here.
export {
  getComputedEmbeddedFields,
  getIngestedEmbeddedFields,
  getIngestedStorageKeys,
  getSurveyEmbeddedFields,
  type TEmbeddedFieldsSurvey,
} from "./embedded-data-fields";

/**
 * What an ingested field answers with when nothing usable was supplied for it — its `defaultValue`,
 * keyed by storage key, for the caller to merge **under** `response.data`.
 *
 * The default only ever exists at read time. `applyIngestContract` deliberately never writes it
 * (rule 8: two writers would let a later change to a default apply on one path and not the other),
 * so a field nothing arrived for keeps its key omitted from storage — and without a read that
 * applies the default, the declared fallback reaches nothing at all. A recall token then renders its
 * own `fallback:` text, and a logic condition reads the field as unset.
 *
 * The two tiers match {@link resolveEmbeddedValue}'s field arm rather than restating it: a stored
 * value that does not fit the field's `dataType` reads as unset and resolves to the default. That is
 * the same answer, and the right one — ingest keeps an uncoercible value verbatim and flags it
 * `coercion_failed`, and what a survey shows should be the field's declared fallback, not the text
 * that failed to be a number.
 *
 * `locked` is read before the stored value, not instead of it. `applyIngestContract` already drops
 * an incoming value for a locked field, so on the ingest path the key is absent anyway — but a field
 * locked *after* its survey collected responses has values in storage that were legitimate when they
 * arrived, and for those the resolver answers with the default. Leaving `locked` to the contract
 * alone would make this projection disagree with the seam it mirrors on exactly that survey.
 *
 * Booleans are stringified the way {@link projectReservedValues} stringifies them — `TResponseData`
 * has no boolean member, and `"true"` / `"false"` is the spelling ingest stores.
 */
export const projectIngestedDefaults = (
  survey: TEmbeddedFieldsSurvey,
  data: TResponseData
): Record<string, string | number> => {
  const defaults: Record<string, string | number> = {};

  for (const { field, link } of getIngestedEmbeddedFields(survey)) {
    const stored = field.locked ? undefined : data[link.storageKey];
    if (coerceToEmbeddedDataType(stored, field.dataType) !== undefined) continue;

    const fallback = coerceToEmbeddedDataType(field.defaultValue, field.dataType);
    if (fallback === undefined) continue;

    defaults[link.storageKey] = typeof fallback === "boolean" ? String(fallback) : fallback;
  }

  return defaults;
};
