import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const src = path.resolve(root, '../../portal/src');
function walk(dir) { return fs.readdirSync(dir,{withFileTypes:true}).flatMap(e=>e.isDirectory()?walk(path.join(dir,e.name)):[path.join(dir,e.name)]); }
const pageFiles=walk(path.join(src,'pages')).filter(f=>f.endsWith('.tsx')&&!f.includes('/api/'));
const local=pageFiles.map(file=>{const body=fs.readFileSync(file,'utf8');const imports=[...body.matchAll(/from ['"](@\/implementations\/[^'"]+)['"]/g)].map(m=>m[1]);let refs=[];for(const name of imports){const p=path.join(src,name.slice(2));const file=['.tsx','.ts','/index.tsx','/index.ts'].map(e=>p+e).find(p=>fs.existsSync(p));if(file){const text=fs.readFileSync(file,'utf8');refs.push({file:path.relative(src,file),bytes:text.length,labels:[...text.matchAll(/(?:title|label|placeholder|heading):?\s*[=:{]?\s*['"]([^'"\n]{3,100})['"]/g)].map(m=>m[1]).slice(0,25),components:[...new Set([...text.matchAll(/(?:createElement\(|<)([A-Z][A-Za-z0-9]+)/g)].map(m=>m[1]))].slice(0,40)});}}return {route:'/'+path.relative(path.join(src,'pages'),file).replace(/\.tsx$/,'').replace(/(^|\/)index$/,''),file:path.relative(src,file),pageBytes:body.length,labels:[...body.matchAll(/(?:title|label|placeholder):?\s*[=:{]?\s*['"]([^'"\n]{3,100})['"]/g)].map(m=>m[1]).slice(0,30),implementations:refs};});
const live=JSON.parse(fs.readFileSync(path.join(root,'audit/live-routes.json'),'utf8')).routes;
const all=[...new Set([...live,...local.map(x=>x.route)])].filter(x=>!['/_app','/_document','/_error'].includes(x)).sort();
fs.writeFileSync(path.join(root,'audit/source-inventory.json'),JSON.stringify({localPageCount:local.length,livePageCount:live.length,unionCount:all.length,pages:all.map(route=>({route,live:live.includes(route),source:local.find(x=>x.route===route)||null}))},null,2));
console.log(JSON.stringify({localPages:local.length,livePages:live.length,allPages:all.length,implementationsRead:local.reduce((a,x)=>a+x.implementations.length,0),liveOnly:live.filter(x=>!local.some(l=>l.route===x))},null,2));
