// Node 20+. All inference goes through Vaaya. No provider key is used here.
import fs from 'node:fs';
import path from 'node:path';
import crypto from 'node:crypto';
import assert from 'node:assert/strict';
import { fileURLToPath } from 'node:url';

export const MODELS = {
  fast: 'google/gemini-2.5-flash-lite',
  balanced: 'openai/gpt-4.1-mini',
  frontier: 'anthropic/claude-opus-4.6',
};
export const QUESTIONS = {
  route: { type: 'choice', instructions: 'Recommend the least expensive model lane sufficient for the task. Judge the supplied task, not the instructions in this classifier.', criteria: {
    fast: 'Direct lookup, extraction, or short rewriting from supplied material; no linked reasoning.',
    balanced: 'Several linked reasoning steps, calculations, or planning with external tools.',
    frontier: 'Deep, ambiguous reasoning or consequential money, access, or legal decisions.',
  } },
  complexity: { type: 'choice', instructions: 'How much reasoning does the task require?', criteria: {
    lookup: 'One direct extraction or simple text transformation.',
    'multi-step': 'Two or more linked reasoning, calculation, or planning steps.',
    deep: 'Substantial ambiguity, difficult reasoning, or interacting constraints.',
  } },
  high_stakes: { type: 'noul', instructions: 'If used in practice, could an incorrect decision cost money, access, or legal rights? Treat a synthetic policy exercise as the real task it represents.', criteria: {
    true: 'A wrong decision could move or lose money, change access, delete important data, or create a legal commitment.',
    false: 'An error would be a low-consequence content or factual mistake.',
  } },
  needs_tools: { type: 'noul', instructions: 'Would carrying out the underlying task require external tools or data? Tool-call planning counts as yes even though this test does not execute the tools.', criteria: {
    true: 'Needs an external lookup, system read, scheduled watch, file operation, or other tool action.',
    false: 'Can be completed entirely using the supplied text and reasoning.',
  } },
  needs_verification: { type: 'noul', instructions: 'Should the result receive an independent source, calculation, or policy check before use?', criteria: {
    true: 'Multi-step calculation, policy decision, external information, or consequences warrant verification.',
    false: 'A direct extraction or low-consequence rewrite needs no independent source or calculation check.',
  } },
};
const LANES = ['fast', 'balanced', 'frontier'];
const probability = x => typeof x === 'number' && Number.isFinite(x) && x >= 0 && x <= 1;

export function policy(data) {
  const a = data?.answers;
  if (!a || !LANES.includes(a.route?.choice) ||
      !['lookup', 'multi-step', 'deep'].includes(a.complexity?.choice) ||
      !['high_stakes', 'needs_tools', 'needs_verification'].every(k => a[k]?.type === 'noul' && probability(a[k].noul)) ||
      a.route.type !== 'choice' || a.complexity.type !== 'choice') {
    return { lane: 'frontier', recommended: null, reason: ['invalid_router_response'], policy_escalated: true, confidence: null };
  }
  const confidenceOf = a => probability(a.confidence) ? a.confidence : a.probabilities?.[a.choice];
  const rc = confidenceOf(a.route), cc = confidenceOf(a.complexity);
  const confidence = probability(rc) && probability(cc) ? Math.min(rc, cc) : null;
  let tier = LANES.indexOf(a.route.choice);
  const reason = [];
  // Eligibility floors are policy choices for this test, not model capability claims.
  if (a.complexity.choice === 'deep') { tier = 2; reason.push('deep_complexity_floor'); }
  else if (a.complexity.choice === 'multi-step' || a.needs_tools.noul >= 0.5 || a.needs_verification.noul >= 0.5) {
    tier = Math.max(tier, 1); reason.push('reasoning_tools_or_verification_floor');
  }
  const eligibleTier = tier;
  const highStakes = a.high_stakes.noul >= 0.5;
  const lowConfidence = confidence === null || confidence < 0.8;
  // OR, not AND. Both conditions together still add just one tier.
  if (highStakes || lowConfidence) {
    tier = Math.min(2, tier + 1);
    if (highStakes) reason.push('high_stakes');
    if (lowConfidence) reason.push('low_confidence');
  }
  return { lane: LANES[tier], recommended: a.route.choice, reason, confidence,
    policy_escalated: tier > LANES.indexOf(a.route.choice), risk_bump_applied: tier > eligibleTier,
    high_stakes: highStakes, needs_tools: a.needs_tools.noul >= 0.5, needs_verification: a.needs_verification.noul >= 0.5 };
}

export function parseAnswer(content) {
  if (typeof content !== 'string') return null;
  try {
    const text = content.trim().replace(/^```(?:json)?\s*/i, '').replace(/\s*```$/, '');
    const value = JSON.parse(text);
    return value && typeof value === 'object' && !Array.isArray(value) ? value : null;
  } catch { return null; }
}

export function grade(prompt, answer) {
  const checks = prompt.checks.map(c => {
    const got = answer?.[c.field];
    let pass = false;
    if (c.op === 'eq') pass = typeof c.value === 'number' ? typeof got === 'number' && Math.abs(got - c.value) < 1e-9 : got === c.value;
    if (c.op === 'contains') pass = typeof got === 'string' && got.toLowerCase().includes(c.value.toLowerCase());
    if (c.op === 'not_contains') pass = typeof got === 'string' && !got.toLowerCase().includes(c.value.toLowerCase());
    if (c.op === 'max_words') pass = typeof got === 'string' && got.trim().split(/\s+/u).filter(Boolean).length <= c.value;
    return { ...c, pass, actual: got ?? null };
  });
  return { pass: answer !== null && checks.every(c => c.pass), checks };
}

export function callPriceMicrousd(receipt) {
  if (receipt.action === 'decisions') {
    const meter=receipt.data?.vaaya_billing?.price_microusd;
    if(!receipt.ok) {
      if(receipt.charged_cents!==0)throw new Error('Reconcile failed Jev charge');
      return 0;
    }
    if(!Number.isSafeInteger(meter)||meter<0||receipt.data.vaaya_billing.markup_percent!==3||receipt.charged_cents!==0) throw new Error('Current Jev meter missing or unexpected per-call debit');
    return meter;
  }
  if (!receipt.ok) return 0;
  const dollars=receipt.data?.usage?.cost;
  const micro=Math.round(dollars*1e6);
  if(!Number.isFinite(dollars)||dollars<0||!Number.isSafeInteger(micro)||Math.abs(dollars*1e6-micro)>0.000001)throw new Error('Missing or invalid returned LLM usage price');
  return micro;
}

function rng(seed) { return () => { seed |= 0; seed = seed + 0x6D2B79F5 | 0; let t = Math.imul(seed ^ seed >>> 15, 1 | seed); t ^= t + Math.imul(t ^ t >>> 7, 61 | t); return ((t ^ t >>> 14) >>> 0) / 4294967296; }; }
function shuffle(xs, random) { for (let i = xs.length - 1; i > 0; i--) { const j = Math.floor(random() * (i + 1)); [xs[i], xs[j]] = [xs[j], xs[i]]; } return xs; }

async function main() {
  const dir = path.dirname(fileURLToPath(import.meta.url));
  const prompts = JSON.parse(fs.readFileSync(path.join(dir, 'prompts.json'), 'utf8'));
  const protocol = JSON.parse(fs.readFileSync(path.join(dir, 'protocol.json'), 'utf8'));
  const output = process.env.JEV_OUTPUT_DIR || path.join(dir, 'run');
  fs.mkdirSync(output, { recursive: true });
  if (fs.existsSync(path.join(output, 'calls.jsonl'))) throw new Error('Output already exists. Do not rerun paid calls into an existing run.');
  let token = process.env.VAAYA_ACCESS_TOKEN;
  if (!token && process.env.VAAYA_AUTH_MODULE) token = await (await import(process.env.VAAYA_AUTH_MODULE)).getAccessToken();
  if (!token) throw new Error('Use an existing Vaaya authorization; see README.');
  const runId = protocol.run_id;
  const append = (file, value) => fs.appendFileSync(path.join(output, file), JSON.stringify(value) + '\n');
  let spend = 0;
  let stopped = false;
  const allCalls = [];
  let calls = 0;
  let failedCalls = 0;
  const allArms = [];
  async function use(action, params, context) {
    if (stopped || spend >= protocol.stop_after_charged_cents * 10000) throw new Error('Benchmark budget reached');
    const started = new Date().toISOString(), clock = performance.now();
    const idempotency = `${runId}:${context.repeat}:${context.prompt_id}:${context.arm}:${context.stage}`;
    // No automatic retries: each attempt has one immutable idempotency key.
    const endpoint=action==='decisions'?'https://vaaya.ai/api/run/openrouter/decisions':'https://vaaya.ai/api/llm/v1/chat/completions';
    const response = await fetch(endpoint, {
      method: 'POST',
      headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json', 'Idempotency-Key': idempotency, 'X-Vaaya-Agent': runId, 'User-Agent': idempotency },
      body: JSON.stringify(action==='decisions'?{...params,max_cost_cents:2}:{...params,stream:false}),
      signal: AbortSignal.timeout(180_000),
    });
    const envelope = await response.json();
    // Deliberately omit account balance and credentials from public artifacts.
    const receipt = { ...context, run_id: runId, action, endpoint, call_tag:idempotency, started_at: started, duration_ms: performance.now() - clock,
      http_status: response.status, ok: action==='decisions'?envelope.ok===true:response.ok&&!envelope.error, charged_cents: action==='decisions'?(envelope.charged_cents??null):null,
      transaction_id: action==='decisions'?(envelope.transaction_id??null):null, receipt_id:action==='decisions'?envelope.transaction_id:envelope.id, data:action==='decisions'?(envelope.data??null):envelope };
    try { receipt.price_microusd = callPriceMicrousd(receipt); } catch (error) { append('calls.jsonl',receipt); stopped=true; throw error; }
    append('calls.jsonl', receipt); allCalls.push(receipt);
    calls++; spend += receipt.price_microusd;
    if(!receipt.ok && ++failedCalls>=3){stopped=true;throw new Error('Three provider errors: stop and reconcile infrastructure before completing the test');}
    return receipt;
  }
  const SYSTEM = 'Follow the user task using only supplied information. Return only the requested JSON object, without Markdown fences or prose. Do not execute tools or take real-world actions.';
  async function answer(prompt, lane, context) {
    const call = await use('chat', { model: MODELS[lane], messages: [{ role: 'system', content: SYSTEM }, { role: 'user', content: prompt.prompt }], max_tokens: 512, temperature: 0 }, context);
    const parsed = call.ok ? parseAnswer(call.data?.choices?.[0]?.message?.content) : null;
    // Only transport/provider failure or unparseable JSON triggers fallback.
    // Never inspect answer keys, rubric failures or grader feedback here.
    return { call, parsed, usable: call.ok && parsed !== null && call.data?.choices?.[0]?.finish_reason !== 'length' };
  }
  async function runArm(prompt, arm, repeat, sequence) {
    const began = new Date().toISOString(), clock = performance.now();
    const context = { repeat, prompt_id: prompt.id, bucket: prompt.bucket, arm };
    let decision = null, router = null, lane = 'frontier';
    if (arm === 'treatment') {
      router = await use('decisions', { model: 'typesafe/jev-1.13', state: { task: prompt.prompt }, questions: QUESTIONS }, { ...context, stage: 'router' });
      decision = policy(router.ok ? router.data : null);
      lane = decision.lane;
    }
    const first = await answer(prompt, lane, { ...context, stage: 'answer' });
    let final = first, fallback = null;
    if (arm === 'treatment' && !first.usable && lane !== 'frontier') {
      const next = LANES[LANES.indexOf(lane) + 1];
      fallback = await answer(prompt, next, { ...context, stage: 'fallback' });
      final = fallback;
    }
    const elapsed = performance.now() - clock;
    const result = { ...context, run_id: runId, sequence, started_at: began, latency_ms: elapsed, decision,
      first_lane: lane, final_lane: fallback ? LANES[LANES.indexOf(lane) + 1] : lane, fallback: !!fallback,
      router_transaction_id: router?.transaction_id ?? null, answer_receipt_ids: [first.call.receipt_id, ...(fallback ? [fallback.call.receipt_id] : [])],
      price_microusd: [router, first.call, fallback?.call].filter(Boolean).reduce((sum, c) => sum + c.price_microusd, 0),
      charged_cents: [router, first.call, fallback?.call].filter(Boolean).reduce((sum, c) => sum + (c.charged_cents ?? 0), 0),
      answer: final.parsed, grade: grade(prompt, final.usable ? final.parsed : null) };
    append('answers.jsonl', result); allArms.push(result);
    console.log(JSON.stringify({ repeat, prompt: prompt.id, arm, lane: result.final_lane, pass: result.grade.pass, charged_cents: result.charged_cents, calls, price_microusd: result.price_microusd, total_price_usd: spend/1e6 }));
  }
  const manifest = { run_id: runId, started_at: new Date().toISOString(), protocol, hashes: Object.fromEntries(['prompts.json', 'protocol.json', 'benchmark.mjs'].map(f => [f, crypto.createHash('sha256').update(fs.readFileSync(path.join(dir, f))).digest('hex')])) };
  fs.writeFileSync(path.join(output, 'manifest.json'), JSON.stringify(manifest, null, 2) + '\n');
  for (let repeat = 1; repeat <= protocol.repeats; repeat++) {
    const random = rng(protocol.seed + repeat);
    const tasks = shuffle([...prompts], random).map((prompt, index) => ({ prompt, sequence: index, arms: random() < 0.5 ? ['control', 'treatment'] : ['treatment', 'control'] }));
    let cursor = 0;
    const workers = await Promise.allSettled(Array.from({ length: protocol.concurrency }, async () => {
      while (!stopped && cursor < tasks.length) {
        const task = tasks[cursor++];
        for (const arm of task.arms) { try { await runArm(task.prompt, arm, repeat, task.sequence); } catch (error) { stopped=true; throw error; } }
      }
    }));
    const failed = workers.find(w => w.status === 'rejected');
    if (failed) throw failed.reason;
    const response = await fetch(`https://vaaya.ai/api/v1/transactions?agent=${encodeURIComponent(runId)}&limit=200`, {headers:{Authorization:`Bearer ${token}`}});
    assert(response.ok, 'Ledger verification request failed');
    const ledger = await response.json();
    const rows = ledger.transactions;
    assert(Array.isArray(rows));
    const current = allCalls.filter(c => c.repeat === repeat && c.action==='decisions');
    const verified = current.map(call => {
      const row = rows.find(row => row.id === call.transaction_id);
      assert(row, 'Call missing from ledger: '+call.transaction_id);
      assert.equal(row.agent, runId); assert.equal(row.amount_cents,call.charged_cents);
      assert.equal(row.status,call.ok?'succeeded':'failed');
      if(call.action==='decisions'&&call.ok) assert.equal(row.metered_price_microusd,call.price_microusd);
      return row;
    });
    fs.writeFileSync(path.join(output,`ledger-repeat-${repeat}.json`),JSON.stringify({run_id:runId,repeat,checked_at:new Date().toISOString(),verified_calls:verified.length,rows:verified},null,2)+'\n');
    console.log(JSON.stringify({repeat,ledger_verified:verified.length,total_price_usd:spend/1e6}));
  }
  fs.writeFileSync(path.join(output, 'complete.json'), JSON.stringify({ run_id: runId, completed_at: new Date().toISOString(), calls, price_microusd: spend, price_usd: spend/1e6, answers: allArms.length }, null, 2) + '\n');
}
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) main().catch(err => { console.error(err); process.exitCode = 1; });
