"""Original TMP-SCI-204 Unit4: bounded search and exact-model bisection.

Standard library only. Fictional data and owned directories. No network,
installation, source changes, existing-output reuse or automatic deletion.
"""
from fractions import Fraction
import hashlib
import json
import math
from pathlib import Path
import platform
import sys


def first_at_least(values, threshold):
    """Return first original-order hit. Validate the complete list first."""
    if type(values) is not list or len(values)>1000:
        raise ValueError('values must be a list of at most 1000 integers')
    if type(threshold) is not int or not 0<=threshold<=1000000:
        raise ValueError('threshold must be an integer in 0–1000000')
    if any(type(x) is not int or not 0<=x<=1000000 for x in values):
        raise ValueError('every reading must be an integer in 0–1000000')
    for index,value in enumerate(values):
        if value>=threshold:
            return {'index':index,'value':value,'comparisons':index+1,'length':len(values)}
    return {'index':None,'value':None,'comparisons':len(values),'length':len(values)}


def exact_input(value,name,maximum,positive=False):
    if type(value) not in (int,Fraction):
        raise ValueError(f'{name} must be an exact int or Fraction, not float/bool')
    value=Fraction(value)
    if value.denominator>10**9 or value<0 or value>maximum or (positive and value==0):
        raise ValueError(f'{name} is outside its documented magnitude/denominator bounds')
    return value


def halvings_needed(width,tolerance):
    """Exact guaranteed cut count for midpoint error <= tolerance."""
    width=exact_input(width,'width',100,positive=True)
    tolerance=exact_input(tolerance,'tolerance',100,positive=True)
    count=0
    while width/2>tolerance:
        width/=2
        count+=1
    return count


def response(t):
    """Internal exact polynomial; public solver validates its domain first."""
    return t*t+2*t


def bisect_response(target,lower,upper,tolerance,max_halvings):
    """Bracket R(t)=target on 0<=t<=100 using exact rational decisions.

    max_halvings counts interval cuts, not endpoint/candidate evaluations.
    Exact endpoint or midpoint success can therefore occur with zero cuts.
    """
    target=exact_input(target,'target',10200)
    lower=exact_input(lower,'lower',100)
    upper=exact_input(upper,'upper',100)
    tolerance=exact_input(tolerance,'tolerance',100,positive=True)
    if lower>=upper:
        raise ValueError('lower must be strictly less than upper')
    if type(max_halvings) is not int or not 0<=max_halvings<=200:
        raise ValueError('max_halvings must be an integer in 0–200')
    fl,fu=response(lower)-target,response(upper)-target
    if fl>0 or fu<0:
        raise ValueError('the supplied interval does not bracket this target')
    trace=[]
    cuts=0
    def result(status,a,b):
        candidate=(a+b)/2
        return {'target':str(target),'status':status,'converged':status!='budget_exhausted',
                'lower':str(a),'upper':str(b),'candidate':str(candidate),
                'candidate_residual':str(response(candidate)-target),
                'error_bound':str((b-a)/2),'requested_tolerance':str(tolerance),
                'halvings':cuts,'max_halvings':max_halvings,'trace':trace}
    if fl==0:return result('exact_root',lower,lower)
    if fu==0:return result('exact_root',upper,upper)
    while True:
        midpoint=(lower+upper)/2
        fm=response(midpoint)-target
        if fm==0:return result('exact_root',midpoint,midpoint)
        if (upper-lower)/2<=tolerance:return result('tolerance_met',lower,upper)
        if cuts>=max_halvings:return result('budget_exhausted',lower,upper)
        old_lower,old_upper=lower,upper
        if fm<0:
            lower=midpoint
            kept='upper half'
        else:
            upper=midpoint
            kept='lower half'
        cuts+=1
        trace.append({'cut':cuts,'old_lower':str(old_lower),'old_upper':str(old_upper),
                      'midpoint':str(midpoint),'midpoint_residual':str(fm),'kept':kept,
                      'new_lower':str(lower),'new_upper':str(upper)})


def stagnation_demo():
    """Fixed float-spacing demonstration, not a generic root solver."""
    lower=1.0
    upper=math.nextafter(lower,math.inf)
    midpoint=lower+(upper-lower)/2
    return {'lower':lower,'upper':upper,'midpoint':midpoint,
            'half_width':(upper-lower)/2,'requested_tolerance':1e-17,
            'can_shrink':lower<midpoint<upper,
            'meaning':'No distinct representable midpoint; no root or convergence claim.'}


def make_report():
    return {'schema_version':1,
            'search':first_at_least([4,9,7,15,13],12),
            'worked':bisect_response(5,1,2,Fraction(1,128),6),
            'short_budget':bisect_response(5,1,2,Fraction(1,128),4),
            'quiz':bisect_response(7,1,2,Fraction(1,256),7),
            'project':bisect_response(11,2,3,Fraction(1,1000),9),
            'exact_shortcut':bisect_response(8,1,3,Fraction(1,1000),0),
            'float_stagnation':stagnation_demo(),
            '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):
    """New owned folder only; retain partial output after later write failure."""
    report=make_report()
    source=Path(__file__).resolve().read_bytes()
    payloads={'report.json':json_bytes(report),'bounded_algorithms.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),'output_argument':str(new_directory),
              'files':{name:hashlib.sha256(data).hexdigest() for name,data in payloads.items()},
              'limits':'Trusted owned folder; no concurrent source edits. Parse manifest and verify known file hashes. Not atomic, authenticated or scientifically validated.'}
    with (output/'run.json').open('xb') as handle:handle.write(json_bytes(manifest))
    return report


def main(argv):
    if len(argv)!=1:
        print('Usage: python3 bounded_algorithms.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 partial evidence and choose a new directory.',file=sys.stderr)
        return 2
    print('Completed new run:',argv[0])
    print('Worked candidate:',report['worked']['candidate'])
    print('Worked error bound:',report['worked']['error_bound'])
    print('Short-budget status:',report['short_budget']['status'])
    return 0


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