// Offline secondary analysis. The 13 October source corpus is read-only.
import fs from 'node:fs';
import path from 'node:path';
import crypto from 'node:crypto';
import assert from 'node:assert/strict';
const root=path.resolve(process.argv.slice(2).find(a=>!a.startsWith('--'))||'.');
const check=process.argv.includes('--check');
const study=path.join(root,'docbd/data/cwv-study-2026');
const output=path.join(root,'docbd/data/cwv-observations-2026-10-14');
const sha=b=>crypto.createHash('sha256').update(b).digest('hex');
const sources={};
function read(file) {const b=fs.readFileSync(path.join(root,file));sources[file]={bytes:b.length,sha256:sha(b)};return JSON.parse(b);}
const manifest=read('docbd/data/cwv-study-2026/manifest.json');
const keys=['largest_contentful_paint','interaction_to_next_paint','cumulative_layout_shift'];
const pages=[];
for(const file of Object.keys(manifest.files).filter(p=>/^raw\/.*\.json$/.test(p)).sort()){
 const source='docbd/data/cwv-study-2026/'+file,d=read(source);
 assert.equal(sources[source].sha256,manifest.files[file].sha256,'Frozen source changed');
 assert.equal(d.field.status,'available');assert.equal(d.field.scope,'url');assert.equal(d.field.form_factor,'PHONE');
 const metrics=new Map(d.field.raw[1]);
 const p75=name=>{const tuple=metrics.get(name)?.[1]?.[1]?.[0];const v=tuple?.[1]??tuple?.[2];assert(v!==null&&v!==undefined&&Number.isFinite(Number(v)),name+' missing');return Number(v);};
 const stable=Object.fromEntries(keys.map(k=>[k,p75(k)]));
 assert.deepEqual(stable,d.field.p75);
 const experimental=Object.fromEntries(keys.map(k=>[k,p75('experimental_'+k+'_with_softnavs')]));
 const delta=Object.fromEntries(keys.map(k=>[k,experimental[k]-stable[k]]));
 let page=pages.find(p=>p.url===d.field.key);
 if(page){assert.deepEqual({stable,experimental,period:d.field.period},{stable:page.stable,experimental:page.experimental,period:page.period},'Repeated reports must have identical field snapshots');page.sources.push(source);}
 else pages.push({url:d.field.key,period:d.field.period,form_factor:'PHONE',stable,experimental,delta,within_tolerance:Math.abs(delta[keys[0]])<=2&&Math.abs(delta[keys[1]])<=2&&delta[keys[2]]===0,sources:[source]});
}
assert.equal(pages.length,11);assert(pages.every(p=>p.sources.length===5));
const runs=Array.from({length:5},(_,i)=>read('docbd/data/cwv-baseline-2026-10-13/run-0'+(i+1)+'.json'));
const psi=read('docbd/data/cwv-baseline-2026-10-13/psi-single-report.json').lhr;
const median=xs=>{const s=[...xs].sort((a,b)=>a-b);return s[Math.floor(s.length/2)];};
const weights={'first-contentful-paint':0.1,'largest-contentful-paint':0.25,'speed-index':0.1,'total-blocking-time':0.3,'cumulative-layout-shift':0.25};
const config=l=>({benchmark_index:l.environment.benchmarkIndex,cpu_slowdown:l.configSettings.throttling.cpuSlowdownMultiplier,throttling_method:l.configSettings.throttlingMethod,host_user_agent:l.environment.hostUserAgent,lighthouse_version:l.lighthouseVersion});
const cliIndex=median(runs.map(r=>config(r).benchmark_index));
const cliCpu=4;assert(runs.every(r=>config(r).cpu_slowdown===cliCpu));
const psiConfig=config(psi);
const component_scores=Object.entries(weights).map(([id,weight])=>({id,weight,cli_scores:runs.map(r=>r.audits[id].score),psi_score:psi.audits[id].score,cli_values:runs.map(r=>r.audits[id].numericValue),psi_value:psi.audits[id].numericValue}));
const soft={analysis_date:'2026-10-14',collection_date:'2026-10-13',design:'Secondary descriptive analysis of a convenience pilot; no population inference',unit:'One URL-level CrUX PHONE snapshot per page, not five independent samples',tolerance:{lcp_ms:2,inp_ms:2,cls:0},field_pages:pages.length,within_tolerance:pages.filter(p=>p.within_tolerance).length,pages};
const cpu={analysis_date:'2026-10-14',cli:runs.map(config),psi:psiConfig,cli_benchmark_median:cliIndex,normalised_index_ratio:(cliIndex/cliCpu)/(psiConfig.benchmark_index/psiConfig.cpu_slowdown),heuristic_matching_slowdown:cliIndex/(psiConfig.benchmark_index/psiConfig.cpu_slowdown),formula:'(CLI benchmark / CLI multiplier) / (PSI benchmark / PSI multiplier)',limit:'Linear benchmark heuristic only, not measured rendering speed or a validated calibration. Different browser builds, environments and audit dependencies; one PSI run. No causal interpretation or guarantee that the heuristic multiplier reproduces PSI.',component_scores,speed_index_score_gap_points:100*weights['speed-index']*(median(runs.map(r=>r.audits['speed-index'].score))-psi.audits['speed-index'].score)};
const results={'soft-navigation-analysis.json':soft,'lab-environment-analysis.json':cpu};
if(check){
 for(const [name,value] of Object.entries(results))assert.deepEqual(JSON.parse(fs.readFileSync(path.join(output,name))),value,name+' replay');
 const m=JSON.parse(fs.readFileSync(path.join(output,'manifest.json')));assert.deepEqual(m.source_files,sources,'Source inventory');
 for(const [name,value] of Object.entries(m.files))assert.equal(sha(fs.readFileSync(path.join(output,name))),value.sha256,name+' digest');
 assert.equal(sha(fs.readFileSync(new URL(import.meta.url))),sha(fs.readFileSync(path.join(output,'analyse.mjs'))),'Published script');
}else{
 fs.mkdirSync(output,{recursive:true});
 for(const [name,value] of Object.entries(results))fs.writeFileSync(path.join(output,name),JSON.stringify(value,null,2)+'\n');
 fs.copyFileSync(new URL(import.meta.url),path.join(output,'analyse.mjs'));
 const files={};for(const name of fs.readdirSync(output).filter(n=>n!=='manifest.json')){const b=fs.readFileSync(path.join(output,name));files[name]={bytes:b.length,sha256:sha(b)};}
 fs.writeFileSync(path.join(output,'manifest.json'),JSON.stringify({version:'1.0',analysis_date:'2026-10-14',source_files:sources,files},null,2)+'\n');
}
console.log(JSON.stringify({operation:check?'verify':'build',field_pages:soft.field_pages,within_tolerance:soft.within_tolerance,changed:pages.filter(p=>!p.within_tolerance).map(p=>({url:p.url,stable:p.stable,experimental:p.experimental})),cli_benchmark:cliIndex,ratio:cpu.normalised_index_ratio,slowdown:cpu.heuristic_matching_slowdown,speed_index_points:cpu.speed_index_score_gap_points},null,2));
