'use strict';

var pex$1 = require('@sphereon/pex');
var jsonpath = require('@astronautlabs/jsonpath');
var uuid = require('uuid');
var vc_verifiablePresentation = require('../vc/verifiable-presentation.cjs');
var vc_presentation = require('../vc/presentation.cjs');
var pex_pexBounds = require('./pex-bounds.cjs');
require('../vc/presentations.cjs');
require('jsonld');
require('jsonld-signatures');
require('@docknetwork/crypto-wasm-ts');
require('bs58');
require('@docknetwork/vc-delegation-engine');
require('../vc/credentials.cjs');
require('@digitalcredentials/vc-status-list');
require('base64url');
require('../vc/CredentialIssuancePurpose.cjs');
require('../vc/helpers.cjs');
require('@transmute/json-web-signature');
require('../vc/document-loader.cjs');
require('../vc/contexts.cjs');
require('../vc/contexts/vc-examples-v1.cjs');
require('../vc/contexts/security_context.cjs');
require('../vc/contexts/status-list-21.cjs');
require('../vc/contexts/private-status-list-21.cjs');
require('../utils/json-fetch.cjs');
require('../vc/crypto/Bls12381BBDT16KeyPairDock2024.cjs');
require('../vc/crypto/constants.cjs');
require('../vc/crypto/common/DockCryptoKeyPair.cjs');
require('../utils/types/bytes.cjs');
require('crypto');
require('../utils/interfaces.cjs');
require('../utils/assert.cjs');
require('../utils/error.cjs');
require('../utils/types/string.cjs');
require('../utils/types/iterable.cjs');
require('../utils/types/object.cjs');
require('../utils/inheritance.cjs');
require('../utils/types/set.cjs');
require('../vc/crypto/Bls12381BBDT16MACDock2024.cjs');
require('@docknetwork/crypto-wasm-ts/lib/index.js');
require('../vc/crypto/common/DockCryptoSignature.cjs');
require('json-stringify-deterministic');
require('semver/preload.js');
require('../vc/crypto/common/CustomLinkedDataSignature.cjs');
require('../types/did/document/verification-method-ref.cjs');
require('../types/generic/typed-enum.cjs');
require('../utils/types/array.cjs');
require('multiformats/bases/base58');
require('varint');
require('../utils/encoding/ss-58.cjs');
require('blake2b');
require('../types/generic/with-base.cjs');
require('../types/generic/with-catch-null.cjs');
require('../types/generic/with-eq.cjs');
require('../types/generic/any-of.cjs');
require('../types/generic/with-from.cjs');
require('../types/generic/with-from-json-bytes.cjs');
require('../types/generic/typed-null.cjs');
require('../types/generic/create-placeholder.cjs');
require('../types/generic/typed-bytes.cjs');
require('../types/generic/typed-string.cjs');
require('../types/generic/typed-array.cjs');
require('../types/generic/typed-tuple.cjs');
require('../types/generic/typed-number.cjs');
require('../types/generic/typed-set.cjs');
require('../types/generic/typed-map.cjs');
require('../types/generic/typed-struct.cjs');
require('js-sha256');
require('../types/generic/with-qualifier.cjs');
require('../types/generic/utils.cjs');
require('../types/generic/typed-bytes-array.cjs');
require('../types/did/onchain/typed-did/index.cjs');
require('../types/did/onchain/typed-did/did-method-key/did-method-key-public-key.cjs');
require('../utils/encoding/base-58-btc.cjs');
require('../types/generic/sized.cjs');
require('../utils/types/number.cjs');
require('../types/public-keys/public-key.cjs');
require('../types/public-keys/public-key-x25519-value.cjs');
require('../types/public-keys/public-key-ed25519-value.cjs');
require('../types/public-keys/public-key-secp256k1-value.cjs');
require('../types/public-keys/public-key-sr25519-value.cjs');
require('../types/did/onchain/constants.cjs');
require('../types/did/onchain/typed-did/signature.cjs');
require('../types/did/onchain/typed-did/did-method-key/did-method-key-signature.cjs');
require('../types/signatures/signature-value.cjs');
require('../types/signatures/signature-ed25519-value.cjs');
require('../types/signatures/signature-secp256k1-value.cjs');
require('../types/signatures/signature.cjs');
require('../types/signatures/signature-sr25519-value.cjs');
require('../types/did/onchain/typed-did/dock-did-value.cjs');
require('../types/generic/typed-uuid.cjs');
require('../types/did/onchain/typed-did/cheqd-did.cjs');
require('../vc/jws.cjs');
require('../vc/crypto/Bls12381BBDT16MACProofDock2024.cjs');
require('../vc/crypto/common/DockCryptoSignatureProof.cjs');
require('../vc/crypto/Bls12381BBSKeyPairDock2023.cjs');
require('../vc/crypto/Bls12381BBSSignatureDock2022.cjs');
require('../vc/crypto/Bls12381G2KeyPairDock2022.cjs');
require('../vc/crypto/Bls12381BBSSignatureDock2023.cjs');
require('../vc/crypto/Bls12381BBSSignatureProofDock2022.cjs');
require('../vc/crypto/Bls12381BBSSignatureProofDock2023.cjs');
require('../vc/crypto/Bls12381BDDT16KeyPairDock2024.cjs');
require('../vc/crypto/Bls12381BDDT16MACDock2024.cjs');
require('../vc/crypto/Bls12381BDDT16MACProofDock2024.cjs');
require('../vc/crypto/Bls12381PSKeyPairDock2023.cjs');
require('../vc/crypto/Bls12381PSSignatureDock2023.cjs');
require('../vc/crypto/Bls12381PSSignatureProofDock2023.cjs');
require('../vc/crypto/EcdsaSecp256k1Signature2019.cjs');
require('../vc/crypto/EcdsaSecp256k1VerificationKey2019.cjs');
require('@juanelas/base64');
require('../keypairs/keypair-secp256k1.cjs');
require('elliptic');
require('../keypairs/dock-keypair.cjs');
require('../utils/encoding/multibase.cjs');
require('../vc/crypto/Ed25519Signature2018.cjs');
require('../vc/crypto/Ed25519VerificationKey2018.cjs');
require('../keypairs/keypair-ed25519.cjs');
require('@stablelib/ed25519');
require('../vc/crypto/Ed25519Signature2020.cjs');
require('../vc/crypto/Ed25519VerificationKey2020.cjs');
require('../vc/crypto/JsonWebSignature2020.cjs');
require('../keypairs/did-keypair.cjs');
require('../types/did/onchain/did-key.cjs');
require('../types/offchain-signatures/params/index.cjs');
require('../types/offchain-signatures/params/value.cjs');
require('../types/generic/option.cjs');
require('../types/offchain-signatures/curve-type.cjs');
require('../types/offchain-signatures/params/id.cjs');
require('../types/generic/with-from-dock-id.cjs');
require('../types/offchain-signatures/public-keys/index.cjs');
require('../types/generic/with-prop.cjs');
require('../types/generic/with-props.cjs');
require('../types/offchain-signatures/public-keys/value.cjs');
require('../types/offchain-signatures/public-keys/ref.cjs');
require('../types/offchain-signatures/public-keys/id.cjs');
require('../types/did/onchain/verification-relationship.cjs');
require('../types/did/document/verification-method-ref-or-ident-ref.cjs');
require('../types/did/document/ident-ref.cjs');
require('../vc/schema.cjs');
require('jsonschema');
require('../vc/constants.cjs');
require('../vc/revocation.cjs');
require('blakejs');
require('../utils/ident/ensure-ident.cjs');
require('../utils/ident/matchers.cjs');
require('../vc/verifiable-credential.cjs');

const DEFAULT_LIMIT_DISCLOSURE_SUITES = [
  'Bls12381BBS+SignatureDock2022',
  'Bls12381BBSSignatureDock2023',
  'Bls12381PSSignatureDock2023',
  'Bls12381BBDT16MACDock2024',
];

const SELECTIVE_DISCLOSURE_SIGNATURE_TYPES = new Set(DEFAULT_LIMIT_DISCLOSURE_SUITES);

const pex = new pex$1.PEX();

const GeneratePresentationStatus = Object.freeze({
  SUCCESS: 'success',
  REQUIREMENTS_NOT_MET: 'requirements_not_met',
  SELECTIVE_DISCLOSURE_REQUIRED: 'selective_disclosure_required',
});

function ensurePresentationDefinition(pexRequest) {
  if (!pexRequest) {
    throw new Error('pexRequest is required');
  }

  if (pexRequest.presentationDefinition) {
    return pexRequest.presentationDefinition;
  }

  if (pexRequest.presentation_definition) {
    return pexRequest.presentation_definition;
  }

  return pexRequest;
}

function flattenAttributes(attributes) {
  if (!Array.isArray(attributes)) {
    return [];
  }
  return attributes.flatMap((attribute) => (Array.isArray(attribute) ? attribute : [attribute]));
}

function normalizeHolderDids({ explicitHolderDids = [], holderDid, holderKeyDoc }) {
  const dids = [...explicitHolderDids];
  const inferred = holderDid || holderKeyDoc?.controller;
  if (inferred && !dids.includes(inferred)) {
    dids.push(inferred);
  }
  return dids;
}

function requiresSelectiveDisclosure(presentationDefinition) {
  return presentationDefinition?.input_descriptors?.some(
    (descriptor) => descriptor?.constraints?.limit_disclosure === 'required',
  );
}

function dedupeAttributes(attributes = []) {
  return [...new Set(attributes)];
}

function isSelectiveDisclosureCredential(credential) {
  const proofType = credential?.proof?.type;
  return typeof proofType === 'string'
    && SELECTIVE_DISCLOSURE_SIGNATURE_TYPES.has(proofType);
}

function normalizeSelectiveDisclosureConfigs(configs = [], expectedLength) {
  if (!Array.isArray(configs)) {
    return Array(expectedLength).fill(undefined);
  }
  const normalized = [...configs];
  while (normalized.length < expectedLength) {
    normalized.push(undefined);
  }
  return normalized;
}

function normalizeAttributesConfig(attributes) {
  if (!attributes) {
    return undefined;
  }
  if (typeof attributes === 'string') {
    return [attributes];
  }
  if (Array.isArray(attributes?.[0])) {
    return flattenAttributes(attributes);
  }
  return Array.isArray(attributes) ? attributes : undefined;
}

function buildSelectiveDisclosureConfigs(selectiveDisclosure = {}, credentialCount) {
  if (!selectiveDisclosure) {
    return Array(credentialCount).fill(undefined);
  }

  let configs = selectiveDisclosure.credentials?.map((config) => {
    if (!config) {
      return undefined;
    }
    return {
      ...config,
      attributes: normalizeAttributesConfig(config.attributes),
    };
  });

  if (
    (!configs || configs.length === 0)
    && (
      selectiveDisclosure.attributes
      || selectiveDisclosure.witness
    )
  ) {
    configs = [{
      attributes: normalizeAttributesConfig(selectiveDisclosure.attributes),
      witness: selectiveDisclosure.witness,
    }];
  }

  return normalizeSelectiveDisclosureConfigs(configs, credentialCount);
}

function filterCredentialsByPexRequest({
  credentials = [],
  pexRequest,
  holderDids = [],
  holderDid,
  holderKeyDoc,
  limitDisclosureSignatureSuites = DEFAULT_LIMIT_DISCLOSURE_SUITES,
  restrictToFormats,
  restrictToDIDMethods,
} = {}) {
  const presentationDefinition = ensurePresentationDefinition(pexRequest);
  const normalizedDids = normalizeHolderDids({ explicitHolderDids: holderDids, holderDid, holderKeyDoc });

  return pex.selectFrom(presentationDefinition, credentials, {
    holderDIDs: normalizedDids.length ? normalizedDids : undefined,
    limitDisclosureSignatureSuites,
    restrictToFormats,
    restrictToDIDMethods,
  });
}

function evaluatePresentationAgainstDefinition({
  presentation,
  pexRequest,
  presentationSubmission,
  limitDisclosureSignatureSuites = DEFAULT_LIMIT_DISCLOSURE_SUITES,
  restrictToFormats,
  restrictToDIDMethods,
} = {}) {
  if (!presentation) {
    throw new Error('presentation is required');
  }

  const presentationDefinition = ensurePresentationDefinition(pexRequest);

  return pex.evaluatePresentation(presentationDefinition, presentation, {
    presentationSubmission,
    limitDisclosureSignatureSuites,
    restrictToFormats,
    restrictToDIDMethods,
  });
}

const attributesToSkip = [
  /^type/,
  /^issuer/,
  /^@context/,
  /^proof/,
  /^credentialSchema/,
  /^issuanceDate/,
];

const shouldSkipAttribute = (attributeName) => attributesToSkip.some((regex) => regex.test(attributeName));

function correctFieldPath(path) {
  return path.replace('$.', '');
}

function getAttributeName({ field, selectedCredentials, index }) {
  let attributeName;
  if (Array.isArray(field.path) && field.path.length > 1) {
    const selectedCredential = selectedCredentials[index];
    if (!selectedCredential) {
      return undefined;
    }

    for (let i = 0; i < field.path.length; i += 1) {
      const path = field.path[i];
      const paths = jsonpath.JSONPath.paths(selectedCredential, path);
      if (paths.length) {
        attributeName = correctFieldPath(jsonpath.JSONPath.stringify(paths[0]));
        break;
      }
    }
  } else {
    attributeName = correctFieldPath(Array.isArray(field.path) ? field.path[0] : field.path);
  }

  return attributeName;
}

function getPexRequiredAttributes(pexRequest, selectedCredentials = []) {
  const presentationDefinition = ensurePresentationDefinition(pexRequest);
  const descriptors = presentationDefinition.input_descriptors || [];
  return descriptors
    .map((inputDescriptor, index) => {
      if (!inputDescriptor?.constraints?.fields?.length) {
        return [];
      }

      return inputDescriptor.constraints.fields
        .filter((field) => {
          if (field.filter || field.optional) {
            return false;
          }

          try {
            const credential = selectedCredentials[index];
            if (!credential) {
              return false;
            }

            const paths = Array.isArray(field.path)
              ? field.path.flatMap((singlePath) => jsonpath.JSONPath.paths(credential, singlePath))
              : jsonpath.JSONPath.paths(credential, field.path);
            return paths.length !== 0;
          } catch (error) {
            console.error(`Error in field ${field.path}: ${error.message}`);
            return false;
          }
        })
        .map((field) => getAttributeName({ field, selectedCredentials, index }))
        .filter((attributeName) => attributeName && !shouldSkipAttribute(attributeName));
    });
}

const PEX_SUBMISSION_CONTEXT = {
  '@version': 1.1,
  presentation_submission: {
    '@id': 'https://identity.foundation/presentation-exchange/#presentation-submission',
    '@type': '@json',
  },
};

/**
 * Generates a (potentially selective-disclosure) presentation that satisfies a Presentation Exchange definition.
 *
 * @param {object} params - Options for presentation derivation.
 * @param {Array<object|string>} params.credentials - The verifiable credentials (JSON objects or serialized JSON strings) to evaluate.
 * @param {object} params.pexRequest - Presentation Definition or a wrapper that contains one (`presentationDefinition` or `presentation_definition`).
 * @param {object} [params.holderKeyDoc] - Holder key material used to sign the presentation when `skipSigning` is false.
 * @param {string} [params.holderDid] - DID that should be set as the presentation holder (falls back to `holderKeyDoc.controller`).
 * @param {Array<string>} [params.holderDids] - Explicit holder DID list passed through to PEX selection.
 * @param {string} [params.challenge] - Challenge used when signing or verifying derived presentations.
 * @param {string} [params.domain] - Domain used when signing selective disclosure presentations.
 * @param {string} [params.presentationId] - Optional identifier for the generated presentation.
 * @param {PresentationSubmissionLocation} [params.presentationSubmissionLocation=PresentationSubmissionLocation.PRESENTATION] - Location for the presentation submission descriptor.
 * @param {object} [params.resolver] - DID resolver used by the Presentation builder and range-proof witness lookups.
 * @param {boolean} [params.compactProof=true] - Whether holder signatures should omit canonical proof fields.
 * @param {Array<string>} [params.limitDisclosureSignatureSuites=DEFAULT_LIMIT_DISCLOSURE_SUITES] - Signature suites that are considered selective-disclosure capable by PEX.
 * @param {Array<string>} [params.restrictToFormats] - Optional PEX filter restricting acceptable VC proof formats.
 * @param {Array<string>} [params.restrictToDIDMethods] - Optional PEX filter restricting acceptable DID methods.
 * @param {boolean} [params.skipSigning=false] - When true, the generated presentation is returned unsigned (useful for SD proofs or tests).
 * @param {Function} [params.loadProvingKey] - Async loader invoked with `{ credentialIndex, presentationDefinition }` and returning `{ provingKey, provingKeyId }` for bound proofs.
 * @param {object} [params.selectiveDisclosure] - Configuration for attribute revelation (global `attributes`), per-credential configs (`credentials[index]`), accumulator witnesses, and presentation builder options.
 * @returns {Promise<object>} Result object containing status, presentation (or derived credentials) and any warnings/errors from PEX.
 */
/* eslint-disable-next-line sonarjs/cognitive-complexity */
async function generatePresentationFromPexRequest({
  credentials = [],
  pexRequest,
  holderKeyDoc,
  holderDid,
  holderDids = [],
  challenge,
  domain,
  presentationId,
  presentationSubmissionLocation = pex$1.PresentationSubmissionLocation.PRESENTATION,
  resolver,
  compactProof = true,
  limitDisclosureSignatureSuites = DEFAULT_LIMIT_DISCLOSURE_SUITES,
  restrictToFormats,
  restrictToDIDMethods,
  skipSigning = false,
  loadProvingKey,
  selectiveDisclosure,
} = {}) {
  const presentationDefinition = ensurePresentationDefinition(pexRequest);
  const selectResults = filterCredentialsByPexRequest({
    credentials,
    pexRequest: presentationDefinition,
    holderDids,
    holderDid,
    holderKeyDoc,
    limitDisclosureSignatureSuites,
    restrictToFormats,
    restrictToDIDMethods,
  });
  const selectedCredentials = selectResults.verifiableCredential || [];

  if (
    selectResults.areRequiredCredentialsPresent === pex$1.Status.ERROR
    || selectedCredentials.length === 0
  ) {
    return {
      status: GeneratePresentationStatus.REQUIREMENTS_NOT_MET,
      error: new Error('Provided credentials do not satisfy the presentation definition'),
      details: selectResults,
    };
  }

  const pexRequiredAttributes = getPexRequiredAttributes(
    presentationDefinition,
    selectedCredentials,
  );
  const selectiveDisclosureRequired = requiresSelectiveDisclosure(presentationDefinition);
  const selectiveConfigs = buildSelectiveDisclosureConfigs(
    selectiveDisclosure,
    selectedCredentials.length,
  );

  if (selectiveDisclosureRequired) {
    const missingAttributes = pexRequiredAttributes.some((required, index) => {
      if (!required.length) {
        return false;
      }
      const provided = new Set(selectiveConfigs[index]?.attributes || []);
      return required.some((attribute) => !provided.has(attribute));
    });
    if (missingAttributes) {
      return {
        status: GeneratePresentationStatus.SELECTIVE_DISCLOSURE_REQUIRED,
        error: new Error('Presentation definition requires selective disclosure'),
        details: selectResults,
        selectiveDisclosure: {
          requiredAttributes: pexRequiredAttributes,
        },
      };
    }
  }

  const needsSelectiveDisclosure = selectiveConfigs.some((config, index) => {
    const required = pexRequiredAttributes[index] || [];
    const provided = config?.attributes || [];
    return required.length > 0
      || provided.length > 0
      || config?.witness;
  }) || Boolean(loadProvingKey);

  const boundOptions = {
    loadProvingKey,
    presentationOptions: selectiveDisclosure?.presentationOptions,
  };

  const shouldRunSelectiveFlow = needsSelectiveDisclosure || Boolean(loadProvingKey);

  let updatedCredentials = selectedCredentials;

  if (shouldRunSelectiveFlow) {
    updatedCredentials = await deriveSelectiveDisclosureCredentials({
      selectedCredentials,
      resolver,
      presentationDefinition,
      pexRequiredAttributes,
      selectiveConfigs,
      boundOptions,
    });
  }

  if (!skipSigning && !holderKeyDoc) {
    throw new Error('holderKeyDoc is required when skipSigning is false');
  }

  if (!skipSigning && !challenge) {
    throw new Error('challenge is required when skipSigning is false');
  }

  const presentationSubmission = pex.presentationSubmissionFrom(
    presentationDefinition,
    updatedCredentials,
    {
      presentationSubmissionLocation,
    },
  );

  const vpId = presentationId || `urn:uuid:${uuid.v4()}`;
  const vp = new vc_verifiablePresentation(vpId);
  updatedCredentials.forEach((credential) => {
    vp.addCredential(credential);
  });
  const normalizedHolder = holderDid || holderKeyDoc?.controller;
  if (normalizedHolder) {
    vp.setHolder(normalizedHolder);
  }
  if (presentationSubmissionLocation === pex$1.PresentationSubmissionLocation.PRESENTATION) {
    vp.addContext(PEX_SUBMISSION_CONTEXT);
    vp.presentation_submission = presentationSubmission;
  }

  if (skipSigning) {
    return {
      status: GeneratePresentationStatus.SUCCESS,
      presentation: vp.toJSON(),
      presentationSubmission,
      warnings: selectResults.warnings || [],
      matches: selectResults.matches || [],
    };
  }

  const signedPresentation = await vp.sign(
    holderKeyDoc,
    challenge,
    domain,
    resolver,
    compactProof,
  );

  return {
    status: GeneratePresentationStatus.SUCCESS,
    presentation: signedPresentation.toJSON(),
    presentationSubmission,
    warnings: selectResults.warnings || [],
    matches: selectResults.matches || [],
  };
}

/* eslint-disable-next-line sonarjs/cognitive-complexity */
async function deriveSelectiveDisclosureCredentials({
  selectedCredentials,
  resolver,
  presentationDefinition,
  pexRequiredAttributes,
  selectiveConfigs,
  boundOptions = {},
}) {
  const globalBoundsEnabled = Boolean(boundOptions.loadProvingKey);
  const derivationPlan = selectedCredentials.map((credential, index) => {
    const config = selectiveConfigs[index] || {};
    const requiredAttributes = pexRequiredAttributes[index] || [];
    const customAttributes = config.attributes || [];
    const attributesToReveal = dedupeAttributes([
      ...customAttributes,
      ...requiredAttributes,
    ]);
    const shouldDerive = globalBoundsEnabled
      || attributesToReveal.length > 0
      || !!config.witness;
    return {
      credential,
      attributesToReveal,
      witness: config.witness,
      shouldDerive,
    };
  });

  if (!derivationPlan.some((item) => item.shouldDerive)) {
    return selectedCredentials;
  }

  derivationPlan.forEach((plan, index) => {
    if (plan.shouldDerive && !isSelectiveDisclosureCredential(plan.credential)) {
      throw new Error(`Selective disclosure is not supported for credential at index ${index}`);
    }
  });

  const presentation = new vc_presentation();
  const sourceToBuilderMap = [];

  for (let index = 0; index < derivationPlan.length; index += 1) {
    const plan = derivationPlan[index];
    if (plan.shouldDerive) {
      const { credential } = plan;
      const clonedCredential = typeof credential === 'string'
        ? JSON.parse(credential)
        : JSON.parse(JSON.stringify(credential));
      // eslint-disable-next-line no-await-in-loop
      const builderIndex = await presentation.addCredentialToPresent(clonedCredential, {
        resolver,
      });
      sourceToBuilderMap.push({ sourceIndex: index, builderIndex });
    }
  }

  const descriptorBoundsMap = {};

  for (const { sourceIndex, builderIndex } of sourceToBuilderMap) {
    const plan = derivationPlan[sourceIndex];
    if (globalBoundsEnabled) {
      // eslint-disable-next-line no-await-in-loop
      const proofConfig = await resolveProvingKeyConfig({
        loadProvingKey: boundOptions.loadProvingKey,
        credentialIndex: sourceIndex,
        presentationDefinition,
      });
      if (proofConfig?.provingKey) {
        const scopedBounds = pex_pexBounds.applyEnforceBounds({
          builder: presentation.presBuilder,
          presentationDefinition,
          provingKeyId: proofConfig.provingKeyId || 'key0',
          provingKey: proofConfig.provingKey,
          selectedCredentials: [plan.credential],
          credentialIdx: builderIndex,
        });
        if (scopedBounds[builderIndex]) {
          descriptorBoundsMap[sourceIndex] = scopedBounds[builderIndex];
        }
      }
    }
    const boundsForCredential = descriptorBoundsMap[sourceIndex] || [];
    const boundAttributes = boundsForCredential.map((bound) => bound.attributeName);
    const filteredAttributes = (plan.attributesToReveal || []).filter(
      (attribute) => attribute
        && !boundAttributes.includes(attribute)
        && !shouldSkipAttribute(attribute),
    );
    const requiredAttributes = pexRequiredAttributes[sourceIndex] || [];
    requiredAttributes.forEach((attribute) => {
      if (attribute && !filteredAttributes.includes(attribute)) {
        filteredAttributes.push(attribute);
      }
    });

    if (filteredAttributes.length) {
      presentation.addAttributeToReveal(builderIndex, filteredAttributes);
    }
    if (plan.witness) {
      const {
        membershipWitness,
        accumulated,
        pk,
        params,
      } = plan.witness;
      presentation.presBuilder.addAccumInfoForCredStatus(
        builderIndex,
        membershipWitness,
        accumulated,
        pk,
        params,
      );
    }
  }

  const derivedCredentials = await presentation.deriveCredentials(
    boundOptions.presentationOptions,
  );

  const updatedCredentials = [...selectedCredentials];
  let derivedIndex = 0;
  sourceToBuilderMap.forEach(({ sourceIndex }) => {
    updatedCredentials[sourceIndex] = derivedCredentials[derivedIndex];
    derivedIndex += 1;
  });

  return updatedCredentials;
}

async function resolveProvingKeyConfig({
  loadProvingKey,
  credentialIndex,
  presentationDefinition,
}) {
  if (typeof loadProvingKey !== 'function') {
    return null;
  }
  const loaded = await loadProvingKey({
    credentialIndex,
    presentationDefinition,
  });
  if (!loaded?.provingKey) {
    return null;
  }
  return {
    provingKey: loaded.provingKey,
    provingKeyId: loaded.provingKeyId || 'key0',
  };
}

exports.GeneratePresentationStatus = GeneratePresentationStatus;
exports.evaluatePresentationAgainstDefinition = evaluatePresentationAgainstDefinition;
exports.filterCredentialsByPexRequest = filterCredentialsByPexRequest;
exports.generatePresentationFromPexRequest = generatePresentationFromPexRequest;
exports.getPexRequiredAttributes = getPexRequiredAttributes;
exports.shouldSkipAttribute = shouldSkipAttribute;
//# sourceMappingURL=pex-utils.cjs.map
