/** Test-only Ed25519 fixture verifier; never included in the SDK build/API. */
import { createPublicKey, verify } from 'crypto';
import {
  BaseSepoliaV3ArtifactEvidenceAttestation,
  canonicalAttestationV2SigningBytes,
  parseCanonicalEvidenceJson,
} from '../../src/baseSepoliaV3Rehearsal';

const TEST_ATTESTATION_KEYS = [
  'schema', 'validator', 'domain', 'chainId', 'manifestArtifactHash',
  'artifactEvidenceBundleSha256', 'validatorSourceSha256',
  'validatorTranscriptSha256', 'deploymentVerificationStatementSha256',
  'keyId', 'algorithm', 'signature',
].sort();
const SHA256 = /^[0-9a-f]{64}$/;

export function verifyTestOnlyBaseSepoliaV3Attestation(
  rawCanonicalAttestation: string,
  testOnlyPublicKeyRawHex: string,
): boolean {
  const receipt = parseCanonicalEvidenceJson(rawCanonicalAttestation, 'test attestation');
  if (Object.keys(receipt).sort().join(',') !== TEST_ATTESTATION_KEYS.join(',')) return false;
  if (
    receipt.schema !== 'vaultfire.base-sepolia-v3-artifact-attestation.v2'
    || receipt.validator !== 'validate_v3_candidate_manifest.py'
    || receipt.domain !== 'vaultfire.base-sepolia-v3.ready-attestation.v2'
    || receipt.chainId !== 84532
    || receipt.algorithm !== 'Ed25519'
    || typeof receipt.keyId !== 'string'
    || !['manifestArtifactHash', 'artifactEvidenceBundleSha256', 'validatorSourceSha256', 'validatorTranscriptSha256', 'deploymentVerificationStatementSha256'].every((field) => SHA256.test(String(receipt[field])))
    || typeof receipt.signature !== 'string'
    || !/^0x[0-9a-f]{128}$/i.test(receipt.signature)
    || !/^[0-9a-f]{64}$/i.test(testOnlyPublicKeyRawHex)
  ) return false;
  const spki = Buffer.concat([Buffer.from('302a300506032b6570032100', 'hex'), Buffer.from(testOnlyPublicKeyRawHex, 'hex')]);
  const key = createPublicKey({ key: spki, format: 'der', type: 'spki' });
  return verify(
    null,
    canonicalAttestationV2SigningBytes(receipt as unknown as BaseSepoliaV3ArtifactEvidenceAttestation),
    key,
    Buffer.from(receipt.signature.slice(2), 'hex'),
  );
}
