import { assertV3RouteRegistry, V3_ROUTES } from '../_lib/registry';
import { requireV3X402Release } from '../_lib/release';
import { evaluateV3BazaarPublicationGate } from '../_lib/capabilities';

export function createV3DiscoveryDocument(now = new Date()) {
  assertV3RouteRegistry(V3_ROUTES);
  return {
    schema: 'vaultfire.v3.x402.discovery.v1',
    schemaVersion: '1.0.0',
    protocolVersion: '3.0.0',
    x402Version: 2,
    releaseMode: 'read-only-fail-closed-v1',
    readiness: 'limited',
    generatedAt: now.toISOString(),
    endpoints: V3_ROUTES,
    bazaar: {
      publicationState: 'not-published',
      indexingVerified: false,
      indexedResourceCount: 0,
      v3CandidateCount: 0,
      publicationGate: evaluateV3BazaarPublicationGate(),
    },
    settlement: {
      enabled: false,
      evidenceVerified: false,
      receiptStore: 'read-only-status-boundary',
      realV3AddressVerified: false,
    },
    safety: {
      autoWalletConnection: false,
      autoSign: false,
      autoPay: false,
      v2Fallback: false,
      missionSensitiveDecisionInputs: 'retired-or-fail-closed',
    },
  };
}

export function assertV3DiscoveryDocument(value: unknown): void {
  if (!value || typeof value !== 'object') throw new Error('V3 discovery must be an object');
  const body = value as Record<string, any>;
  if (
    body.schema !== 'vaultfire.v3.x402.discovery.v1' ||
    body.protocolVersion !== '3.0.0' ||
    body.x402Version !== 2 ||
    body.releaseMode !== 'read-only-fail-closed-v1' ||
    body.readiness !== 'limited' ||
    !Array.isArray(body.endpoints) ||
    body.endpoints.length !== 20 ||
    body.schemaVersion !== '1.0.0' ||
    body.bazaar?.publicationState !== 'not-published' ||
    body.bazaar?.indexingVerified !== false ||
    body.bazaar?.indexedResourceCount !== 0 ||
    body.bazaar?.v3CandidateCount !== 0 ||
    body.bazaar?.publicationGate?.eligible !== false ||
    body.bazaar?.publicationGate?.candidateCount !== 0 ||
    body.settlement?.enabled !== false ||
    body.settlement?.evidenceVerified !== false ||
    body.settlement?.realV3AddressVerified !== false ||
    body.safety?.autoWalletConnection !== false ||
    body.safety?.autoSign !== false ||
    body.safety?.autoPay !== false ||
    body.safety?.v2Fallback !== false ||
    body.safety?.missionSensitiveDecisionInputs !== 'retired-or-fail-closed'
  ) {
    throw new Error('invalid V3 discovery document');
  }
  assertV3RouteRegistry(body.endpoints);
}

export function GET(): Response {
  const closed = requireV3X402Release();
  if (closed) return closed;
  try {
    const body = createV3DiscoveryDocument();
    assertV3DiscoveryDocument(body);
    return Response.json(body, {
      headers: { 'Cache-Control': 'no-store', 'X-Robots-Tag': 'noindex' },
    });
  } catch {
    return Response.json(
      { error: 'V3 discovery schema validation failed', code: 'v3_discovery_schema_invalid', retryable: false },
      { status: 503, headers: { 'Cache-Control': 'no-store', 'X-Robots-Tag': 'noindex' } },
    );
  }
}
