"""Replay the frozen five-trial policies on public PD1 image workloads."""

import argparse
from collections import Counter, defaultdict
import gzip
from hashlib import file_digest, sha256
from itertools import combinations
import json
from math import fsum
from pathlib import Path

import ray

from asha_shadow import RAY_VERSION, decisions
from race import EARLY_SCREEN_POLICY, POLICIES, stage_checkpoints, two_decisions
from score_shadow import finite_number, final_regret


IMAGE_DATASETS = {"cifar10", "cifar100", "fashion_mnist", "imagenet", "mnist", "svhn_no_extra"}
WIDTH = 5
COHORT_SALT = "slime-pd1-five-trial-v1"
TRACE_FIELDS = ("trial_dir", "status", "global_step", "steps_per_sec", "valid/error_rate")


def asha_cutoffs(curves, times):
    horizon = len(next(iter(curves.values())))
    arrivals = sorted(
        (seconds, key, checkpoint)
        for key, readings in times.items()
        for checkpoint, seconds in enumerate(readings, start=1)
    )
    terminal = {}
    events = (
        {"trial_id": key, "checkpoint": checkpoint, "error": curves[key][checkpoint - 1]}
        for _, key, checkpoint in arrivals if key not in terminal
    )
    config = {"campaign_id": "pd1-replay", "trial_ids": sorted(curves), "horizon": horizon,
              "grace_period": 16, "reduction_factor": 2}
    for receipt in decisions(config, events):
        if receipt["action"] != "continue":
            terminal[receipt["trial_id"]] = receipt["checkpoint"]
    if set(terminal) != set(curves):
        raise RuntimeError("ASHA left a trial without a terminal receipt")
    return terminal


def read_trace(row, grid, indices):
    errors = row["valid/error_rate"]
    rates = row["steps_per_sec"]
    if (row["status"] != "done" or tuple(row["global_step"] or ()) != grid
            or errors is None or rates is None or len(errors) != len(grid) or len(rates) != len(grid)):
        return None
    if any(not finite_number(error) or not 0 <= error <= 1 for error in errors):
        return None
    elapsed = 0.0
    times = []
    for step, previous_step, rate in zip(grid, (0, *grid[:-1]), rates):
        if not finite_number(rate) or rate <= 0 or step <= previous_step:
            return None
        elapsed += (step - previous_step) / rate
        times.append(elapsed)
    return [errors[i] for i in indices], [times[i] for i in indices]


def winner_preserving_floor(curves, times, checkpoint):
    """Cost if every trial reaches the screen and only the cheapest winner continues."""
    best_error = min(curve[-1] for curve in curves.values())
    prefix_cost = fsum(readings[checkpoint - 1] for readings in times.values())
    winner_tail = min(readings[-1] - readings[checkpoint - 1]
                      for key, readings in times.items() if curves[key][-1] == best_error)
    return prefix_cost + winner_tail


def staged_winner_preserving_floor(curves, times, policy):
    """Cheapest legal assignment to the policy's fixed stages with a finalist winner."""
    horizon = len(next(iter(curves.values())))
    screen, second, finalist_count = stage_checkpoints(horizon, policy)
    best_error = min(curve[-1] for curve in curves.values())
    prefix_cost = fsum(readings[screen - 1] for readings in times.values())
    second_cost = {key: readings[second - 1] - readings[screen - 1]
                   for key, readings in times.items()}
    finish_cost = {key: readings[-1] - readings[screen - 1]
                   for key, readings in times.items()}
    second_only_count = len(curves) - 1 - finalist_count
    tails = []
    for finalists in combinations(curves, finalist_count):
        if all(curves[key][-1] > best_error for key in finalists):
            continue
        other_costs = sorted(cost for key, cost in second_cost.items() if key not in finalists)
        tails.append(fsum([*(finish_cost[key] for key in finalists),
                           *other_costs[:second_only_count]]))
    return prefix_cost + min(tails)


def run(path, include_screen_bound=False, include_early_screen=False, include_staged_bound=False):
    if ray.__version__ != RAY_VERSION:
        raise RuntimeError(f"Use Ray {RAY_VERSION}, found {ray.__version__}")
    challengers = (*POLICIES, EARLY_SCREEN_POLICY) if include_early_screen else POLICIES
    groups = defaultdict(list)
    with gzip.open(path, "rt") as source:
        for line in source:
            row = json.loads(line)
            if row["dataset"] not in IMAGE_DATASETS:
                continue
            task = (row["dataset"], row["model"], row["hps.batch_size"])
            groups[task].append({field: row[field] for field in TRACE_FIELDS})

    tasks = []
    for task, rows in sorted(groups.items()):
        grids = Counter(tuple(row["global_step"]) for row in rows
                        if row["status"] == "done" and row["global_step"])
        if not grids:
            continue
        grid = min(grids, key=lambda value: (-grids[value], value))
        horizon = min(len(grid), 100)
        if horizon < 18:
            tasks.append({"task": task, "source_reports": len(grid), "source_trials": len(rows),
                          "reason": "fewer than 18 reports in modal completed grid"})
            continue
        indices = [i * (len(grid) - 1) // (horizon - 1) for i in range(horizon)]
        ids = [row["trial_dir"] for row in rows]
        if len(set(ids)) != len(ids):
            raise ValueError(f"{task}: duplicate trial IDs in source archive")
        rows.sort(key=lambda row: sha256(f"{COHORT_SALT}/{row['trial_dir']}".encode()).digest())
        policies = ("train-through", "asha", *challengers)
        results = {name: [] for name in policies}
        floors = {checkpoint: [] for checkpoint in (4, 8, 12, 16)}
        staged_floors = {name: [] for name in challengers}
        complete = 0
        for start in range(0, len(rows) - WIDTH + 1, WIDTH):
            traces = [read_trace(row, grid, indices) for row in rows[start:start + WIDTH]]
            if any(trace is None for trace in traces):
                continue
            complete += 1
            curves = {str(i): trace[0] for i, trace in enumerate(traces)}
            times = {str(i): trace[1] for i, trace in enumerate(traces)}
            reference = [curve[-1] for curve in curves.values()]
            cutoffs = {"train-through": dict.fromkeys(curves, horizon),
                       "asha": asha_cutoffs(curves, times)}
            cutoffs.update({name: two_decisions(curves, name) for name in challengers})
            if include_screen_bound:
                for checkpoint, values in floors.items():
                    values.append(winner_preserving_floor(curves, times, checkpoint))
            if include_staged_bound:
                for name, values in staged_floors.items():
                    values.append(staged_winner_preserving_floor(curves, times, name))
            for name, last in cutoffs.items():
                used = fsum(times[key][cutoff - 1] for key, cutoff in last.items())
                regret = final_regret(reference, [curves[key][-1] for key in last if last[key] == horizon])
                results[name].append((used, regret))

        task_result = {"task": task, "source_trials": len(rows), "source_reports": len(grid),
                       "replayed_reports": horizon,
                       "candidate_cohorts": len(rows) // WIDTH, "complete_cohorts": complete}
        if complete:
            costs = {name: fsum(used for used, _ in observations)
                     for name, observations in results.items()}
            task_result["policies"] = {}
            for name, observations in results.items():
                regrets = [regret for _, regret in observations]
                task_result["policies"][name] = {
                    "estimated_elapsed_hours": costs[name] / 3600,
                    "gross_fraction_avoided_vs_train_through": 1 - costs[name] / costs["train-through"],
                    "gross_fraction_avoided_vs_asha": 1 - costs[name] / costs["asha"],
                    "winner_losses": sum(regret is None or regret > 0 for regret in regrets),
                    "no_finalist": regrets.count(None),
                    "worst_final_regret": None if None in regrets else max(regrets),
                }
            if include_screen_bound:
                task_result["winner_preserving_floor_hours"] = {
                    checkpoint: fsum(values) / 3600 for checkpoint, values in floors.items()
                }
            if include_staged_bound:
                task_result["staged_winner_preserving_floor_hours"] = {
                    name: fsum(values) / 3600 for name, values in staged_floors.items()
                }
        tasks.append(task_result)
    with path.open("rb") as source:
        digest = file_digest(source, "sha256").hexdigest()
    return {"scope": "public retrospective replay with estimated elapsed time",
            "source_sha256": digest, "cohort_salt": COHORT_SALT, "ray_version": ray.__version__,
            "asha": {"grace_period": 16, "reduction_factor": 2},
            "tasks": tasks}


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("unmatched_phase1", type=Path)
    parser.add_argument("--screen-bound", action="store_true",
                        help="Also compute optimistic minimum costs for four screen checkpoints")
    parser.add_argument("--early-screen", action="store_true",
                        help="Also replay the report-12 two-finalist challenger")
    parser.add_argument("--staged-bound", action="store_true",
                        help="Also compute optimistic minimum costs for the fixed staged schedules")
    args = parser.parse_args()
    print(json.dumps(run(args.unmatched_phase1, args.screen_bound, args.early_screen, args.staged_bound),
                     indent=2, allow_nan=False))
