"""Original TMP-SCI-204 Unit3 numerical lab, standard library only.

Fictional values, owned exercise folders, no concurrent source edits.
No network, installation, deletion or existing-output reuse.
"""
from fractions import Fraction
import hashlib
import json
import math
from pathlib import Path
import platform
import re
import sys

DECIMAL_TOKEN = re.compile(r'[+-]?(?:0|[1-9][0-9]{0,17})(?:\.[0-9]{1,12})?\Z')


def parse_decimal(token):
    """Exact reference from bounded decimal text, never from a prior float."""
    if type(token) is not str or len(token) > 32 or not DECIMAL_TOKEN.fullmatch(token):
        raise ValueError('use signed decimal text: 1–18 integer digits, optional 1–12 decimal digits; no leading zeroes except zero itself')
    return Fraction(token)


def difference_case(left, right):
    """Subtract left-right; report exact decimal-reference and binary error."""
    exact = parse_decimal(left) - parse_decimal(right)
    calculated = float(left) - float(right)
    error = abs(Fraction(calculated) - exact)
    return {
        'left_token': left, 'right_token': right,
        'exact_difference': str(exact), 'float_difference': calculated,
        'float_difference_exact': str(Fraction(calculated)),
        'absolute_error': str(error),
        'relative_error': None if exact == 0 else str(error / abs(exact)),
    }


def sum_case(tokens):
    """Compare deliberate left-to-right float addition with math.fsum."""
    if type(tokens) is not list or not 1 <= len(tokens) <= 1000:
        raise ValueError('supply a list of 1–1000 bounded decimal tokens')
    exact = sum((parse_decimal(token) for token in tokens), Fraction(0))
    values = [float(token) for token in tokens]
    sequential = 0.0
    for value in values:
        sequential += value
    accurate = math.fsum(values)
    return {
        'tokens': list(tokens), 'exact_sum': str(exact),
        'sequential_float_sum': sequential, 'fsum': accurate,
        'sequential_absolute_error': str(abs(Fraction(sequential) - exact)),
        'fsum_absolute_error': str(abs(Fraction(accurate) - exact)),
    }


def close_finite(a, b, *, rel_tol, abs_tol):
    """Explicit finite-value comparison; tolerances must be justified elsewhere."""
    for value in (a, b, rel_tol, abs_tol):
        if type(value) not in (int, float):
            raise ValueError('values and tolerances must be finite int/float numbers, not bool')
        try:
            finite = math.isfinite(value)
        except OverflowError as error:
            raise ValueError('number exceeds this float comparison contract') from error
        if not finite:
            raise ValueError('values and tolerances must be finite')
    if not 0 <= rel_tol < 1 or abs_tol < 0:
        raise ValueError('require 0 <= rel_tol < 1 and abs_tol >= 0')
    return math.isclose(a, b, rel_tol=rel_tol, abs_tol=abs_tol)


def make_report():
    """Fixed original demonstrations; source snapshot preserves their inputs."""
    return {
        'schema_version': 1,
        'worked': difference_case('1000000000000.126', '1000000000000.125'),
        'quiz': difference_case('1000000000000.128', '1000000000000.125'),
        'project': difference_case('1000000000000.130', '1000000000000.125'),
        'recentered_project': difference_case('0.130', '0.125'),
        'exact_binary': difference_case('17.375', '17.125'),
        'order_sensitive': sum_case(['18014398509481984', '3', '-18014398509481984']),
        'reordered': sum_case(['18014398509481984', '-18014398509481984', '3']),
        'lost_input': sum_case(['9007199254740993', '-9007199254740992']),
        'near_zero_relative_only': close_finite(0.0, 2e-9, rel_tol=.01, abs_tol=0.0),
        'near_zero_absolute': close_finite(0.0, 2e-9, rel_tol=0.0, abs_tol=3e-9),
        'runtime_float': {'radix':sys.float_info.radix,'mantissa_bits':sys.float_info.mant_dig},
    }


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


def run_lab(new_directory):
    """Create a new evidence folder; retain partial output if a later write fails."""
    report = make_report()
    source = Path(__file__).resolve().read_bytes()
    payloads = {'report.json':json_bytes(report), 'numerical_lab.py':source}
    target = Path(new_directory)
    target.mkdir(exist_ok=False)
    for name, raw in payloads.items():
        with (target/name).open('xb') as handle:
            handle.write(raw)
    manifest = {
        'status':'complete', 'python':platform.python_version(),
        'implementation':platform.python_implementation(),
        'output_argument':str(new_directory), 'invocation_argv':list(sys.argv),
        'files':{name:hashlib.sha256(raw).hexdigest() for name,raw in payloads.items()},
        'limits':'Known owned folder; no concurrent source edits. Validate JSON and file hashes. Byte consistency is not authenticity or scientific validity.',
    }
    with (target/'run.json').open('xb') as handle:
        handle.write(json_bytes(manifest))
    return report


def main(argv):
    if len(argv) != 1:
        print('Usage: python3 numerical_lab.py NEW_RUN_DIRECTORY',file=sys.stderr)
        return 2
    try:
        report = run_lab(argv[0])
    except (OSError,ValueError) as error:
        print(f'Run failed: {error}. Preserve any partial output and choose a new directory.',file=sys.stderr)
        return 2
    print('Completed new run:',argv[0])
    print('Worked absolute error:',report['worked']['absolute_error'])
    print('Worked relative error:',report['worked']['relative_error'])
    return 0


if __name__ == '__main__':
    raise SystemExit(main(sys.argv[1:]))
