"""WHO-only deterministic proposed public source/browser build; no shared-site inputs."""
from pathlib import Path
import argparse,json,hashlib,html,re,io,tarfile,gzip,runpy
D=Path(__file__).resolve().parent
sha=lambda b:hashlib.sha256(b).hexdigest()
def source_inventory():
 manifest=json.loads((D/'SOURCE-MANIFEST.json').read_text());expected=manifest['files']
 actual={str(p.relative_to(D)) for p in D.rglob('*') if p.is_file()}
 if any(p.is_symlink() for p in D.rglob('*')):raise ValueError('Symlink in source tree')
 if actual!=set(expected)|{'SOURCE-MANIFEST.json'}:raise ValueError('Source inventory differs from closed allowlist')
 for n,pin in expected.items():
  if sha((D/n).read_bytes())!=pin:raise ValueError('Source hash differs: '+n)
 return sorted(actual)
def archive(files,release):
 buf=io.BytesIO()
 with gzip.GzipFile(fileobj=buf,mode='wb',mtime=0,filename='') as z:
  with tarfile.open(fileobj=z,mode='w',format=tarfile.USTAR_FORMAT) as tar:
   for n in files:
    b=(D/n).read_bytes();i=tarfile.TarInfo('who-growth-z-score-'+release+'/'+n);i.size=len(b);i.mtime=0;i.mode=0o644;i.uid=i.gid=0;i.uname=i.gname='';tar.addfile(i,io.BytesIO(b))
 return buf.getvalue()
def build(out):
 out=out.resolve()
 if out==D or D in out.parents:raise ValueError('Output must be outside source tree')
 if out.exists() and any(out.iterdir()):raise ValueError('Output must be absent or empty; existing files are never removed')
 files=source_inventory();config=json.loads((D/'public-build-config.json').read_text());release=config['release']
 if not re.fullmatch(r'[a-z0-9-]{1,80}',release):raise ValueError('Invalid release')
 expected='/source/who-growth-z-score/'+release+'/'
 if config['sourcePath']!=expected or config['calculatorPath']!='/calculators/who-growth-z-score/':raise ValueError('Unexpected component paths')
 if config['stage']!='proposed-public-bytes' or config['publicRightsApproved'] is not False:raise ValueError('This builder produces proposed public bytes only, never release authority')
 if config['publicOrigin']!='https://calculatorsprout.com' or config['brand']!='Calculator Sprout':raise ValueError('Unexpected existing brand/origin')
 generated=runpy.run_path(str(D/'generate-module.py'),run_name='who_generator')['render']()
 if generated!=(D/'calculate.mjs').read_bytes():raise ValueError('Scientific module does not reproduce exactly')
 esc=lambda x:html.escape(str(x),quote=True)
 definition=json.loads((D/'definition.json').read_text());fields=[]
 for f in definition['fields']:
  key,label,default,step,*kind=f
  if not re.fullmatch('[a-zA-Z][a-zA-Z0-9]*',key):raise ValueError('Invalid field name')
  if kind and kind[0]=='select':
   control='<select id="'+key+'" name="'+key+'">'+''.join('<option value="'+esc(v)+'"'+(' selected' if v==default else '')+'>'+esc(l)+'</option>' for v,l in kind[1])+'</select>'
  else:
   typ='date' if kind and kind[0]=='date' else 'text'
   control='<input id="'+key+'" name="'+key+'" type="'+typ+'" value="'+esc(default)+'"'+(' inputmode="decimal" autocomplete="off" spellcheck="false"' if typ=='text' else ' autocomplete="off" min="0001-01-01" max="9999-12-31"')+'>'
  fields.append('<div class="field" data-field="'+key+'"><label for="'+key+'">'+esc(label)+'</label>'+control+'</div>')
 page=(D/'page-template.html').read_text().replace('__FIELDS__',''.join(fields)).replace('__SOURCES__',''.join('<li><a href="'+esc(url)+'">'+esc(label)+'</a></li>' for label,url in definition['sources'])).replace('__SOURCE_PATH__',expected).replace('__RELEASE__',release).replace('__CANONICAL__',config['publicOrigin']+config['calculatorPath'])
 payload={config['calculatorPath'].lstrip('/')+'index.html':page.encode()}
 for n in ['calculate.mjs','controller.mjs','style.css']:payload[config['calculatorPath'].lstrip('/')+n]=(D/n).read_bytes()
 prefix=expected.lstrip('/');bundle=archive(files,release)
 payload[prefix+'source.tar.gz']=bundle
 for n in files:payload[prefix+'files/'+n]=(D/n).read_bytes()
 listing=''.join('<li><a href="files/'+esc(n)+'">'+esc(n)+'</a> — <code>'+sha((D/n).read_bytes())+'</code></li>' for n in files)
 landing='<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="robots" content="noindex, follow"><link rel="canonical" href="'+esc(config['publicOrigin']+expected)+'"><meta name="description" content="Exact editable source, upstream licences and offline reconstruction instructions for the Calculator Sprout WHO reference worksheet."><title>WHO component source | Calculator Sprout</title></head><body><main><a href="/">Calculator Sprout</a><h1>WHO worksheet: exact source and licence</h1><p>Release '+esc(release)+'. Copyright (C)2026 Calculator Sprout contributors. GNU GPL version3. No warranty; independent WHO-reference arithmetic, no WHO endorsement.</p><p><a href="source.tar.gz">Download complete source archive</a> — SHA256 <code>'+sha(bundle)+'</code></p><p><a href="files/COPYING">GNU GPL version 3</a> · <a href="files/NOTICE.md">Notices and modifications</a> · <a href="files/README.md">Offline reconstruction instructions</a></p><ul>'+listing+'</ul></main></body></html>'
 payload[prefix+'index.html']=landing.encode()
 csp="default-src 'self'; script-src 'self'; style-src 'self'; connect-src 'none'; img-src 'self'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'; form-action 'none'"
 headers=''.join(path+'*\n  X-Robots-Tag: '+robots+'\n  Cache-Control: '+cache+'\n  X-Content-Type-Options: nosniff\n  Referrer-Policy: no-referrer\n  Content-Security-Policy: '+csp+'\n' for path,robots,cache in [(config['calculatorPath'],'index, follow','public, max-age=300'),(expected,'noindex, follow','public, max-age=31536000, immutable')])
 payload['_headers']=headers.encode()
 for n,b in payload.items():
  p=out/n;p.parent.mkdir(parents=True,exist_ok=True);p.write_bytes(b)
 return {'stage':config['stage'],'files':{n:sha(b) for n,b in sorted(payload.items())},'archiveSHA256':sha(bundle),'sourceFileCount':len(files),'scientificModuleByteIdentical':True,'livePublished':False}
if __name__=='__main__':
 parser=argparse.ArgumentParser();parser.add_argument('--out',type=Path,required=True);args=parser.parse_args();print(json.dumps(build(args.out),indent=2))
