"""Prepare participant inputs or score the two-assay BO-2 case GC043-T11."""
from argparse import ArgumentParser
from datetime import datetime
from hashlib import file_digest
import json
from pathlib import Path
from statistics import median


TASK_ID = 'GC043-T11'
ROOT = Path(__file__).resolve().parents[1]
LAB_THRESHOLD = 0.002
FIELD_THRESHOLD = 0.025


def load_rows(path, receipt):
    from openpyxl import load_workbook

    with path.open('rb') as handle:
        if file_digest(handle, 'sha256').hexdigest() != receipt['sha256']:
            raise ValueError(f'{path.name} differs from the audited workbook')
    book = load_workbook(path, read_only=True, data_only=True)
    try:
        return list(book.active.values)
    finally:
        book.close()


def load_case(field_path, lab_path):
    record = json.loads((ROOT / 'content/GC043.json').read_text())
    task = next(t for t in record['tasks'] if t['id'] == TASK_ID)
    field_receipt, lab_receipt = task['data_audit']['evidence']
    field = load_rows(field_path, field_receipt)
    lab = load_rows(lab_path, lab_receipt)
    insertion = next(row for row in lab[1:] if row[0] == 'Dye insertion')
    origin = datetime.combine(insertion[1].date(), insertion[2])
    field = sorted(((row[0] - origin).total_seconds() / 3600, row[1])
                   for row in field[1:] if isinstance(row[0], datetime)
                   and row[0] >= origin and isinstance(row[1], (int, float)))
    assays = {}
    for row in lab[1:]:
        label, hour, concentration = row[0], row[5], row[7]
        if (isinstance(label, str) and label.startswith('BO2-')
                and isinstance(hour, (int, float)) and 0 < hour <= field[-1][0]
                and isinstance(concentration, (int, float))):
            assays.setdefault(hour, []).append(concentration)
    return field, {hour: median(values) for hour, values in sorted(assays.items())}


def first_run(field, length):
    count = 0
    for i, (_, value) in enumerate(field):
        count = count + 1 if value >= FIELD_THRESHOLD else 0
        if count == length:
            return field[i + 1 - length][0]
    raise ValueError(f'No field run of {length} readings at the declared threshold')


def nearest(hours, target):
    return min(hours, key=lambda hour: (abs(hour - target), hour))


def bracket(assays):
    preceding = None
    for hour, concentration in sorted(assays.items()):
        if concentration >= LAB_THRESHOLD:
            return [preceding, hour] if preceding is not None else None
        preceding = hour
    return None


def score(assays, choices, reference):
    if len(set(choices)) != 2 or not all(hour in assays for hour in choices):
        raise ValueError('Choose two distinct elapsed hours from the available assays')
    selected = {hour: assays[hour] for hour in sorted(choices)}
    observed = bracket(selected)
    return {
        'assays_ug_per_l': selected,
        'bracket_hours': observed,
        'width_hours': observed[1] - observed[0] if observed else None,
        'encloses_reference': bool(observed and observed[0] <= reference[0] <= reference[1] <= observed[1]),
    }


def main():
    cli = ArgumentParser(description=__doc__)
    cli.add_argument('field_workbook', type=Path)
    cli.add_argument('lab_workbook', type=Path)
    mode = cli.add_mutually_exclusive_group()
    mode.add_argument('--inputs', action='store_true', help='Show field data and eligible assay hours')
    mode.add_argument('--assay-hours', type=float, nargs=2, help='Score two preselected laboratory sample hours')
    args = cli.parse_args()
    try:
        field, assays = load_case(args.field_workbook, args.lab_workbook)
        result = {'task': TASK_ID}
        if args.inputs:
            result.update(field_readings_hours_ug_per_l=field, available_assay_hours=list(assays))
        else:
            reference = bracket(assays)
            if reference is None:
                raise ValueError('The public laboratory trace does not bracket the threshold')
            choices = args.assay_hours
            if choices is None:
                early, late = first_run(field, 3), first_run(field, 6)
                choices = [nearest(assays, early + fraction * (late - early)) for fraction in (.5, .75)]
            result.update(
                reference_bracket_hours=reference,
                chosen_assays=score(assays, choices, reference),
                fixed_baseline=score(assays, [nearest(assays, target) for target in (60, 120)], reference),
            )
    except (ImportError, OSError, ValueError) as error:
        cli.error(str(error))
    print(json.dumps(result, indent=2, allow_nan=False))


if __name__ == '__main__':
    main()
