"""Bind complete gameplay evidence to one exact native/client artifact pair.

Individual reports retain their narrower boundaries. A passing aggregate needs
every required gate from a successful scoped run; historical callback reports
and loaded scene setup cannot fill normal entry/carry/card gates.
"""
from __future__ import annotations
import argparse
import json
from pathlib import Path
from test_gameplay_real_server import GATES
from test_real_server import sha

NORMAL_ONLY={'normal_entry','carrying','card_save_load_restart'}


def aggregate(paths, native, client):
    native_hash,client_hash=sha(native),sha(client)
    runtime={path.name:sha(path) for path in native.parent.glob('*.dll')}
    gates={name:dict(passed=False,evidence=[],shortcuts=[],remaining='no successful exact-artifact scoped report')
           for name in GATES}
    sources=[]
    for path in paths:
        report=json.loads(path.read_text(encoding='utf8'))
        if report.get('native_sha256')!=native_hash or report.get('client_sha256')!=client_hash:
            raise ValueError(f'{path}: runtime artifact pair differs from aggregate')
        if report.get('native_runtime_sha256',{})!=runtime:
            raise ValueError(f'{path}: native DLL runtime differs from aggregate')
        if report.get('status')!='passed':
            raise ValueError(f'{path}: failed or incomplete report cannot supply accepted gates')
        unchanged=report.get('execution_inputs_unchanged',{})
        if not unchanged or not all(value is True for value in unchanged.values()):
            raise ValueError(f'{path}: execution inputs were not frozen')
        scope=report.get('scope_gates',[])
        if not scope or not set(scope)<=set(GATES):
            raise ValueError(f'{path}: invalid acceptance scope')
        for name in scope:
            gate=report.get('gates',{}).get(name,{})
            if gate.get('passed') is not True or not gate.get('evidence'):
                raise ValueError(f'{path}: scoped gate {name} has no passing evidence')
            if name in NORMAL_ONLY and report.get('acceptance_kind')!='normal_gameplay':
                raise ValueError(f'{path}: loaded scene setup cannot prove {name}')
            reference={'report':str(path.resolve()),'report_sha256':sha(path),
                       'acceptance_kind':report.get('acceptance_kind'),'boundary':report.get('boundary'),
                       'evidence':gate['evidence']}
            gates[name]['passed']=True
            gates[name]['remaining']=None
            gates[name]['evidence'].append(reference)
            gates[name]['shortcuts']+=gate.get('shortcuts',[])
        sources.append({'path':str(path.resolve()),'sha256':sha(path),'scope_gates':scope,
                        'ap_revision':report.get('ap_revision'),'toolkit_revision':report.get('toolkit_revision'),
                        'catalog_sha256':report.get('catalog_sha256'),'patches':report.get('patches'),
                        'driver_sha256':report.get('driver_sha256'),
                        'orchestration_sha256':report.get('orchestration_sha256')})
    return {'format':'pikmin2-production-gameplay-evidence-v1',
            'status':'passed' if all(g['passed'] for g in gates.values()) else 'failed',
            'native_sha256':native_hash,'client_sha256':client_hash,'gates':gates,'source_reports':sources,
            'native_runtime_sha256':runtime,
            'boundary':'aggregate of exact-artifact production gameplay scopes; setup shortcuts remain attached to each gate; no fullcampaign or shuffled/co-op option claim'}


if __name__=='__main__':
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--native',type=Path,required=True)
    parser.add_argument('--client',type=Path,required=True)
    parser.add_argument('--report',type=Path,action='append',required=True)
    parser.add_argument('--output',type=Path,required=True)
    args=parser.parse_args()
    result=aggregate(args.report,args.native,args.client)
    args.output.parent.mkdir(parents=True,exist_ok=True)
    args.output.write_text(json.dumps(result,indent=2)+'\n',encoding='utf8')
    print(json.dumps({'status':result['status'],'gates':{k:v['passed'] for k,v in result['gates'].items()},
                      'report':str(args.output)},indent=2))
    if result['status']!='passed':raise SystemExit(1)
