/** Public-report adapter + offline analysis. Never executes scripts from archived HTML. */
import fs from 'node:fs/promises';
import path from 'node:path';
import {createHash} from 'node:crypto';
import {gzipSync,gunzipSync} from 'node:zlib';
import {pathToFileURL} from 'node:url';
export const hash=x=>createHash('sha256').update(x).digest('hex');
export function decodePublicReport(html) {
  const m=/AF_initDataCallback\(\{key: 'ds:0', hash: '[^']+', data:/.exec(html);
  if(!m) throw Error('Public report payload absent; adapter must be reviewed.');
  const start=m.index+m[0].length;
  let quoted=false,escaped=false,depth=0,end=-1;
  for(let i=start;i<html.length;i++) {const c=html[i];if(quoted){if(escaped)escaped=false;else if(c==='\\')escaped=true;else if(c==='"')quoted=false;continue;}if(c==='"')quoted=true;else if(c==='['||c==='{')depth++;else if(c===']'||c==='}') {depth--;if(depth===0){end=i+1;break;}}}
  if(end<0)throw Error('Incomplete report JSON');
  const data=JSON.parse(html.slice(start,end));
  if(!Array.isArray(data[4]))throw Error('Unexpected public report schema');
  const rows=data[4];
  const laboratory=rows.filter(r=>r[2]===1&&r[3]===1);
  if(laboratory.length!==1)throw Error('Expected exactly one mobile Lighthouse record');
  const lhr=typeof laboratory[0][9]==='string'?JSON.parse(laboratory[0][9]):null;
  if(lhr&&lhr.configSettings?.formFactor!=='mobile')throw Error('Device mapping mismatch');
  const field=rows.find(r=>r[2]===1&&r[3]===3);
  const origin=rows.find(r=>r[2]===1&&r[3]===2);
  function crux(row,scope) {
    if(!row?.[5])return {scope,status:'unavailable',error:row?.[7]||null};
    const raw=row[5]; const key=raw[0]?.[0];
    // 1 means desktop, 2 phone in the embedded CrUX key; never mix with row device IDs.
    if(key?.[2]!==2)throw Error('Expected CrUX PHONE record');
    const date=x=>Array.isArray(x)&&x.length===3?`${x[0]}-${String(x[1]).padStart(2,'0')}-${String(x[2]).padStart(2,'0')}`:null;
    const period={first_date:date(raw[3]?.[0]),last_date:date(raw[3]?.[1])};
    const values={};
    for(const [id] of [['largest_contentful_paint'],['interaction_to_next_paint'],['cumulative_layout_shift']]) {
      const item=raw[1]?.find(x=>x[0]===id);
      const tuple=item?.[1]?.[1]?.[1]?.[0];
      const value=tuple?.[1]??tuple?.[2];
      values[id]=value!==null&&value!==undefined&&value!==''&&Number.isFinite(Number(value))?Number(value):null;
    }
    return {scope,status:'available',key:scope==='url'?key[4]:key[0],form_factor:'PHONE',period,p75:values,raw};
  }
  return {report_id:data[0],requested_url:data[1],lhr,field:crux(field,'url'),origin:crux(origin,'origin')};
}
export function stats(v) {if(!v.length)return null;const s=[...v].sort((a,b)=>a-b),q=p=>{const x=(s.length-1)*p,l=Math.floor(x);return s[l]+(s[Math.ceil(x)]-s[l])*(x-l);};return {n:v.length,median:q(.5),q1:q(.25),q3:q(.75),min:s[0],max:s.at(-1)};}
export function fieldVerdict(field) {
  const p=field?.p75;
  if(field?.status!=='available'||!p||!['largest_contentful_paint','interaction_to_next_paint','cumulative_layout_shift'].every(k=>typeof p[k]==='number'&&Number.isFinite(p[k])&&p[k]>=0))return null;
  return p.largest_contentful_paint<=2500&&p.interaction_to_next_paint<=200&&p.cumulative_layout_shift<=.1;
}
export function wilson(k,n) {if(!n)return null;const z=1.959963984540054,p=k/n,den=1+z*z/n,c=(p+z*z/(2*n))/den,h=z*Math.sqrt(p*(1-p)/n+z*z/(4*n*n))/den;return [Math.max(0,c-h),Math.min(1,c+h)];}
export function analysePage(entry, reports) {
  const reasons=[]; const valid=reports.filter(r=>r.lhr&&!r.lhr.runtimeError&&Number.isFinite(r.lhr.categories?.performance?.score));
  if(reports.length!==5||valid.length!==5)reasons.push('five_valid_runs_required');
  if(new Set(reports.map(r=>r.report_id)).size!==reports.length||new Set(valid.map(r=>r.lhr.fetchTime)).size!==valid.length)reasons.push('duplicate_report');
  if(valid.some(r=>r.requested_url!==entry.url))reasons.push('requested_url_mismatch');
  const signatures=valid.map(({lhr:r})=>JSON.stringify({version:r.lighthouseVersion,browser:r.environment?.hostUserAgent,final:r.finalDisplayedUrl||r.finalUrl,settings:r.configSettings}));
  if(new Set(signatures).size>1)reasons.push('tool_or_configuration_changed');
  const fields=reports.map(r=>r.field);
  if(fields.some(f=>f.scope!=='url'||f.key!==entry.url||fieldVerdict(f)===null||!f.period?.first_date||!f.period?.last_date))reasons.push('complete_url_field_record_required');
  if(new Set(fields.map(f=>JSON.stringify({key:f.key,period:f.period,p75:f.p75}))).size>1)reasons.push('field_record_changed');
  const scores=valid.map(r=>Math.round(r.lhr.categories.performance.score*100));
  return {id:entry.id,url:entry.url,attempts:reports.length,valid_runs:valid.length,scores,performance:stats(scores),
    lcp_ms:stats(valid.map(r=>r.lhr.audits['largest-contentful-paint']?.numericValue).filter(Number.isFinite)),
    field:fields[0]?{scope:fields[0].scope,status:fields[0].status,key:fields[0].key,period:fields[0].period,p75:fields[0].p75}:null,
    field_pass:fieldVerdict(fields[0]),eligible:reasons.length===0,exclusion_reasons:reasons,report_ids:reports.map(r=>r.report_id)};
}
async function main() {
  const command=process.argv[2], args=Object.fromEntries(process.argv.slice(3).map(s=>{const i=s.indexOf('=');return [s.slice(2,i),s.slice(i+1)];}));
  const dir=path.resolve(args.dir||'docbd/data/cwv-study-2026');
  if(command==='archive') {
    if(!/^https:\/\/pagespeed\.web\.dev\/analysis\/[^?]+\/[^/?]+(?:\?form_factor=mobile)?$/.test(args.url||''))throw Error('Use an observed public report URL, not an analysis request.');
    if(!/^[a-z0-9-]+$/.test(args.id||'')||!/^0[1-5]$/.test(args.run||''))throw Error('Specify panel id and run 01–05');
    const response=await fetch(args.url);if(!response.ok)throw Error(`HTTP ${response.status}`);const html=await response.text();
    const data=decodePublicReport(html), stem=`${args.id}-${args.run}`;
    await fs.mkdir(path.join(dir,'raw'),{recursive:true});const raw=gzipSync(html);
    data.provenance={source_url:args.url,retrieved_at:new Date().toISOString(),archive:`raw/${stem}.html.gz`,archive_sha256:hash(raw),html_sha256:hash(html),adapter_version:'1.0',collection_method:'ordinary_public_PSI_UI_then_report_URL_archive'};
    await fs.writeFile(path.join(dir,'raw',stem+'.html.gz'),raw,{flag:'wx'});
    await fs.writeFile(path.join(dir,'raw',stem+'.json'),JSON.stringify(data,null,2)+'\n',{flag:'wx'});
    console.log(JSON.stringify({id:args.id,run:args.run,score:data.lhr?.categories?.performance?.score,field:data.field.p75,field_period:data.field.period,error:data.lhr?.runtimeError||null}));
  } else if(command==='analyse') {
    const panel=JSON.parse(await fs.readFile(path.join(dir,'panel.json'),'utf8'));
    const protocol=JSON.parse(await fs.readFile(path.join(dir,'protocol.json'),'utf8'));
    if(hash(await fs.readFile(path.join(dir,'panel.json')))!==protocol.panel_sha256)throw Error('Frozen panel hash changed');
    const files=(await fs.readdir(path.join(dir,'raw'))).filter(x=>x.endsWith('.json'));const pages=[];
    for(const entry of panel.entries){const reports=[];for(const f of files.filter(x=>x.startsWith(entry.id+'-'))){const r=JSON.parse(await fs.readFile(path.join(dir,'raw',f),'utf8'));const raw=await fs.readFile(path.join(dir,r.provenance.archive));if(hash(raw)!==r.provenance.archive_sha256||hash(gunzipSync(raw))!==r.provenance.html_sha256)throw Error('Archive hash mismatch '+f);const decoded=decodePublicReport(gunzipSync(raw).toString());if(JSON.stringify(decoded)!==JSON.stringify(Object.fromEntries(Object.entries(r).filter(([k])=>k!=='provenance'))))throw Error('Derived report differs '+f);reports.push(r);}pages.push(analysePage(entry,reports));}
    const eligible=pages.filter(p=>p.eligible);
    const endpoint=predicate=>{const p=eligible.filter(predicate),failed=p.filter(x=>!x.field_pass).length;return {failed,total:p.length,proportion:p.length?failed/p.length:null,wilson_95: wilson(failed,p.length)};};
    const result={version:'1.0',generated_at:new Date().toISOString(),panel_sha256:protocol.panel_sha256,scope:panel.sampling,panel_size:pages.length,complete_eligible_pages:eligible.length,
      primary_median_100:endpoint(p=>p.performance.median===100),secondary_median_green:endpoint(p=>p.performance.median>=90),sensitivity_all_five_100:endpoint(p=>p.scores.every(v=>v===100)),pages,
      limitations:['Convenience sample: no estimate of the web or a country.','95% intervals do not correct selection bias.','Five lab runs per URL; shared field window is not five independent field samples.','The historical 30-hotel panel is absent and unmeasured.','No DOI or external validation.']};
    await fs.writeFile(path.join(dir,'results.json'),JSON.stringify(result,null,2)+'\n');console.log(JSON.stringify({...result,pages:pages.map(p=>({id:p.id,score:p.performance?.median,field_pass:p.field_pass,reasons:p.exclusion_reasons}))},null,2));
  } else throw Error('Commands: archive --url=PUBLIC_REPORT --id=PANEL_ID --run=01 --dir=DIR | analyse --dir=DIR');
}
if(process.argv[1]&&import.meta.url===pathToFileURL(path.resolve(process.argv[1])).href)await main();
