import { assertV3ApiRouteInventory, V3_API_ROUTES, type V3ApiRoute } from '../../_lib/inventory';

export type V3Route = V3ApiRoute & {
  free: true;
  version: 'v3';
  contractStatus: 'read-only';
  requestSchema: 'empty#';
  idempotencyRule: 'none';
  finality: 'soft';
  dataSource: 'computed';
  privacy: 'public' | 'restricted';
  availability: 'available' | 'fail-closed' | 'retired';
};

export const V3_ROUTES: readonly V3Route[] = Object.freeze(V3_API_ROUTES.map((route) => Object.freeze({
  ...route,
  free: true as const,
  version: 'v3' as const,
  contractStatus: 'read-only' as const,
  requestSchema: 'empty#' as const,
  idempotencyRule: 'none' as const,
  finality: 'soft' as const,
  dataSource: 'computed' as const,
  privacy: route.id === 'retired-partnership-write' ? 'restricted' as const : 'public' as const,
  availability: route.disposition === 'retired' ? 'retired' as const : route.deploymentRequired ? 'fail-closed' as const : 'available' as const,
})));

export function assertV3RouteRegistry(value: unknown): asserts value is readonly V3Route[] {
  assertV3ApiRouteInventory(value);
  for (const route of value as readonly V3Route[]) {
    if (route.free !== true || !['public', 'restricted'].includes(route.privacy) || route.finality !== 'soft' || route.dataSource !== 'computed' || route.version !== 'v3' || route.contractStatus !== 'read-only' || route.requestSchema !== 'empty#' || route.idempotencyRule !== 'none' || !['available', 'fail-closed', 'retired'].includes(route.availability)) throw new Error(`invalid V3 registry route: ${route.id}`);
  }
}

/** Exact stable lookup; aliases are forbidden because IDs bind authorization evidence. */
export function getV3Route(id: string): V3Route {
  const route = V3_ROUTES.find((candidate) => candidate.id === id);
  if (!route) throw new Error(`unknown V3 route: ${id}`);
  return route;
}
assertV3RouteRegistry(V3_ROUTES);
