import { V3_REQUEST_ID_SOURCE } from '../../_lib/validation';

export const V3_X402_RELEASE_ENV = 'VAULTFIRE_X402_V3_RELEASE';
export const V3_X402_RELEASE_VALUE = 'read-only-fail-closed-v1';

const EXACT_PATHS = new Set([
  '/api/v3/contracts',
  '/api/v3/bonds',
  '/api/v3/pull-credits',
  '/api/v3/migration/dispositions',
  '/api/v3/protocol/solvency',
  '/api/v3/protocol/status',
  '/api/v3/x402/discovery',
  '/api/v3/x402/challenge-status',
  '/api/v3/solana/health',
  '/api/v3/x402/actions/create-partnership-bond',
]);

const MANDATE_PATH = /^\/api\/v3\/mandate\/0x[0-9a-f]{64}$/;
const PLURAL_MANDATE_PATH = /^\/api\/v3\/mandates\/0x[0-9a-f]{64}$/;
const RECEIPT_PATH = new RegExp(`^/api/v3/x402/receipts/${V3_REQUEST_ID_SOURCE}$`);
const CONTRACT_PATH = /^\/api\/v3\/contracts\/[A-Za-z][A-Za-z0-9]{1,79}$/;
const UINT_READ_PATH = /^\/api\/v3\/(?:bonds|disputes|tasks)\/(?:0|[1-9]\d*)$/;
const GOVERNANCE_PATH = /^\/api\/v3\/governance\/proposals\/(?:0|[1-9]\d*)$/;
const EVIDENCE_PATH = /^\/api\/v3\/evidence\/0x[0-9a-f]{64}$/;
const CHALLENGE_PATH = /^\/api\/v3\/x402\/challenges\/0x[0-9a-f]{64}$/;

export function isV3X402ReleaseEnabled(
  environment: Readonly<Record<string, string | undefined>> = process.env,
): boolean {
  return environment[V3_X402_RELEASE_ENV] === V3_X402_RELEASE_VALUE;
}

export function isAllowedV3ReleasePath(pathname: string): boolean {
  return EXACT_PATHS.has(pathname) ||
    MANDATE_PATH.test(pathname) ||
    PLURAL_MANDATE_PATH.test(pathname) ||
    RECEIPT_PATH.test(pathname) ||
    CONTRACT_PATH.test(pathname) ||
    UINT_READ_PATH.test(pathname) ||
    GOVERNANCE_PATH.test(pathname) ||
    EVIDENCE_PATH.test(pathname) ||
    CHALLENGE_PATH.test(pathname);
}

export function v3ReleaseGateClosedResponse(): Response {
  return Response.json(
    {
      schema: 'vaultfire.v3.release-gate.v1',
      schemaVersion: '1.0.0',
      protocolVersion: '3.0.0',
      error: 'Vaultfire V3 x402 routes are disabled pending explicit read-only release approval',
      code: 'v3_x402_release_gate_closed',
      retryable: false,
      releaseMode: 'disabled',
    },
    {
      status: 503,
      headers: {
        'Cache-Control': 'no-store',
        'X-Robots-Tag': 'noindex',
      },
    },
  );
}

export function requireV3X402Release(
  environment: Readonly<Record<string, string | undefined>> = process.env,
): Response | null {
  return isV3X402ReleaseEnabled(environment) ? null : v3ReleaseGateClosedResponse();
}
