"""Use Ray Tune ASHA to decide from a chronological checkpoint stream."""

from datetime import datetime, timezone
import hashlib
import json
from math import isfinite
import sys
from types import SimpleNamespace

import ray
from ray.tune.schedulers import ASHAScheduler


RAY_VERSION = "2.59.0"


def decisions(config, events):
    fields = {"campaign_id", "trial_ids", "horizon", "grace_period", "reduction_factor"}
    if not isinstance(config, dict) or set(config) != fields:
        raise ValueError("Provide the frozen campaign ID, trials, horizon, grace and reduction factor")
    campaign_id = config["campaign_id"]
    trial_ids = config["trial_ids"]
    horizon = config["horizon"]
    grace = config["grace_period"]
    reduction = config["reduction_factor"]
    if not isinstance(campaign_id, str) or not campaign_id:
        raise ValueError("Campaign ID must be a nonempty string")
    if (not isinstance(trial_ids, list) or not all(isinstance(key, str) and key for key in trial_ids)
            or len(trial_ids) < 2 or len(set(trial_ids)) != len(trial_ids)):
        raise ValueError("Provide at least two unique opaque trial IDs")
    if any(type(n) is not int for n in (horizon, grace, reduction)) or not (1 <= grace < horizon and reduction >= 2):
        raise ValueError("Require integer horizon > grace_period >= 1 and reduction_factor >= 2")
    scheduler = ASHAScheduler(time_attr="checkpoint", metric="error", mode="min",
                              max_t=horizon, grace_period=grace, reduction_factor=reduction, brackets=1)
    trials = {key: SimpleNamespace(trial_id=key) for key in trial_ids}
    for trial in trials.values():
        scheduler.on_trial_add(None, trial)
    last_checkpoint = dict.fromkeys(trial_ids, 0)
    finished = set()

    for event in events:
        if not isinstance(event, dict) or set(event) != {"trial_id", "checkpoint", "error"}:
            raise ValueError("Provide only trial_id, checkpoint and observed error")
        key, checkpoint, error = event["trial_id"], event["checkpoint"], event["error"]
        if not isinstance(key, str) or key not in trials or key in finished:
            raise ValueError("Checkpoint belongs to an unknown or terminal trial")
        if type(checkpoint) is not int or checkpoint != last_checkpoint[key] + 1:
            raise ValueError("Send each trial's checkpoints once, consecutively from one")
        if type(error) not in (int, float) or not isfinite(error) or not 0 <= error <= 1:
            raise ValueError("Observed error must be finite and in [0, 1]")
        result = {"checkpoint": checkpoint, "error": error}
        action = scheduler.on_trial_result(None, trials[key], result)
        if action == scheduler.STOP:
            scheduler.on_trial_complete(None, trials[key], result)
            finished.add(key)
        elif action != scheduler.CONTINUE:
            raise RuntimeError(f"Unexpected ASHA action {action}")
        last_checkpoint[key] = checkpoint
        yield {
            "campaign_id": campaign_id,
            "trial_id": key,
            "checkpoint": checkpoint,
            "action": "complete" if checkpoint == horizon else action.lower(),
        }


def main():
    if ray.__version__ != RAY_VERSION:
        raise ValueError(f"Use pinned Ray {RAY_VERSION}, found {ray.__version__}")
    config_line = sys.stdin.buffer.readline()
    stream_digest = hashlib.sha256(config_line)

    def events():
        for line in sys.stdin.buffer:
            stream_digest.update(line)
            yield json.loads(line)

    for position, receipt in enumerate(decisions(json.loads(config_line), events()), start=1):
        receipt.update(ray_version=RAY_VERSION, observation=position,
                       stream_sha256=stream_digest.hexdigest(),
                       forecast_utc=datetime.now(timezone.utc).isoformat(timespec="seconds"))
        print(json.dumps(receipt, allow_nan=False), flush=True)


if __name__ == "__main__":
    main()
