"""Original TMP-SCI-204 Unit6 fictional transfer model; standard library only."""
import argparse
from decimal import Decimal, localcontext
from fractions import Fraction as F
import hashlib
import json
from pathlib import Path
import platform
import re
import sys

MAX_BYTES=65536
RATIONAL=re.compile(r'(0|[1-9][0-9]*)(?:/([1-9][0-9]*))?\Z')

def parse_packet(raw):
    if type(raw) is not bytes or len(raw)>MAX_BYTES:raise ValueError('packet must be bytes of at most 64 KiB')
    def pairs(items):
        result={}
        for key,value in items:
            if key in result:raise ValueError('duplicate JSON object key')
            result[key]=value
        return result
    def bad_constant(value):raise ValueError('nonfinite JSON constants are unsupported')
    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 rational(value,maximum,positive=False):
    if type(value) is not str or len(value)>24 or not RATIONAL.fullmatch(value):raise ValueError('use an unsigned integer or fraction string, no spaces, leading zeros or decimal point')
    parts=value.split('/')
    if len(parts)==2 and int(parts[1])>1000:raise ValueError('written denominator must be at most 1000')
    number=F(value)
    if number>maximum or (positive and number==0):raise ValueError('rational parameter outside supported range')
    return number

def validate_packet(packet):
    fields={'a0_g','b0_g','k_per_min','duration_min','base_steps'}
    if type(packet) is not dict or set(packet)!=fields:raise ValueError('packet fields must match the five-field dictionary')
    a=rational(packet['a0_g'],1000);b=rational(packet['b0_g'],1000)
    k=rational(packet['k_per_min'],10);t=rational(packet['duration_min'],100,True)
    n=packet['base_steps']
    if type(n) is not int or not 1<=n<=64:raise ValueError('base_steps must be an integer 1–64, not a boolean')
    return a,b,k,t,n

def _grid(a0,b0,k,t,n):
    h=t/n;q=1-k*h;a,b=a0,b0;total=a0+b0
    states=[];first_negative=None;nonincreasing=True;previous=a
    for step in range(n+1):
        if a<0 or b<0:
            if first_negative is None:first_negative=step
        if a>previous:nonincreasing=False
        states.append({'step':step,'time_min':str(step*h),'a_g':str(a),'b_g':str(b),'total_g':str(a+b)})
        previous=a
        if step<n:
            transfer=k*h*a
            a,b=a-transfer,b+transfer
    return {'steps':n,'step_min':str(h),'q':str(q),'positivity_condition':0<=k*h<=1,
            'conserved':all(F(s['total_g'])==total for s in states),'nonnegative':first_negative is None,
            'first_negative_step':first_negative,'a_nonincreasing':nonincreasing,
            'endpoint_a_g':str(a),'endpoint_b_g':str(b),'states':states}

def analyse_packet(packet):
    a,b,k,t,n=validate_packet(packet)
    grids=[_grid(a,b,k,t,m*n) for m in (1,2,4)]
    ends=[F(g['endpoint_a_g']) for g in grids]
    coarse=abs(ends[1]-ends[0]);fine=abs(ends[2]-ends[1])
    # Rounded external-to-recurrence comparator, not an interval certificate.
    with localcontext() as ctx:
        ctx.prec=50
        dec=lambda f:Decimal(f.numerator)/Decimal(f.denominator)
        ref=dec(a)*(-dec(k*t)).exp()
        reference={'formula':'A(T) = A0 * exp(-k*T); B(T) = A0 + B0 - A(T)',
                   'a_g_decimal':str(ref),'b_g_decimal':str(dec(a+b)-ref),'precision_digits':50,
                   'interpretation':'Separately rounded supplied ideal constant-rate model; not measured data or a certified interval.'}
        for g in grids:g['reference_abs_difference_g_decimal']=str(abs(dec(F(g['endpoint_a_g']))-ref))
    return {'schema_version':1,'model':'fictional closed one-way constant-rate transfer',
            'parameters':dict(packet),'total_g':str(a+b),'grids':grids,'reference':reference,
            'refinement':{'coarse_gap_g':str(coarse),'fine_gap_g':str(fine),
                          'gap_ratio':str(coarse/fine) if fine else None,
                          'interpretation':'Same-time finite-grid differences, not an error bound, convergence proof or empirical validation.'},
            'interpretation':'Exact rational recurrence arithmetic does not make the timestep approximation or physical model exact. Negative states are retained and flagged.'}

def text_summary(report):
    lines=['Fictional closed transfer: grams, minutes, rate per minute.',
           'Total initial mass: '+report['total_g']+' g.']
    for g in report['grids']:
        lines.append(f"Grid {g['steps']} steps; h={g['step_min']} min; q={g['q']}; positivity condition={g['positivity_condition']}.")
        lines.append(f"Endpoint A={g['endpoint_a_g']} g; B={g['endpoint_b_g']} g; conserved={g['conserved']}; nonnegative={g['nonnegative']}; first negative step={g['first_negative_step']}; A nonincreasing={g['a_nonincreasing']}.")
        for s in g['states']:lines.append(f"Step {s['step']}, time {s['time_min']} min: A {s['a_g']} g, B {s['b_g']} g, total {s['total_g']} g.")
        lines.append('Absolute difference from rounded reference, g: '+g['reference_abs_difference_g_decimal'])
    lines.append('Refinement: '+json.dumps(report['refinement'],sort_keys=True))
    lines.append('Reference: '+json.dumps(report['reference'],sort_keys=True))
    lines.append(report['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 handle:raw=handle.read(MAX_BYTES+1)
    report=analyse_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('utf-8'),'transfer_model.py':source}
    output=Path(new_directory);output.mkdir(exist_ok=False)
    for name,data in payloads.items():
        with (output/name).open('xb') as handle:handle.write(data)
    manifest={'status':'complete','python':platform.python_version(),'implementation':platform.python_implementation(),
              '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':'Completion requires valid run.json plus all matching listed files. Partial directories are retained, never silently overwritten. Hashes detect changes, not authorship or scientific validity.'}
    with (output/'run.json').open('xb') as handle:handle.write(json_bytes(manifest))
    return report

def main():
    parser=argparse.ArgumentParser(description='Fictional transfer-model diagnostics 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}. Keep any partial output and choose a new directory after diagnosis.\n')
    print('Completed evidence packet:',args.new_directory)

if __name__=='__main__':main()
