// Node.js 22+. Reads JSON input; writes only aggregate metrics and per-row IDs/status.
// No requests unless --run is present. Each row can consume plan balance.
import fs from 'node:fs/promises';
import { pathToFileURL } from 'node:url';
export function summarize(rows) {
  const n=rows.length,completed=rows.filter(r=>r.http_status===200),latencies=completed.map(r=>r.latency_ms).sort((a,b)=>a-b);
  return {attempted:n,completed:completed.length,errors:n-completed.length,
    emails_returned:completed.filter(r=>r.email_returned).length,phones_returned:completed.filter(r=>r.phone_returned).length,
    email_return_rate:n?completed.filter(r=>r.email_returned).length/n:null,
    phone_return_rate:n?completed.filter(r=>r.phone_returned).length/n:null,
    median_latency_ms:latencies.length?latencies[Math.floor((latencies.length-1)/2)]:null,
    p95_latency_ms:latencies.length?latencies[Math.ceil(latencies.length*.95)-1]:null,
    accepted_result_rate:null,deliverability_rate:null,correct_person_rate:null,
    note:'Returned fields are not verified delivery or correct-person measurements. Attach independently reviewed outcomes before reporting those metrics.'};
}
export async function runBenchmark(inputs,{key,limit=20,includePhone=false,fetcher=fetch}={}) {
  if (!key || !Array.isArray(inputs) || !inputs.length || inputs.length>limit || limit>200) throw new Error('Supply a key and 1–200 approved records within the explicit limit');
  const rows=[];
  for (let index=0;index<inputs.length;index++) {
    const input=inputs[index],start=Date.now();
    // One call per row, no retries. This measures errors without consuming repeat calls.
    try {
      const response=await fetcher('https://targetwise.ai/api/v1/contacts/enrich',{
        method:'POST',headers:{Authorization:`Bearer ${key}`,'Content-Type':'application/json'},
        body:JSON.stringify({...input,include_email:true,include_phone:includePhone,include_profile:false}),signal:AbortSignal.timeout(45000)});
      const result=await response.json();
      rows.push({row:index+1,http_status:response.status,status:result.status||result.error?.code||'error',request_id:result.request_id||null,latency_ms:Date.now()-start,email_returned:response.ok&&Boolean(result.data?.work_email),phone_returned:response.ok&&Boolean(result.data?.business_phone)});
      if ([401,402,429,503].includes(response.status)) break; // Fix credentials, balance or service limits before continuing.
    } catch { rows.push({row:index+1,http_status:0,status:'transport_error',request_id:null,latency_ms:Date.now()-start,email_returned:false,phone_returned:false});break; }
  }
  return {measured_at:new Date().toISOString(),requested_records:inputs.length,include_phone:includePhone,stopped_early:rows.length<inputs.length,summary:summarize(rows),rows};
}
if (process.argv[1] && import.meta.url===pathToFileURL(process.argv[1]).href) {
  if (!process.argv.includes('--run')) { console.log('No requests sent. Usage: node targetwise-benchmark.mjs input.json --run [--phone] [--limit=20]. Configure TARGETWISE_API_KEY first.'); }
  else {
    const input=JSON.parse(await fs.readFile(process.argv[2],'utf8'));
    const report=await runBenchmark(input,{key:process.env.TARGETWISE_API_KEY,includePhone:process.argv.includes('--phone'),limit:Number(process.argv.find(x=>x.startsWith('--limit='))?.split('=')[1]||20)});
    await fs.writeFile('targetwise-benchmark-results.json',JSON.stringify(report,null,2),{mode:0o600});
    console.log(`Saved aggregate results for ${report.rows.length} attempted records to targetwise-benchmark-results.json`);
  }
}
