import fs from 'node:fs'
import path from 'node:path'

const root=path.resolve('packages/kbx-ui/src')
const baselinePath=path.resolve('governance/design-debt-baseline.json')
const write=process.argv.includes('--write-baseline')
const files=[]
function walk(dir){for(const e of fs.readdirSync(dir,{withFileTypes:true})){const p=path.join(dir,e.name);if(e.isDirectory())walk(p);else if(/\.(vue|ts|css)$/.test(e.name))files.push(p)}}
walk(root)
const report={}
for(const file of files){
  const rel=path.relative(process.cwd(),file).replaceAll('\\','/')
  if(rel.includes('/tokens/source/')||rel.endsWith('/tokens/kbx.css')) continue
  const text=fs.readFileSync(file,'utf8')
  const hex=(text.match(/#[0-9A-Fa-f]{3,8}\b/g)||[]).length
  const px=(text.match(/(?<![-\w])\d+(?:\.\d+)?px\b/g)||[]).length
  if(hex||px) report[rel]={hex,px,total:hex+px}
}
const totals=Object.values(report).reduce((a,x)=>({hex:a.hex+x.hex,px:a.px+x.px,total:a.total+x.total}),{hex:0,px:0,total:0})
const payload={generatedFrom:'packages/kbx-ui/src',policy:'ratchet-only: existing hardcoded literals may decrease but must not increase; new files start at zero',totals,files:report}
fs.mkdirSync('generated',{recursive:true})
fs.writeFileSync('generated/design-debt-report.json',JSON.stringify(payload,null,2)+'\n')
if(write){fs.mkdirSync(path.dirname(baselinePath),{recursive:true});fs.writeFileSync(baselinePath,JSON.stringify(payload,null,2)+'\n');console.log(`wrote design debt baseline: ${totals.total} literals`);process.exit(0)}
if(!fs.existsSync(baselinePath)){console.error('missing design debt baseline; run measure-design-debt.mjs --write-baseline intentionally');process.exit(1)}
const baseline=JSON.parse(fs.readFileSync(baselinePath,'utf8'))
let failed=false
for(const [file,current] of Object.entries(report)){
  const allowed=baseline.files[file]?.total ?? 0
  if(current.total>allowed){console.error(`design debt increased: ${file} ${current.total} > baseline ${allowed}`);failed=true}
}
if(totals.total>baseline.totals.total){console.error(`design debt total increased: ${totals.total} > ${baseline.totals.total}`);failed=true}
if(failed) process.exit(1)
console.log(`design debt ratchet PASS: ${totals.total} <= ${baseline.totals.total}`)
