#!/usr/bin/env node
// Public cold-agent reference runner for Rail Check 01. It imports only the
// published @voidly/session package and uses pinned public HTTPS endpoints. It
// has no identity, wallet, payment, Bounty, persistence, or write-capable
// dependency. Every network response is time-, size-, status-, and redirect-
// bounded. No request is retried.

import process from "node:process";
import { readFileSync, realpathSync } from "node:fs";
import { fileURLToPath } from "node:url";
import {
  canonicalBytes,
  sha256Hex,
  verifyProvider,
} from "@voidly/session";

export const RAIL_CHECK_TASK_URL = "https://api.voidly.ai/v1/proofs/task";
export const RAIL_CHECK_START_URL = "https://api.voidly.ai/v1/proofs/runs";
export const RAIL_CHECK_VERDICT_URL = "https://api.voidly.ai/v1/proofs/verdict";
export const RAIL_CHECK_INDEX_URL = "https://api.voidly.ai/v1/session/providers";
export const RAIL_CHECK_REQUEST_TIMEOUT_MS = 8_000;
export const RAIL_CHECK_TOTAL_TIMEOUT_MS = 30_000;
export const RAIL_CHECK_MAX_JSON_BYTES = 32 * 1024;

const PROVIDER_DID = "did:voidly:6rGTFa5apSnKNF14bGXZfu";
const WRONG_PROVIDER_DID = "did:voidly:2222222222222222";
const MANIFEST_URL = "https://intelligence.voidly.ai:8443/.well-known/voidly-session-provider.json";
const TASK_ID = "rail-check-01";
const TASK_VERSION = 1;
const ACCEPTANCE_RULE_SHA256 = "9369dae22733e8f14e504ea38cecf3cbe1b7574bd65a520baa8e0f04b167110c";
const TASK_SCHEMA = "voidpay-proof-task/v1";
const RUN_REQUEST_SCHEMA = "voidpay.pay.rail-check.run-request/v1";
const RUN_SCHEMA = "voidpay.pay.rail-check.run/v1";
const SUBMISSION_SCHEMA = "voidpay.pay.rail-check.submission/v1";
const VERDICT_SCHEMA = "voidpay.pay.rail-check.verdict/v1";
const RESPONSE_SCHEMA = "voidly.pay.rail-check.response/v1";
const HASH64 = /^[0-9a-f]{64}$/;
const RUN_ID = /^[0-9a-f]{32}$/;
const PLAIN = (value) => value !== null && typeof value === "object" && !Array.isArray(value);

function exactKeys(value, expected) {
  return PLAIN(value) &&
    JSON.stringify(Object.keys(value).sort()) === JSON.stringify([...expected].sort());
}

function canonicalJson(value) {
  if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
  if (PLAIN(value)) {
    return `{${Object.keys(value).sort().map((key) =>
      `${JSON.stringify(key)}:${canonicalJson(value[key])}`).join(",")}}`;
  }
  const encoded = JSON.stringify(value);
  if (encoded === undefined) throw new Error("non_json_value");
  return encoded;
}

function exactZeroReward(value) {
  return exactKeys(value, ["amount", "asset", "offered"]) &&
    value.offered === false && value.amount === "0" && value.asset === null;
}

function exactUrl(response, expectedUrl) {
  return response.redirected !== true && (response.url === "" || response.url === expectedUrl);
}

async function readJson(response, what, expectedStatus, expectedUrl) {
  if (!(response instanceof Response)) throw new Error(`${what}_response_unusable`);
  if (response.status !== expectedStatus) throw new Error(`${what}_http_${response.status}`);
  if (!exactUrl(response, expectedUrl)) throw new Error(`${what}_redirect_refused`);
  const contentType = response.headers.get("content-type")?.split(";", 1)[0].trim().toLowerCase();
  if (contentType !== "application/json") throw new Error(`${what}_content_type_unusable`);
  const declared = response.headers.get("content-length");
  if (declared !== null && (!/^\d+$/.test(declared) || Number(declared) > RAIL_CHECK_MAX_JSON_BYTES)) {
    throw new Error(`${what}_too_large`);
  }
  const reader = response.body?.getReader();
  if (!reader) throw new Error(`${what}_body_missing`);
  const chunks = [];
  let size = 0;
  try {
    for (;;) {
      const part = await reader.read();
      if (part.done) break;
      size += part.value.byteLength;
      if (size > RAIL_CHECK_MAX_JSON_BYTES) {
        await reader.cancel();
        throw new Error(`${what}_too_large`);
      }
      chunks.push(part.value);
    }
  } catch (error) {
    try { await reader.cancel(); } catch { /* best effort */ }
    throw error;
  }
  const bytes = new Uint8Array(size);
  let offset = 0;
  for (const chunk of chunks) {
    bytes.set(chunk, offset);
    offset += chunk.byteLength;
  }
  let parsed;
  try {
    parsed = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
  } catch {
    throw new Error(`${what}_json_unusable`);
  }
  if (!PLAIN(parsed)) throw new Error(`${what}_not_object`);
  return parsed;
}

function boundedFetch(fetchImpl, totalSignal) {
  return (input, init = {}) => {
    const signals = [totalSignal, AbortSignal.timeout(RAIL_CHECK_REQUEST_TIMEOUT_MS)];
    if (init.signal) signals.push(init.signal);
    return fetchImpl(input, {
      ...init,
      redirect: "error",
      signal: AbortSignal.any(signals),
    });
  };
}

const postJson = (fetchImpl, url, body) => fetchImpl(url, {
  method: "POST",
  headers: { accept: "application/json", "content-type": "application/json" },
  body: JSON.stringify(body),
});

function taskContractIsPinned(task) {
  const responseRule = task.acceptance_rule?.challenge_response;
  const template = responseRule?.preimage;
  return exactKeys(task, [
    "acceptance_rule", "acceptance_rule_sha256", "agent_requirements", "allowed_actions",
    "counted", "forbidden_actions", "identity_registration_allowed", "instruction", "limits",
    "mode", "payment_action_allowed", "provider", "public_submission_stored", "reference_runner",
    "reward", "run_request", "schema", "start_endpoint", "status", "task_id", "task_url", "title",
    "verdict_endpoint", "verdict_submission", "version", "verifier", "wallet_required",
  ]) &&
    task.schema === TASK_SCHEMA &&
    task.task_id === TASK_ID &&
    task.version === TASK_VERSION &&
    task.status === "active" &&
    task.mode === "zero_value" &&
    task.counted === false &&
    exactZeroReward(task.reward) &&
    task.wallet_required === false &&
    task.payment_action_allowed === false &&
    task.identity_registration_allowed === false &&
    task.public_submission_stored === false &&
    exactKeys(task.provider, ["index_url", "manifest_url", "provider_did"]) &&
    task.provider.provider_did === PROVIDER_DID &&
    task.provider.manifest_url === MANIFEST_URL &&
    task.provider.index_url === RAIL_CHECK_INDEX_URL &&
    exactKeys(task.verifier, ["package", "version"]) &&
    task.verifier.package === "@voidly/session" &&
    task.verifier.version === "1.2.2" &&
    task.task_url === RAIL_CHECK_TASK_URL &&
    task.start_endpoint === RAIL_CHECK_START_URL &&
    task.verdict_endpoint === RAIL_CHECK_VERDICT_URL &&
    exactKeys(task.run_request, ["body", "schema"]) &&
    task.run_request.schema === RUN_REQUEST_SCHEMA &&
    exactKeys(task.run_request.body, ["schema", "task_id", "task_version"]) &&
    task.run_request.body.schema === RUN_REQUEST_SCHEMA &&
    task.run_request.body.task_id === TASK_ID &&
    task.run_request.body.task_version === TASK_VERSION &&
    exactKeys(task.verdict_submission, ["body", "schema"]) &&
    task.verdict_submission.schema === SUBMISSION_SCHEMA &&
    exactKeys(task.verdict_submission.body, [
      "challenge_response_sha256", "manifest_digest_sha256", "manifest_url", "provider_did",
      "run_token", "schema",
    ]) &&
    task.verdict_submission.body.schema === SUBMISSION_SCHEMA &&
    task.verdict_submission.body.provider_did === PROVIDER_DID &&
    task.verdict_submission.body.manifest_url === MANIFEST_URL &&
    Array.isArray(task.agent_requirements) && task.agent_requirements.length >= 4 &&
    exactKeys(task.reference_runner, ["install", "instructions_url", "runtime", "sha256", "url"]) &&
    task.reference_runner.url === "https://voidly.ai/pay/proofs/rail-check-agent.mjs" &&
    task.reference_runner.instructions_url === "https://voidly.ai/pay/proofs/README.md" &&
    task.reference_runner.runtime === "Node.js >=20.3" &&
    task.reference_runner.install === "npm install --ignore-scripts --save-exact @voidly/session@1.2.2" &&
    HASH64.test(String(task.reference_runner.sha256 ?? "")) &&
    responseRule?.formula === "lowercase-hex SHA-256 over the verifier package's canonical byte encoding of preimage" &&
    template?.schema === RESPONSE_SCHEMA &&
    template?.task_id === TASK_ID &&
    template?.task_version === TASK_VERSION &&
    template?.provider_did === PROVIDER_DID &&
    template?.manifest_url === MANIFEST_URL;
}

function runContractIsPinned(run, task) {
  const issuedAt = Date.parse(run.issued_at);
  const expiresAt = Date.parse(run.expires_at);
  return exactKeys(run, [
    "acceptance_rule_sha256", "challenge", "counted", "expires_at", "issued_at", "ok",
    "payment_action_allowed", "persistence", "reward", "run_id", "run_token", "schema",
    "submit_to", "task_id", "task_version", "wallet_required",
  ]) &&
    run.schema === RUN_SCHEMA && run.ok === true &&
    run.task_id === TASK_ID && run.task_version === TASK_VERSION &&
    run.acceptance_rule_sha256 === task.acceptance_rule_sha256 &&
    RUN_ID.test(String(run.run_id ?? "")) &&
    typeof run.run_token === "string" && run.run_token.length >= 16 && run.run_token.length <= 4096 &&
    HASH64.test(String(run.challenge ?? "")) &&
    Number.isFinite(issuedAt) && Number.isFinite(expiresAt) && expiresAt - issuedAt === 10 * 60 * 1000 &&
    run.submit_to === RAIL_CHECK_VERDICT_URL &&
    run.counted === false && exactZeroReward(run.reward) &&
    run.wallet_required === false && run.payment_action_allowed === false &&
    run.persistence === "none; the run token is stateless and replayable until expiry";
}

function canonicalIso(value) {
  if (typeof value !== "string") return false;
  const parsed = Date.parse(value);
  return Number.isFinite(parsed) && new Date(parsed).toISOString() === value;
}

function verdictContractIsPinned(verdict, task, run, manifestDigestSha256) {
  const outcomeIsCoherent =
    (verdict.outcome === "PASS" && verdict.ok === true) ||
    ((verdict.outcome === "FAIL" || verdict.outcome === "INCONCLUSIVE") && verdict.ok === false);
  const passChecksAreComplete = verdict.outcome !== "PASS" || (
    exactKeys(verdict.server_checks, [
      "manifest_verified", "provider_pair_listed", "run_unexpired", "token_authentic", "wrong_pin_refused",
    ]) && Object.values(verdict.server_checks).every((value) => value === true) &&
    exactKeys(verdict.claimant_checks, ["challenge_response_matches", "manifest_digest_matches"]) &&
    Object.values(verdict.claimant_checks).every((value) => value === true)
  );
  const checkedAt = Date.parse(verdict.checked_at);
  const issuedAt = Date.parse(run.issued_at);
  const expiresAt = Date.parse(run.expires_at);
  const evidenceHasExactShape = exactKeys(verdict.evidence, [
    "infrastructure_reason", "manifest_digest_sha256", "manifest_url", "provider_did",
    "provider_index_generated_at", "wrong_pin_reason",
  ]);
  const evidenceIsWellFormed = evidenceHasExactShape &&
    verdict.evidence.provider_did === PROVIDER_DID &&
    verdict.evidence.manifest_url === MANIFEST_URL &&
    (verdict.evidence.manifest_digest_sha256 === null ||
      HASH64.test(String(verdict.evidence.manifest_digest_sha256))) &&
    (verdict.evidence.wrong_pin_reason === null ||
      typeof verdict.evidence.wrong_pin_reason === "string") &&
    (verdict.evidence.infrastructure_reason === null ||
      typeof verdict.evidence.infrastructure_reason === "string") &&
    (verdict.evidence.provider_index_generated_at === null ||
      canonicalIso(verdict.evidence.provider_index_generated_at));
  const passEvidenceIsExact = verdict.outcome !== "PASS" || (
    evidenceIsWellFormed &&
    verdict.evidence.manifest_digest_sha256 === manifestDigestSha256 &&
    verdict.evidence.wrong_pin_reason === "manifest_did_not_pinned" &&
    verdict.evidence.infrastructure_reason === null &&
    (verdict.evidence.provider_index_generated_at === null ||
      canonicalIso(verdict.evidence.provider_index_generated_at))
  );
  return exactKeys(verdict, [
    "acceptance_rule_sha256", "application_receipt_persisted", "checked_at", "claimant_checks",
    "commercial_transaction", "counted", "credited_to_traction_metrics", "customer_identity_verified",
    "evidence", "expires_at", "issued_at", "limitations", "ok", "outcome", "payment_boundary",
    "persistence", "public_receipt_url", "related_surface", "reward", "run_id", "schema",
    "server_checks", "task_id", "task_version",
  ]) &&
    verdict.schema === VERDICT_SCHEMA && outcomeIsCoherent && passChecksAreComplete &&
    verdict.task_id === TASK_ID && verdict.task_version === run.task_version &&
    verdict.acceptance_rule_sha256 === task.acceptance_rule_sha256 && verdict.run_id === run.run_id &&
    verdict.issued_at === run.issued_at && verdict.expires_at === run.expires_at &&
    canonicalIso(verdict.checked_at) && checkedAt >= issuedAt && checkedAt <= expiresAt &&
    evidenceIsWellFormed && passEvidenceIsExact &&
    exactKeys(verdict.payment_boundary, [
      "authorization_created", "decision", "settlement_observed", "transaction_broadcast",
    ]) &&
    verdict.payment_boundary.decision === "STOP" &&
    verdict.payment_boundary.authorization_created === false &&
    verdict.payment_boundary.transaction_broadcast === false &&
    verdict.payment_boundary.settlement_observed === false &&
    verdict.counted === false && exactZeroReward(verdict.reward) &&
    verdict.application_receipt_persisted === false && verdict.public_receipt_url === null &&
    verdict.customer_identity_verified === false && verdict.commercial_transaction === false &&
    verdict.credited_to_traction_metrics === false &&
    verdict.persistence === "No run, submission, or receipt row is written. Requests still traverse Cloudflare and ordinary edge logs may contain network metadata." &&
    exactKeys(verdict.related_surface, ["bounty_board_url", "note"]) &&
    verdict.related_surface.bounty_board_url === "https://api.voidly.ai/v1/bounty/board" &&
    verdict.related_surface.note === "Bounties are a separate system and do not affect this verdict." &&
    canonicalJson(verdict.limitations) === canonicalJson(task.limits);
}

export async function completeRailCheck({
  fetchImpl = fetch,
  taskUrl = RAIL_CHECK_TASK_URL,
  expectedTask,
} = {}) {
  if (typeof AbortSignal.any !== "function") throw new Error("node_20_3_or_newer_required");
  if (taskUrl !== RAIL_CHECK_TASK_URL) throw new Error("task_url_not_pinned");
  const request = boundedFetch(fetchImpl, AbortSignal.timeout(RAIL_CHECK_TOTAL_TIMEOUT_MS));
  const task = await readJson(await request(taskUrl, {
    method: "GET",
    headers: { accept: "application/json" },
  }), "task", 200, taskUrl);
  if (task.status !== "active") {
    return { ok: false, outcome: "task_withheld", status: task.status ?? null };
  }
  if (expectedTask !== undefined && (
    !PLAIN(expectedTask) ||
    expectedTask.status !== "active" ||
    canonicalJson(task) !== canonicalJson(expectedTask)
  )) {
    throw new Error("task_source_mismatch");
  }
  if (!taskContractIsPinned(task)) throw new Error("task_contract_not_pinned");
  // The canonical API cannot silently select different client bytes or a new
  // acceptance rule while still calling this task version 1.
  const executingRunnerSha256 = await sha256Hex(readFileSync(fileURLToPath(import.meta.url)));
  if (task.reference_runner.sha256 !== executingRunnerSha256) {
    throw new Error("runner_checksum_mismatch");
  }
  if (
    task.acceptance_rule_sha256 !== ACCEPTANCE_RULE_SHA256 ||
    await sha256Hex(canonicalBytes(task.acceptance_rule)) !== task.acceptance_rule_sha256
  ) {
    throw new Error("acceptance_rule_hash_mismatch");
  }

  const run = await readJson(
    await postJson(request, RAIL_CHECK_START_URL, task.run_request.body),
    "run",
    201,
    RAIL_CHECK_START_URL,
  );
  if (!runContractIsPinned(run, task)) throw new Error("run_contract_not_pinned");

  const index = await readJson(await request(RAIL_CHECK_INDEX_URL, {
    method: "GET",
    headers: { accept: "application/json" },
  }), "index", 200, RAIL_CHECK_INDEX_URL);
  if (
    !Array.isArray(index.providers) ||
    !index.providers.some((entry) =>
      PLAIN(entry) && entry.provider_did === PROVIDER_DID && entry.manifest_url === MANIFEST_URL)
  ) {
    throw new Error("pinned_provider_pair_not_listed");
  }

  const manifest = await readJson(await request(MANIFEST_URL, {
    method: "GET",
    headers: { accept: "application/json" },
  }), "manifest", 200, MANIFEST_URL);
  const found = verifyProvider(manifest, PROVIDER_DID);
  if (!found.ok) throw new Error(`manifest_${found.reason}`);
  const wrongPin = verifyProvider(found.provider.manifest, WRONG_PROVIDER_DID);
  if (wrongPin.ok || wrongPin.reason !== "manifest_did_not_pinned") {
    throw new Error("wrong_pin_not_refused");
  }
  const manifestDigestSha256 = await sha256Hex(canonicalBytes(found.provider.manifest));
  const preimage = {
    ...task.acceptance_rule.challenge_response.preimage,
    challenge: run.challenge,
    manifest_digest_sha256: manifestDigestSha256,
  };
  const challengeResponseSha256 = await sha256Hex(canonicalBytes(preimage));
  const submission = {
    ...task.verdict_submission.body,
    run_token: run.run_token,
    manifest_digest_sha256: manifestDigestSha256,
    challenge_response_sha256: challengeResponseSha256,
  };
  const verdict = await readJson(
    await postJson(request, RAIL_CHECK_VERDICT_URL, submission),
    "verdict",
    200,
    RAIL_CHECK_VERDICT_URL,
  );
  if (!verdictContractIsPinned(verdict, task, run, manifestDigestSha256)) {
    throw new Error("verdict_contract_not_pinned");
  }
  return verdict;
}

export function railCheckProcessExitCode(result) {
  if (result?.outcome === "task_withheld") return 2;
  return result?.outcome === "PASS" && result?.ok === true ? 0 : 3;
}

export const invokedAsMain = (argv1, metaUrl) => {
  try {
    return typeof argv1 === "string" && realpathSync(argv1) === realpathSync(fileURLToPath(metaUrl));
  } catch {
    return false;
  }
};

export async function runRailCheckCli() {
  if (process.argv.length !== 2) {
    console.error("REFUSED  arguments_not_supported — Rail Check uses the one pinned public task URL");
    return 1;
  }
  try {
    const result = await completeRailCheck();
    if (result.outcome === "task_withheld") {
      console.error(`WITHHELD ${String(result.status).replace(/[^a-z_]/g, "_")}`);
      return 2;
    }
    console.log(JSON.stringify(result, null, 2));
    if (railCheckProcessExitCode(result) !== 0) {
      console.error(`NOT PASSED  ${String(result.outcome).replace(/[^A-Z_]/g, "_")}`);
      return 3;
    }
    return 0;
  } catch (error) {
    const code = /^[a-z0-9_]{1,96}$/.test(String(error?.message ?? ""))
      ? error.message
      : "rail_check_failed";
    console.error(`REFUSED  ${code}`);
    return 1;
  }
}

if (invokedAsMain(process.argv[1], import.meta.url)) {
  process.exitCode = await runRailCheckCli();
}
