import crypto from 'node:crypto';

const baseUrl = (process.env.MUJ428_BASE_URL || 'https://agents.muj428.com').replace(/\/$/, '');
const externalCallerRef = process.env.EXTERNAL_CALLER_REF || 'urn:example:external-agent';
const payload = { task: 'conformance_commit', message: 'hello from an external runtime' };
const actionRef = `external-conformance-${Date.now()}-${Math.random().toString(16).slice(2)}`;

const stableDigest = (value) =>
  crypto.createHash('sha256').update(JSON.stringify(value)).digest('hex');

const authorizationResponse = await fetch(`${baseUrl}/v1/integration-sandbox/authorize`, {
  method: 'POST',
  headers: { 'content-type': 'application/json', accept: 'application/json' },
  body: JSON.stringify({ action_ref: actionRef, external_caller_ref: externalCallerRef, payload })
});
const authorization = await authorizationResponse.json();
if (!authorizationResponse.ok) throw new Error(`Authorization failed: ${authorizationResponse.status} ${JSON.stringify(authorization)}`);
if (authorization.production_authority !== false || authorization.moves_money !== false || authorization.execution_authority !== 'SANDBOX_ONLY') {
  throw new Error('Refusing unexpected sandbox authority response');
}

const executionRequest = { receipt: authorization.receipt, current: authorization.current, payload };

const executionResponse = await fetch(`${baseUrl}/v1/integration-sandbox/execute`, {
  method: 'POST',
  headers: { 'content-type': 'application/json', accept: 'application/json' },
  body: JSON.stringify(executionRequest)
});
const execution = await executionResponse.json();
if (!executionResponse.ok || execution?.verified_effect?.effect_state !== 'COMMITTED') {
  throw new Error(`Execution failed: ${executionResponse.status} ${JSON.stringify(execution)}`);
}
if (execution.verified_effect.production_effect !== false || execution.verified_effect.moves_money !== false) {
  throw new Error('Refusing unexpected production or money-moving effect');
}

// Independently observable replay test: submit the exact same one-time receipt/effect again.
// The second attempt MUST fail closed and MUST expose an explicit replay reason.
const replayResponse = await fetch(`${baseUrl}/v1/integration-sandbox/execute`, {
  method: 'POST',
  headers: { 'content-type': 'application/json', accept: 'application/json' },
  body: JSON.stringify(executionRequest)
});
const replay = await replayResponse.json().catch(() => ({}));
const replayReasonCodes = Array.isArray(replay?.reason_codes) ? replay.reason_codes : [];
const acceptedReplayDenials = new Set(['NONCE_ALREADY_CONSUMED', 'EFFECT_ALREADY_COMMITTED']);
const replayDenied = replay?.ok === false && replayReasonCodes.some((code) => acceptedReplayDenials.has(code));

if (!replayDenied) {
  throw new Error(
    `Replay denial was not independently observable: HTTP ${replayResponse.status} ${JSON.stringify(replay)}`
  );
}

const fixture = {
  action_ref: actionRef,
  external_caller_ref: externalCallerRef,
  payload
};

console.log(JSON.stringify({
  observed_at: new Date().toISOString(),
  fixture_sha256: stableDigest(fixture),
  action_ref: actionRef,
  external_caller_ref: externalCallerRef,
  receipt_id: authorization.receipt.action_id,
  receipt_digest: execution.verified_effect.receipt_digest || stableDigest(authorization.receipt),
  verified_effect: execution.verified_effect,
  replay_proof: {
    replay_denied: true,
    http_status: replayResponse.status,
    reason_codes: replayReasonCodes,
    original_effect_state: execution.verified_effect.effect_state,
    replay_effect_state: replay?.verified_effect?.effect_state || null,
    same_action_ref: actionRef,
    same_receipt_id: authorization.receipt.action_id
  }
}, null, 2));
