"""Original TMP-SCI-204 Unit5 fictional tabular analysis, standard library only."""
import argparse
from fractions import Fraction
import hashlib
import json
from pathlib import Path
import platform
import re
import sys

MAX_BYTES=1048576
ID=re.compile(r'[A-Za-z0-9_-]{1,32}\Z')

def identifier(value):
    return type(value) is str and ID.fullmatch(value) is not None

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

def validate_packet(packet):
    if type(packet) is not dict or set(packet)!={'sites','samples'}:raise ValueError('packet needs exactly sites and samples')
    sites,samples=packet['sites'],packet['samples']
    if type(sites) is not list or len(sites)>100:raise ValueError('at most 100 site rows')
    if type(samples) is not list or len(samples)>1000:raise ValueError('at most 1000 sample rows')
    lookup={}
    for site in sites:
        if type(site) is not dict or set(site)!={'site_id','label'}:raise ValueError('site fields must be site_id and label')
        sid,label=site['site_id'],site['label']
        if not identifier(sid) or sid in lookup:raise ValueError('site IDs must be valid and unique')
        if type(label) is not str or not label.strip() or len(label)>80 or not label.isprintable():raise ValueError('site labels must be printable nonblank text, at most 80 characters')
        lookup[sid]=label
    seen=set()
    for row in samples:
        if type(row) is not dict or set(row)!={'sample_id','site_id','value_ug_l','qc'}:raise ValueError('sample fields differ from the data dictionary')
        if not identifier(row['sample_id']) or row['sample_id'] in seen:raise ValueError('sample IDs must be valid and globally unique')
        seen.add(row['sample_id'])
        if not identifier(row['site_id']) or row['site_id'] not in lookup:raise ValueError('sample references an unknown or invalid site ID')
        v=row['value_ug_l']
        if v is not None and (type(v) is not int or not 0<=v<=1000000):raise ValueError('value must be integer 0–1000000 or null')
        if type(row['qc']) is not str or row['qc'] not in {'accepted','flagged'}:raise ValueError('qc must be accepted or flagged')
    return lookup

def analyse_packet(packet,include_flagged=False,missing_interval=None):
    lookup=validate_packet(packet)
    if type(include_flagged) is not bool:raise ValueError('include_flagged must be bool')
    if missing_interval is not None:
        if type(missing_interval) is not tuple or len(missing_interval)!=2:raise ValueError('missing interval must be a two-integer tuple')
        lo,hi=missing_interval
        if any(type(v) is not int or not 0<=v<=1000000 for v in (lo,hi)) or lo>hi:raise ValueError('invalid missing-value interval')
    groups={sid:{'site_id':sid,'label':label,'planned':0,'eligible':0,'included':0,'sum_ug_l':0,'excluded_flagged':0,'excluded_missing':0} for sid,label in sorted(lookup.items())}
    audit=[]
    for position,row in enumerate(packet['samples'],start=1):
        group=groups[row['site_id']];group['planned']+=1
        if row['qc']=='flagged' and not include_flagged:
            decision='flagged';group['excluded_flagged']+=1
        else:
            group['eligible']+=1
            if row['value_ug_l'] is None:
                decision='missing';group['excluded_missing']+=1
            else:
                decision='included';group['included']+=1;group['sum_ug_l']+=row['value_ug_l']
        audit.append({'row_number':position,'sample_id':row['sample_id'],'site_id':row['site_id'],'decision':decision})
    site_means=[]
    for group in groups.values():
        mean=Fraction(group['sum_ug_l'],group['included']) if group['included'] else None
        group['mean_ug_l']=str(mean) if mean is not None else None
        if mean is not None:site_means.append(mean)
    included=sum(g['included'] for g in groups.values());eligible=sum(g['eligible'] for g in groups.values())
    total=sum(g['sum_ug_l'] for g in groups.values());missing=eligible-included
    scenario=None
    if missing_interval is not None:
        lo,hi=missing_interval
        scenario={'interval_ug_l':[lo,hi],'missing_eligible':missing,'denominator':eligible,
                  'lower_mean_ug_l':str(Fraction(total+missing*lo,eligible)) if eligible else None,
                  'upper_mean_ug_l':str(Fraction(total+missing*hi,eligible)) if eligible else None}
    return {'schema_version':1,'policy':{'include_flagged':include_flagged,'exclusion_priority':['flagged_if_disallowed','missing']},
            'planned':len(packet['samples']),'eligible':eligible,'included':included,'sum_ug_l':total,
            'pooled_mean_ug_l':str(Fraction(total,included)) if included else None,
            'mean_of_observed_site_means_ug_l':str(sum(site_means,Fraction(0))/len(site_means)) if site_means else None,
            'sites_with_observations':len(site_means),'declared_sites':len(groups),
            'excluded_by_reason':{'flagged':sum(g['excluded_flagged'] for g in groups.values()),'missing':missing},
            'sites':list(groups.values()),'audit':audit,'missing_scenario':scenario,
            'interpretation':'Descriptive summaries of fictional supplied rows. Exact arithmetic is not exact measurement, random sampling, causation or confidence.'}

def text_summary(report):
    show=lambda value:'undefined (no included observations)' if value is None else value
    lines=['Fictional sample analysis; concentrations in micrograms per litre.',
           f"Include flagged sensitivity: {report['policy']['include_flagged']}",
           f"Planned {report['planned']}; QC-eligible {report['eligible']}; included {report['included']}.",
           f"Excluded flagged {report['excluded_by_reason']['flagged']}; excluded missing {report['excluded_by_reason']['missing']}.",
           'Pooled observed mean: '+show(report['pooled_mean_ug_l']),
           f"Mean of observed-site means ({report['sites_with_observations']} of {report['declared_sites']} declared sites): "+show(report['mean_of_observed_site_means_ug_l'])]
    for g in report['sites']:
        lines.append(f"Site {g['site_id']} ({g['label']}): planned {g['planned']}, included {g['included']}, sum {g['sum_ug_l']}, mean {show(g['mean_ug_l'])}.")
    if report['missing_scenario'] is not None:lines.append('Conditional missing-value scenario: '+json.dumps(report['missing_scenario'],sort_keys=True))
    lines.append(report['interpretation'])
    return '\n'.join(lines)+'\n'

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

def run_analysis(input_path,new_directory,include_flagged=False,missing_interval=None):
    with Path(input_path).open('rb') as handle:raw=handle.read(MAX_BYTES+1)
    report=analyse_packet(parse_packet(raw),include_flagged,missing_interval)
    source=Path(__file__).resolve().read_bytes()
    payloads={'input.json':raw,'report.json':json_bytes(report),'summary.txt':text_summary(report).encode('utf-8'),'tabular_analysis.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),
              'analysis_options':{'include_flagged':include_flagged,'missing_interval':list(missing_interval) if missing_interval is not None else None},
              'files':{name:hashlib.sha256(data).hexdigest() for name,data in payloads.items()},
              'limits':'Known owned files; no concurrent source edits. Parse manifest and check all four known hashes. Non-atomic; byte consistency is not authenticity or scientific validity.'}
    with (output/'run.json').open('xb') as handle:handle.write(json_bytes(manifest))
    return report

def main(argv):
    parser=argparse.ArgumentParser(description='Analyse a fictional packet into a new owned directory.',allow_abbrev=False)
    parser.add_argument('input');parser.add_argument('output')
    parser.add_argument('--include-flagged',action='store_true')
    parser.add_argument('--missing-range',nargs=2,type=int,metavar=('LOW','HIGH'))
    args=parser.parse_args(argv)
    try:report=run_analysis(args.input,args.output,args.include_flagged,tuple(args.missing_range) if args.missing_range is not None else None)
    except (OSError,ValueError) as error:
        print(f'Run failed: {error}. Preserve any partial output; choose a new directory.',file=sys.stderr);return 2
    print('Completed new run:',args.output)
    print('Pooled observed mean:',report['pooled_mean_ug_l'])
    return 0

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