import { randomUUID } from 'node:crypto'
const recovering=process.argv.includes('--status')
if(recovering&&!process.env.JEV_REQUEST_ID)throw new Error('Set the original JEV_REQUEST_ID for status recovery.')
const requestId=process.env.JEV_REQUEST_ID || randomUUID()
// Node.js 22+. Set JEV_API_KEY, then: node starter.mjs
// Recover without inference: JEV_REQUEST_ID=<original-id> node starter.mjs --status
// Optional: JEV_INDUSTRY, JEV_SCENARIO, JEV_MESSAGE. No dependencies or retries.
const base = 'https://nsr.stateset.com'
async function request(path, body, key) {
  let response
  try {
    response = await fetch(base + path, {
      method: body ? 'POST' : 'GET', signal: AbortSignal.timeout(35000),
      headers: { Accept: 'application/json', ...(key ? { 'Content-Type': 'application/json', 'X-Jev-Api-Key': key, 'Idempotency-Key': requestId } : {}) },
      ...(body ? { body: JSON.stringify(body) } : {}),
    })
  } catch { throw new Error('Network error. Outcome unknown; do not retry automatically.') }
  const payload = await response.json()
  if (!response.ok) {
    const error = payload.error || {}
    const delay = response.status === 429 ? ` Wait ${response.headers.get('Retry-After') || 60} seconds.` : ''
    throw new Error(`${error.code || response.status}: ${error.message || 'Request failed'}. ${error.next_action || 'Do not retry automatically.'}${delay}`)
  }
  return payload
}
try {
  if(recovering){
    const key=process.env.JEV_API_KEY?.trim()
    if(!key)throw new Error('Set JEV_API_KEY to the same key used for the original request.')
    const record=await request('/api/jev/requests/'+encodeURIComponent(requestId),undefined,key)
    console.log(JSON.stringify(record,null,2))
    if(record.state!=='completed')process.exitCode=2
  } else {
  const catalog = await request('/api/jev/catalog')
  if (!catalog.live_available) throw new Error('Live demo unavailable. Explore /jev/example.json instead.')
  const industry = process.env.JEV_INDUSTRY || 'retail'
  const pack = catalog.packs.find(p => p.industry === industry)
  if (!pack) throw new Error('Unknown industry. Choose one from /api/jev/catalog.')
  const scenario = process.env.JEV_SCENARIO || pack.scenarios[0].id
  if (!pack.scenarios.some(s => s.id === scenario)) throw new Error('Scenario does not belong to this industry.')
  const key = process.env.JEV_API_KEY?.trim()
  if (!key) throw new Error('Set JEV_API_KEY to a direct TypeSafe key. Never put it in the message.')
  console.error(`Request ID: ${requestId}. Recover with GET /api/jev/requests/${requestId} and the same Jev key; no new inference.`)
  const envelope = await request('/api/jev/decisions', { industry, scenario, ...(process.env.JEV_MESSAGE !== undefined ? { message: process.env.JEV_MESSAGE } : {}) }, key)
  console.log(JSON.stringify(envelope, null, 2))
  if (!envelope.result) throw new Error('Original request pending or unknown. Check its status before another inference.')
  const result = envelope.result
  console.log(`Decision: ${result.decision} (no business action executed)`)
  if (result.routing?.band === 'escalate' || result.evidence?.requires_human_review || result.refusal?.requires_human_review) console.log('Human review required. Do not automate a business action.')
  if (result.decision === 'refused') console.log('Refused is a valid decision. Inspect the reason; the demo evidence cannot be changed.')
  }
} catch (error) { console.error(error.message); process.exitCode = 1 }
