"""Score frozen stopping decisions on the queue owner's machine."""

import argparse
import hashlib
import json
from math import fsum, isfinite
from pathlib import Path


def finite_number(value):
    return type(value) in (int, float) and isfinite(value)


def final_regret(reference_errors, finished_errors):
    return min(finished_errors) - min(reference_errors) if finished_errors else None


def score(packet):
    campaigns = packet["campaigns"]
    if not campaigns or len({row["id"] for row in campaigns}) != len(campaigns):
        raise ValueError("Provide campaigns with unique IDs")
    policies = set(campaigns[0]["policies"])
    if not {"incumbent", "slime"} <= policies:
        raise ValueError("Provide incumbent and slime decisions")

    totals = {name: {"costs": [], "winner_losses": 0, "no_full_horizon": 0, "worst_regret": 0.0}
              for name in sorted(policies)}
    for campaign in campaigns:
        trials = campaign["trials"]
        if len(trials) < 2 or set(campaign["policies"]) != policies:
            raise ValueError("Campaigns need at least two trials and identical comparator lists")
        errors = {}
        for trial, receipt in trials.items():
            error = receipt["final_error"]
            meter = receipt["cumulative_device_seconds"]
            if not finite_number(error) or not 0 <= error <= 1:
                raise ValueError("Final errors must be finite and in [0, 1]")
            if (not meter or any(not finite_number(t) or t < 0 for t in meter)
                    or any(current < previous for previous, current in zip(meter, meter[1:]))
                    or meter[-1] <= 0):
                raise ValueError("Device seconds must be nondecreasing and positive at the horizon")
            errors[trial] = error
        for name, decision in campaign["policies"].items():
            checkpoints = decision["last_checkpoint"]
            overhead = decision["overhead_device_seconds"]
            if set(checkpoints) != set(trials) or not finite_number(overhead) or overhead < 0:
                raise ValueError("Provide all trial cutoffs and nonnegative metered overhead")
            finished = []
            costs = [overhead]
            for trial, cutoff in checkpoints.items():
                meter = trials[trial]["cumulative_device_seconds"]
                if type(cutoff) is not int or not 0 <= cutoff <= len(meter):
                    raise ValueError("Checkpoint is outside the trial horizon")
                if cutoff:
                    costs.append(meter[cutoff - 1])
                if cutoff == len(meter):
                    finished.append(errors[trial])
            row = totals[name]
            row["costs"].append(fsum(costs))
            regret = final_regret(errors.values(), finished)
            if regret is None:
                row["no_full_horizon"] += 1
                row["winner_losses"] += 1
                continue
            row["winner_losses"] += regret > 0
            row["worst_regret"] = max(row["worst_regret"], regret)

    reference = fsum(totals["incumbent"]["costs"])
    if reference <= 0:
        raise ValueError("Incumbent must use positive device time to estimate relative savings")
    for row in totals.values():
        used = fsum(row.pop("costs"))
        if row["no_full_horizon"]:
            row["worst_regret"] = None
        row["projected_device_hours"] = used / 3600
        row["projected_device_hours_avoided_vs_incumbent"] = (reference - used) / 3600
        row["projected_fraction_avoided_vs_incumbent"] = (reference - used) / reference
    return {"scope": "shadow projection from metered checkpoints",
            "device_class": packet["device_class"],
            "campaigns": len(campaigns),
            "policies": totals}


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("owner_packet", type=Path)
    args = parser.parse_args()
    raw = args.owner_packet.read_bytes()
    receipt = score(json.loads(raw))
    receipt["owner_packet_sha256"] = hashlib.sha256(raw).hexdigest()
    print(json.dumps(receipt, indent=2, allow_nan=False))
