import { V3_CONTRACT_CATALOG } from '../../_lib/contracts';
import { V3_API_ROUTES } from '../../_lib/inventory';
import { staticV3Json, V3_PROTOCOL_VERSION, V3_SCHEMA_VERSION } from '../../_lib/http';
import { requireV3X402Release } from '../../x402/_lib/release';

const SDK_DISPOSITIONS = Object.freeze({
  supported: ['bonds', 'pullCredits', 'solvency', 'mandates', 'capabilities', 'taskEscrow', 'governance'],
  degraded: [],
  unavailable: ['x402.status', 'x402.discovery', 'x402.challenge', 'x402.receipt'],
  retired: ['latest', 'v2-fallback'],
});

export function createV3MigrationDispositions(now = new Date()) {
  return {
    schema: 'vaultfire.v3.migration-dispositions.v1',
    schemaVersion: V3_SCHEMA_VERSION,
    protocolVersion: V3_PROTOCOL_VERSION,
    route: '/api/v3/migration/dispositions',
    generatedAt: now.toISOString(),
    policy: {
      v3OptInOnly: true,
      v2PreservedUnchanged: true,
      v2Fallback: 'forbidden',
      writesEnabled: false,
      paymentsEnabled: false,
      prohibitedDecisionInputs: [
        'behavioral-scoring', 'reputation', 'loyalty', 'quality', 'belief',
        'biometric', 'profiling', 'surveillance', 'subjective-flourishing',
      ],
    },
    canonicalSdk: SDK_DISPOSITIONS,
    pilot: {
      deploymentState: 'unconfigured',
      supportedContracts: V3_CONTRACT_CATALOG.filter((entry) => entry.disposition === 'supported').map((entry) => entry.name),
      deferredContracts: V3_CONTRACT_CATALOG.filter((entry) => entry.disposition === 'deferred').map((entry) => entry.name),
      retiredContracts: V3_CONTRACT_CATALOG.filter((entry) => entry.disposition === 'retired').map((entry) => entry.name),
    },
    routes: V3_API_ROUTES,
  } as const;
}

export function assertV3MigrationDispositions(value: unknown): void {
  const body = value as Record<string, any>;
  if (
    !body || body.schema !== 'vaultfire.v3.migration-dispositions.v1' ||
    body.schemaVersion !== V3_SCHEMA_VERSION || body.protocolVersion !== V3_PROTOCOL_VERSION ||
    body.route !== '/api/v3/migration/dispositions' || Number.isNaN(Date.parse(body.generatedAt)) ||
    body.policy?.v3OptInOnly !== true || body.policy?.v2PreservedUnchanged !== true ||
    body.policy?.v2Fallback !== 'forbidden' || body.policy?.writesEnabled !== false ||
    body.policy?.paymentsEnabled !== false || body.pilot?.deploymentState !== 'unconfigured' ||
    !Array.isArray(body.routes) || body.routes.length !== V3_API_ROUTES.length ||
    body.canonicalSdk?.supported?.length !== 7 || body.canonicalSdk?.unavailable?.length !== 4
  ) throw new Error('invalid V3 migration dispositions');
}

export function GET(): Response {
  const closed = requireV3X402Release();
  if (closed) return closed;
  return staticV3Json(createV3MigrationDispositions(), assertV3MigrationDispositions);
}
