#!/usr/bin/env node
// Standalone Node.js 22+ runner. No dependencies; API keys never enter reports.
import { createHash } from 'node:crypto'
import { readFile, writeFile, mkdir } from 'node:fs/promises'
import { resolve, dirname } from 'node:path'
import { fileURLToPath, pathToFileURL } from 'node:url'
import { performance } from 'node:perf_hooks'
import { setTimeout as delay } from 'node:timers/promises'

export const sha256 = value => createHash('sha256').update(value).digest('hex')
export function summary(rows) {
  const completed = rows.filter(row => row.status === 'completed')
  function stats(key) {
    const values = completed.map(row => row[key]).filter(Number.isFinite).sort((a,b) => a-b)
    if (!values.length) return null
    const middle = Math.floor(values.length / 2)
    return { count: values.length, mean: values.reduce((a,b)=>a+b,0)/values.length,
      median: values.length % 2 ? values[middle] : (values[middle-1]+values[middle])/2,
      min: values[0], max: values.at(-1) }
  }
  return { attempts: rows.length, completed: completed.length, unsuccessful: rows.length-completed.length,
    observedSeconds: stats('observedSeconds'), serverSeconds: stats('serverSeconds') }
}
function epoch(value) {
  if (value === null || value === undefined || value === '') return null
  const n = typeof value === 'number' ? value : Date.parse(value)
  return Number.isFinite(n) ? n : null
}
export async function runOne({project, apiKey, baseUrl='https://api.zvid.io', pollMs=2000, timeoutMs=600000,
  fetchImpl=fetch, wait=delay, now=()=>performance.now(), wall=()=>new Date().toISOString()}) {
  const started = now()
  const row = {startedAt:wall(),status:'unknown',jobId:null,observations:[]}
  const headers = {'Content-Type':'application/json','X-API-Key':apiKey}
  async function request(path, options={}) {
    const remaining = timeoutMs-(now()-started)
    if (remaining<=0) throw new Error('run_timeout')
    const response = await fetchImpl(`${baseUrl}${path}`, { ...options, headers, redirect:'error',
      signal:AbortSignal.timeout(Math.max(1,Math.min(30000,Math.ceil(remaining)))) })
    if (!response.ok) throw new Error(`http_${response.status}`)
    return response.json()
  }
  try {
    // Never retry this POST: a lost response can still have created a billed job.
    const accepted = await request('/api/render/api-key',{method:'POST',body:JSON.stringify({payload:project})})
    if (typeof accepted.jobId!=='string' || !accepted.jobId) throw new Error('missing_job_id')
    row.jobId=accepted.jobId
    row.acceptedAt=wall()
    row.creditsReserved=Number.isFinite(accepted.creditsReserved)?accepted.creditsReserved:null
    while (now()-started < timeoutMs) {
      const job=await request(`/api/jobs/${encodeURIComponent(row.jobId)}`)
      const state=job.state || job.status || 'unknown'
      row.observations.push({at:wall(),elapsedSeconds:(now()-started)/1000,state})
      if (state==='completed' || state==='failed') {
        row.status=state
        row.observedSeconds=(now()-started)/1000
        row.finishedObservedAt=wall()
        const created=epoch(job.ts?.created), finished=epoch(job.ts?.finished)
        row.serverCreatedAt=created===null?null:new Date(created).toISOString()
        row.serverFinishedAt=finished===null?null:new Date(finished).toISOString()
        row.serverSeconds=created!==null && finished!==null && finished>=created?(finished-created)/1000:null
        row.outputUrl=state==='completed'?(typeof job.result==='string'?job.result:job.result?.url) || null:null
        if (state==='completed' && !row.outputUrl) row.status='completed_without_output'
        return row
      }
      await wait(Math.min(pollMs,Math.max(0,timeoutMs-(now()-started))))
    }
    row.status='timeout'
  } catch (error) {
    row.status='error'
    // Never serialize response bodies, auth headers or arbitrary error messages.
    row.errorCode=/^(http_\d{3}|missing_job_id|run_timeout)$/.test(error.message)?error.message:'request_failed'
  }
  row.finishedObservedAt=wall()
  row.observedSeconds=(now()-started)/1000
  return row
}
export function csv(rows) {
  const keys=['run','status','startedAt','acceptedAt','finishedObservedAt','observedSeconds','serverCreatedAt','serverFinishedAt','serverSeconds','jobId','creditsReserved','outputUrl','errorCode']
  const cell=value=>`"${String(value??'').replaceAll('"','""')}"`
  return [keys.join(','),...rows.map(row=>keys.map(key=>cell(row[key])).join(','))].join('\n')+'\n'
}
async function main() {
  const args=process.argv.slice(2)
  const execute=args.includes('--run')
  const outIndex=args.indexOf('--out')
  if (args.includes('--help') || !execute) {
    console.log('Node.js 22+. Set ZVID_API_KEY and BENCHMARK_PLAN (your account plan), then run:\nnode benchmark.mjs --run --out ./my-results\nFive sequential 60-second Full HD renders reserve 300 credits in total. Hobby or above is required.\nWithout --run, no network request or paid render is made. Output directories must be new.')
    return
  }
  if (!process.env.ZVID_API_KEY || !process.env.BENCHMARK_PLAN) throw new Error('Set ZVID_API_KEY and BENCHMARK_PLAN before running.')
  if (outIndex<0 || !args[outIndex+1] || args[outIndex+1].startsWith('--')) throw new Error('Provide --out with a new results directory.')
  const here=dirname(fileURLToPath(import.meta.url))
  const projectBytes=await readFile(resolve(here,'project.json'))
  const assetBytes=await readFile(resolve(here,'assets.json'))
  const checksumLines=(await readFile(resolve(here,'SHA256SUMS.txt'),'utf8')).trim().split(/\r?\n/)
  const checksums=new Map(checksumLines.map(line=>{const [digest,name]=line.split('  ');return [name,digest]}))
  if (sha256(projectBytes)!==checksums.get('project.json') || sha256(assetBytes)!==checksums.get('assets.json')) {
    throw new Error('The project or asset manifest differs from the kit checksums. Download the original files before running this fixed-cost benchmark.')
  }
  const project=JSON.parse(projectBytes)
  const manifest=JSON.parse(assetBytes)
  const media=new Set([...project.visuals.filter(v=>v.type==='VIDEO').map(v=>v.src),...project.audios.map(a=>a.src)])
  console.log('Verifying source media before timing any render...')
  for (const url of media) {
    const asset=manifest.assets.find(asset=>asset.url===url)
    if (!asset || new URL(url).origin!=='https://cdn.zvid.io') throw new Error('Project media is not present in the published manifest.')
    const response=await fetch(url,{redirect:'error',signal:AbortSignal.timeout(120000)})
    if (!response.ok) throw new Error('Source media download failed.')
    const bytes=Buffer.from(await response.arrayBuffer())
    if (bytes.length!==asset.bytes || sha256(bytes)!==asset.sha256) throw new Error('Source media checksum failed.')
  }
  const destination=resolve(args[outIndex+1])
  // Exclusive directory creation protects old measurements from being overwritten.
  await mkdir(destination)
  await writeFile(resolve(destination,'project.json'),projectBytes)
  const report={schemaVersion:1,startedAt:new Date().toISOString(),service:'Zvid',baseUrl:'https://api.zvid.io',
    plan:process.env.BENCHMARK_PLAN,clientRegion:process.env.BENCHMARK_CLIENT_REGION || 'not supplied',
    runtime:process.version,platform:process.platform,arch:process.arch,projectSha256:sha256(projectBytes),
    requestedRuns:5,concurrency:1,pollMs:2000,timeoutMs:600000,warmupRuns:0,
    cachePolicy:'No cache reset or warm-up; media preflight precedes all runs. Cache state and other account activity are uncontrolled.',
    observedMetric:'Monotonic elapsed time from before submission until a terminal status response is received. Includes network, queue and polling delay; excludes output download.',
    serverMetric:'Server finished minus created timestamps, when supplied. Includes queue time; kept separate from observed time.',
    aggregation:'Arithmetic mean, median, minimum and maximum of successful runs; all attempts and failures retained.',
    runs:[]}
  for (let run=1;run<=5;run++) {
    console.log(`Running ${run}/5`)
    const row=await runOne({project,apiKey:process.env.ZVID_API_KEY})
    report.runs.push({run,...row})
    report.summary=summary(report.runs)
    report.updatedAt=new Date().toISOString()
    await writeFile(resolve(destination,'results.json'),JSON.stringify(report,null,2)+'\n')
    await writeFile(resolve(destination,'runs.csv'),csv(report.runs))
    // An unknown submission outcome or polling failure may leave an active job.
    if (['timeout','error'].includes(row.status)) {console.log('Stopped after an uncertain outcome. Inspect the recorded job before retrying.');break}
  }
  console.log(JSON.stringify(report.summary,null,2))
  if (report.runs.length!==5 || report.summary.unsuccessful) process.exitCode=1
}
if (process.argv[1] && import.meta.url===pathToFileURL(resolve(process.argv[1])).href) {
  main().catch(error=>{console.error(error.message);process.exitCode=1})
}
