"""Original TMP-SCI-204 Unit 7 synthetic trials; standard library only."""
import argparse
from fractions import Fraction as F
import hashlib
import json
from pathlib import Path
import platform
import random
import sys
MAX_BYTES=65536

def parse_packet(raw):
    if type(raw) is not bytes or len(raw)>MAX_BYTES:raise ValueError('input must be bytes of at most 64 KiB')
    def pairs(items):
        result={}
        for k,v in items:
            if k in result:raise ValueError('duplicate JSON object key')
            result[k]=v
        return result
    def bad_constant(value):raise ValueError('nonfinite JSON constant')
    try:return json.loads(raw.decode('utf-8'),object_pairs_hook=pairs,parse_constant=bad_constant)
    except (UnicodeDecodeError,RecursionError) as error:raise ValueError('invalid or overly nested UTF-8 JSON') from error

def validate_packet(p):
    fields={'success_numerator','success_denominator','batch_size','batch_count','seed'}
    if type(p) is not dict or set(p)!=fields:raise ValueError('packet must contain exactly the five documented fields')
    if any(type(v) is not int for v in p.values()):raise ValueError('all fields must be JSON integers, not booleans')
    a,d,n,b,s=(p[k] for k in ['success_numerator','success_denominator','batch_size','batch_count','seed'])
    if not (1<=d<=1000 and 0<=a<=d and 1<=n<=100 and 2<=b<=40 and 0<=s<2**32):raise ValueError('parameter outside supported range')
    return a,d,n,b,s

def summarise_draws(p,draws):
    a,d,n,b,seed=validate_packet(p)
    if type(draws) is not list or len(draws)!=n*b or any(type(x) is not int or not 0<=x<d for x in draws):raise ValueError('draw list must have the exact supported length and integer range')
    outcomes=[int(x<a) for x in draws]
    counts=[sum(outcomes[i*n:(i+1)*n]) for i in range(b)]
    total=sum(counts)
    return {'schema_version':1,'model':'fictional independent equal-probability synthetic detection trials',
            'parameters':dict(p),'probability':str(F(a,d)),'draws':list(draws),'outcomes':outcomes,
            'batch_successes':counts,'batch_rates':[str(F(c,n)) for c in counts],
            'total_trials':n*b,'total_successes':total,'pooled_success_rate':str(F(total,n*b)),
            'observed_mean_successes':str(F(total,b)),
            'expected_successes_per_batch':str(F(n*a,d)),
            'batch_min':min(counts),'batch_max':max(counts),
            'interpretation':'Recorded synthetic variation under stated ideal independence/equal-probability assumptions; not observations, confidence intervals or empirical validation.'}

def encode_state(state):return [state[0],list(state[1]),state[2]]

def restore_rng(encoded):
    if type(encoded) is not list or len(encoded)!=3 or type(encoded[0]) is not int or encoded[0]!=3 or encoded[2] is not None:raise ValueError('requires version-3 Random state with no Gaussian cache')
    vector=encoded[1]
    if type(vector) is not list or len(vector)!=625:raise ValueError('state vector must contain 625 integers')
    if any(type(x) is not int or not 0<=x<2**32 for x in vector[:624]) or type(vector[624]) is not int or not 0<=vector[624]<=624:raise ValueError('state words or index out of range')
    rng=random.Random(0);rng.setstate((3,tuple(vector),None));return rng

def replay_checkpoint(p,states):
    a,d,n,b,seed=validate_packet(p);split=n*(b//2)
    if type(states) is not dict or type(states.get('checkpoint_draw_count')) is not int or states.get('checkpoint_draw_count')!=split:raise ValueError('checkpoint draw count does not match this packet')
    contract={k:p[k] for k in ['success_denominator','batch_size','batch_count','seed']}
    observed=states.get('stream_contract')
    if type(observed) is not dict or observed!=contract or any(type(v) is not int for v in observed.values()):raise ValueError('checkpoint draw contract does not match this packet')
    rng=restore_rng(states.get('checkpoint'))
    suffix=[rng.randrange(d) for _ in range(n*b-split)]
    return suffix,encode_state(rng.getstate())

def simulate_packet(p):
    a,d,n,b,seed=validate_packet(p);rng=random.Random(seed);split=n*(b//2)
    initial=encode_state(rng.getstate());draws=[];checkpoint=None
    for i in range(n*b):
        draws.append(rng.randrange(d))
        if i+1==split:checkpoint=encode_state(rng.getstate())
    states={'generator':'Python random.Random; implementation-specific version-3 state, no Gaussian cache',
            'stream_contract':{k:p[k] for k in ['success_denominator','batch_size','batch_count','seed']},
            'initial':initial,'checkpoint_draw_count':split,'checkpoint':checkpoint,'final':encode_state(rng.getstate())}
    report=summarise_draws(p,draws)
    suffix,final=replay_checkpoint(p,states)
    report['checkpoint_draw_count']=split
    report['checkpoint_replay_verified']=suffix==draws[split:] and final==states['final']
    return report,states

def text_summary(r):
    p=r['parameters'];n=p['batch_size']
    lines=['Fictional synthetic detection trials; success is a model label, not a real observation.',
           f"Seed {p['seed']}; probability {r['probability']}; {p['batch_count']} batches of {n} trials."]
    for i,c in enumerate(r['batch_successes']):
        lines.append(f"Batch {i+1}: draws {r['draws'][i*n:(i+1)*n]}; outcomes {r['outcomes'][i*n:(i+1)*n]}; successes {c}; rate {r['batch_rates'][i]}.")
    lines.extend([f"Total successes {r['total_successes']} of {r['total_trials']}; pooled rate {r['pooled_success_rate']}.",
                  f"Observed mean successes {r['observed_mean_successes']}; theoretical expected successes per batch {r['expected_successes_per_batch']}.",
                  f"Observed batch range {r['batch_min']} to {r['batch_max']}; not a confidence interval."])
    if 'checkpoint_replay_verified' in r:lines.append(f"Checkpoint after {r['checkpoint_draw_count']} draws; suffix and final state replay verified {r['checkpoint_replay_verified']}.")
    lines.append(r['interpretation']);return '\n'.join(lines)+'\n'

def json_bytes(value):return (json.dumps(value,sort_keys=True,indent=2,allow_nan=False)+'\n').encode('utf-8')

def run_analysis(input_path,new_directory):
    with Path(input_path).open('rb') as f:raw=f.read(MAX_BYTES+1)
    report,states=simulate_packet(parse_packet(raw));source=Path(__file__).resolve().read_bytes()
    payloads={'input.json':raw,'report.json':json_bytes(report),'summary.txt':text_summary(report).encode(),
              'states.json':json_bytes(states),'simulation_records.py':source}
    output=Path(new_directory);output.mkdir(exist_ok=False)
    for name,data in payloads.items():
        with (output/name).open('xb') as f:f.write(data)
    manifest={'status':'complete','python':platform.python_version(),'implementation':platform.python_implementation(),
              'generator':'random.Random / Mersenne Twister; randrange algorithm and state compatibility depend on implementation/version',
              'invocation_argv':list(sys.argv),'input_argument':str(input_path),'output_argument':str(new_directory),
              'files':{name:hashlib.sha256(data).hexdigest() for name,data in payloads.items()},
              'warning':'Require a parseable complete run.json and all matching payloads. Preserve partial output; never silently overwrite. Hashes are not authentication or scientific validation.'}
    with (output/'run.json').open('xb') as f:f.write(json_bytes(manifest))
    return report

def main():
    parser=argparse.ArgumentParser(description='Record fictional repeated trials into a new directory only.')
    parser.add_argument('input_json');parser.add_argument('new_directory');args=parser.parse_args()
    try:run_analysis(args.input_json,args.new_directory)
    except (ValueError,OSError) as error:parser.exit(2,f'Cannot complete run: {error}. Preserve any partial output; diagnose and choose a new directory.\n')
    print('Completed synthetic evidence packet:',args.new_directory)
if __name__=='__main__':main()
