"""Portable exact-source build, archive, negative-control and local HTTP checks."""
from pathlib import Path
import tempfile,subprocess,sys,json,hashlib,tarfile,io,shutil,threading,http.server,urllib.request,re
D=Path(__file__).resolve().parent;checks=0
sha=lambda b:hashlib.sha256(b).hexdigest()
def check(x,message):
 global checks
 assert x,message;checks+=1
def run(root,*args,ok=True):
 p=subprocess.run([sys.executable,str(root/'build.py'),*map(str,args)],capture_output=True,text=True)
 check((p.returncode==0)==ok,'builder status '+p.stderr);return json.loads(p.stdout) if ok else p
with tempfile.TemporaryDirectory(prefix='who-component-check-') as tmp:
 T=Path(tmp);a=T/'a';b=T/'b';one=run(D,'--out',a);two=run(D,'--out',b);check(one==two,'deterministic repeated receipt')
 for n,pin in one['files'].items():check(sha((a/n).read_bytes())==pin==sha((b/n).read_bytes()),'output parity '+n)
 config=json.loads((D/'public-build-config.json').read_text());prefix=config['sourcePath'].lstrip('/');bundle=(a/prefix/'source.tar.gz').read_bytes()
 with tarfile.open(fileobj=io.BytesIO(bundle),mode='r:gz') as tar:
  members=tar.getmembers();root='who-growth-z-score-'+config['release']+'/'
  for item in members:check(item.isfile() and item.name.startswith(root) and '..' not in Path(item.name).parts and not Path(item.name).is_absolute(),'safe source member')
  extracted=T/'unpacked';extracted.mkdir()
  for item in members:
   p=extracted/item.name;p.parent.mkdir(parents=True,exist_ok=True);p.write_bytes(tar.extractfile(item).read())
 source=extracted/root;three=run(source,'--out',T/'rebuild');check(one==three,'clean extracted source rebuild parity')
 for command in [[sys.executable,'generate-module.py'],['node','controller-tests.mjs'],['node','tests.mjs']]:
  p=subprocess.run(command,cwd=source,capture_output=True,text=True);check(p.returncode==0,'portable '+str(command)+' '+p.stderr)
 check((source/'calculate.mjs').read_bytes()==(D/'calculate.mjs').read_bytes(),'clean generation exact module')
 oracle=T/'oracle';oracle.mkdir();(oracle/'source').mkdir();(oracle/'evidence').mkdir();shutil.copyfile(source/'generate-oracle.py',oracle/'generate-oracle.py')
 for p in (source/'source').glob('*.txt'):shutil.copyfile(p,oracle/'source'/p.name)
 oracleRun=subprocess.run([sys.executable,'generate-oracle.py'],cwd=oracle,capture_output=True,text=True)
 check(oracleRun.returncode==0,'Decimal oracle regeneration '+oracleRun.stderr)
 check((oracle/'oracle-fixtures.json').read_bytes()==(source/'oracle-fixtures.json').read_bytes(),'1088 Decimal fixtures reproduced byte-for-byte')
 newOracle=subprocess.run([sys.executable,'-B','generate-r5-oracle.py'],cwd=source,capture_output=True,text=True)
 check(newOracle.returncode==0,'R5 Decimal/CDF oracle regeneration '+newOracle.stderr)
 check((source/'r5-oracle-fixtures.json').read_bytes()==(D/'r5-oracle-fixtures.json').read_bytes(),'R5 Decimal/CDF fixtures reproduced byte-for-byte')
 # Strong negative controls for allowlist, source integrity, symlink, accidental release.
 def copy(name):
  p=T/name;shutil.copytree(D,p);return p
 x=copy('extra');(x/'unlisted.txt').write_text('private');run(x,'--out',T/'bad-extra',ok=False)
 x=copy('tamper');(x/'style.css').write_text('tamper');run(x,'--out',T/'bad-tamper',ok=False)
 x=copy('symlink');(x/'unexpected-link').symlink_to(x/'COPYING');run(x,'--out',T/'bad-link',ok=False)
 run(D,'--out',D/'inside',ok=False);run(D,'--out',a,ok=False)
 # Inspect exact allowlisted text; official archives are independently pinned upstream.
 inventory=json.loads((D/'SOURCE-MANIFEST.json').read_text())['files']
 for n in inventory:
  if n.endswith('.tar.gz'):continue
  text=(D/n).read_text();check(not re.search(r'/'+'Users/|/'+'private/tmp/|Q-'+r'[0-9a-f]{20}|full-'+'query-members|github_'+'publisher|CLOUDFLARE_'+'API_TOKEN|GITHUB_'+'TOKEN',text),'private leakage '+n)
 check(set(re.findall(r"from ['\"]([^'\"]+)",(D/'controller.mjs').read_text()))=={'./calculate.mjs'},'finite controller import graph')
 check('noindex' not in (a/config['calculatorPath'].lstrip('/')/'index.html').read_text(),'proposed public calculator has no private robots')
 check(config['publicOrigin']+config['calculatorPath'] in (a/config['calculatorPath'].lstrip('/')/'index.html').read_text(),'exact same-site canonical')
 for name in ['index.html']:
  page=(a/config['calculatorPath'].lstrip('/')/name).read_text();check(not re.search('Private|awaiting|pending|unapproved',page,re.I),'no private/pending visible page text')
 # Anonymous local HTTP simulation only; no provider, account or public offer claim.
 class Handler(http.server.SimpleHTTPRequestHandler):
  def __init__(self,*args,**kwargs):super().__init__(*args,directory=str(a),**kwargs)
  def log_message(self,*args):pass
 server=http.server.ThreadingHTTPServer(('127.0.0.1',0),Handler);thread=threading.Thread(target=server.serve_forever,daemon=True);thread.start()
 try:
  origin='http://127.0.0.1:'+str(server.server_port)
  for url,expected in [(config['sourcePath']+'source.tar.gz',bundle),(config['sourcePath']+'files/COPYING',(D/'COPYING').read_bytes()),(config['calculatorPath']+'controller.mjs',(D/'controller.mjs').read_bytes())]:
   with urllib.request.urlopen(origin+url) as response:check(response.status==200 and response.read()==expected,'anonymous local source retrieval '+url)
 finally:server.shutdown();server.server_close();thread.join()
 print(json.dumps({'passed':True,'checks':checks,'sourceFiles':one['sourceFileCount'],'archiveSHA256':one['archiveSHA256'],'anonymousRetrieval':'local HTTP simulation only; not live public delivery','reconstruction':'exact extracted-source byte-identical output','publicRightsApproved':False,'providerMutations':False},indent=2))
