"""Render from a temporary copy with no sibling brief and compare all12 PNGs.
The temporary folder is created strictly below this pack's qa/ directory and
its resolved containment is verified before cleanup. No network is used.
"""
from pathlib import Path
import hashlib, json, shutil, subprocess, sys, tempfile

ROOT=Path(__file__).resolve().parent
QA=(ROOT/'qa').resolve()
def sha(p):return hashlib.sha256(p.read_bytes()).hexdigest()
def main():
    task_tmp=Path(tempfile.mkdtemp(prefix='_reproduction_',dir=QA)).resolve()
    assert task_tmp.is_relative_to(QA) and task_tmp.name.startswith('_reproduction_')
    try:
        shutil.copy2(ROOT/'render_suites.py',task_tmp/'render_suites.py')
        for name in ['stock','art','copy','fonts/production']:
            shutil.copytree(ROOT/name,task_tmp/name)
        result=subprocess.run([sys.executable,str(task_tmp/'render_suites.py')],capture_output=True,text=True,encoding='utf-8',check=True)
        qa=json.loads((task_tmp/'qa/render-validation.json').read_text(encoding='utf-8'))
        assert qa['all_checks_pass']
        compared=[]
        for p in sorted((ROOT/'faces').glob('*.png')):
            same=sha(p)==sha(task_tmp/'faces'/p.name)
            compared.append({'file':p.name,'sha256':sha(p),'reproduced_identically':same})
        assert len(compared)==12 and all(x['reproduced_identically'] for x in compared)
        receipt={'method':'Fresh isolated copy, sibling brief absent; renderer falls back to bundled stock and resolves packaged fonts/art/copy.','faces':compared,'all12_identical':True,'copy_and_stock_mask_checks_pass':True,'external_brief_required':False,'physical_tested':False}
        (QA/'portable-reproduction.json').write_text(json.dumps(receipt,indent=2),encoding='utf-8')
        print(json.dumps({'all12_identical':True,'checks_pass':True,'external_brief_required':False}))
    finally:
        # Verify the final absolute recursive-delete target stays inside qa/.
        checked_target=task_tmp.resolve()
        assert checked_target.is_relative_to(QA) and checked_target.name.startswith('_reproduction_') and checked_target!=QA
        shutil.rmtree(checked_target)
if __name__=='__main__':main()
