import 'server-only';
import fs from 'node:fs';
import path from 'node:path';
import {createHash} from 'node:crypto';
/**
 * A file alone does not mean an app renders. Generated by an offline Chromium
 * smoke run; recorded SHA-256 prevents later/replaced captures being silently
 * shown as Available without a new verification run.
 */
interface RenderHealth{version:number;devices:Record<string,{ok:boolean;sha256:string;reason?:string}>}
const root=path.resolve(process.cwd(),'app-uis');
let report:RenderHealth|undefined;
const cache=new Map<string,{mtimeMs:number;size:number;sha256:string}>();
function getReport():RenderHealth{
 if(report)return report;
 try{report=JSON.parse(fs.readFileSync(path.join(root,'render-health.json'),'utf8')) as RenderHealth}catch{report={version:1,devices:{}}}
 return report;
}
export function verifiedAppUiFile(slug:string,device:'phone'|'desktop'):string|null{
 if(!/^[a-z0-9-]{1,70}$/.test(slug))return null;
 const file=path.join(root,slug,device,'index.html');
 const health=getReport().devices[slug+'/'+device];
 if(!health?.ok||!/^[a-f0-9]{64}$/.test(health.sha256))return null;
 try{
  const stat=fs.statSync(file);if(!stat.isFile()||stat.size<1000)return null;
  let c=cache.get(file);
  if(!c||c.mtimeMs!==stat.mtimeMs||c.size!==stat.size){
   c={mtimeMs:stat.mtimeMs,size:stat.size,sha256:createHash('sha256').update(fs.readFileSync(file)).digest('hex')};cache.set(file,c);
  }
  return c.sha256===health.sha256?file:null;
 }catch{return null}
}
