/**
 * Truth labels shown next to every version-scoped surface on the website.
 *
 * The label strings are a fixed vocabulary. Copy that implies audit status,
 * production readiness, or fund safety beyond what the deployment record and
 * gates prove is not allowed.
 */

import {
  DEFAULT_V3_FLAGS,
  type ProtocolVersion,
  type V3FeatureFlags,
} from "./version-flags";
import type { WebsiteAddressEntry } from "../generated/website-addresses.generated";

export const TRUTH_LABELS = Object.freeze({
  LEGACY_V2: "Legacy V2",
  V3_TEST_DEPLOYMENT: "V3 test deployment",
  V3_AUDITED_PILOT: "V3 audited pilot",
  DEPRECATED: "Deprecated",
  READ_ONLY: "Read-only",
} as const);

export type TruthLabel = (typeof TRUTH_LABELS)[keyof typeof TRUTH_LABELS];

export const ALL_TRUTH_LABELS: readonly TruthLabel[] = Object.freeze([
  TRUTH_LABELS.LEGACY_V2,
  TRUTH_LABELS.V3_TEST_DEPLOYMENT,
  TRUTH_LABELS.V3_AUDITED_PILOT,
  TRUTH_LABELS.DEPRECATED,
  TRUTH_LABELS.READ_ONLY,
]);

export type LabelSubject = {
  readonly protocolVersion: ProtocolVersion;
  /** Canonical deployment record, or null when no verified address exists. */
  readonly deployment?: WebsiteAddressEntry | null;
  /** True when this surface can currently submit a state change. */
  readonly writesAvailable?: boolean;
};

/**
 * Resolves the labels for a surface. Order is stable so UI badges render
 * deterministically: version label first, then modifiers.
 */
export function resolveTruthLabels(
  subject: LabelSubject,
  flags: V3FeatureFlags = DEFAULT_V3_FLAGS,
): readonly TruthLabel[] {
  const labels: TruthLabel[] = [];
  const status = subject.deployment?.status;

  if (subject.protocolVersion === "v2") {
    labels.push(
      status === "deprecated" || status === "retired"
        ? TRUTH_LABELS.DEPRECATED
        : TRUTH_LABELS.LEGACY_V2,
    );
  } else {
    // No deployment record means no deployment label. A V3 surface may claim a
    // test deployment only with a verified V3 deployment record; audited pilot
    // additionally requires the explicit audited-pilot flag.
    if (subject.deployment) {
      const auditedPilot = flags.v3AuditedPilotEnabled;
      labels.push(
        auditedPilot ? TRUTH_LABELS.V3_AUDITED_PILOT : TRUTH_LABELS.V3_TEST_DEPLOYMENT,
      );
    }
    if (status === "deprecated" || status === "retired") {
      labels.push(TRUTH_LABELS.DEPRECATED);
    }
  }

  if (!subject.writesAvailable) labels.push(TRUTH_LABELS.READ_ONLY);
  return Object.freeze(labels);
}
