"""Development challenger: keep a third run alive for a second decision."""

import argparse
from datetime import datetime, timezone
import hashlib
import json
from math import isfinite
from pathlib import Path
from statistics import median


def rank_prefixes(prefixes, count, lookback):
    lengths = {len(values) for values in prefixes.values()}
    if len(lengths) != 1 or min(lengths) < lookback:
        raise ValueError("Compare complete prefixes at the same checkpoint")
    return sorted(prefixes, key=lambda key: (median(prefixes[key][-lookback:]), key))[:count]


POLICIES = ("two-decisions-v1", "two-finalists-v1")
EARLY_SCREEN_POLICY = "two-finalists-screen12-v1"


def stage_checkpoints(horizon, policy):
    if policy == POLICIES[0]:
        return 16, (horizon + 16) // 2, 1
    screen = 12 if policy == EARLY_SCREEN_POLICY else 16
    return screen, screen + max(1, (horizon - screen) // 4), 2


def two_decisions(curves, policy=POLICIES[0]):
    horizon = len(next(iter(curves.values())))
    screen, checkpoint, finalists = stage_checkpoints(horizon, policy)
    extended = rank_prefixes({k: v[:screen] for k, v in curves.items()}, len(curves) - 1, 1)
    finish = rank_prefixes({k: curves[k][:checkpoint] for k in extended}, finalists, 5)
    return {k: horizon if k in finish else checkpoint if k in extended else screen for k in curves}


def forecast(path, policy=POLICIES[0]):
    raw = path.read_bytes()
    request = json.loads(raw)
    required = {"request_id", "horizon", "stage", "prefixes"}
    if not isinstance(request, dict) or not required <= request.keys() <= required | {"candidate_count"}:
        raise ValueError("Expected request_id, horizon, stage, observed prefixes and optional candidate_count")
    horizon = request["horizon"]
    if type(horizon) is not int or not 18 <= horizon <= 100:
        raise ValueError("Horizon must be a fixed integer from 18 through 100 anchors")
    candidate_count = request.get("candidate_count", 4)
    if type(candidate_count) is not int or candidate_count not in (4, 5):
        raise ValueError("Freeze the candidate count at four or five before the first decision")
    prefixes = request["prefixes"]
    if not isinstance(prefixes, dict) or not all(key and isinstance(row, list) and all(
        isinstance(v, (int, float)) and isfinite(v) and 0 <= v <= 1 for v in row
    ) for key, row in prefixes.items()):
        raise ValueError("Expected named observed error prefixes in [0, 1]")
    screen, second_checkpoint, finalists = stage_checkpoints(horizon, policy)
    extended = candidate_count - 1
    expected = {
        "screen": (candidate_count, screen, extended, 1, second_checkpoint),
        "finish": (extended, second_checkpoint, finalists, 5, horizon),
    }
    width, checkpoint, count, lookback, next_anchor = expected[request["stage"]]
    if len(prefixes) != width or any(len(row) != checkpoint for row in prefixes.values()):
        raise ValueError(f"This stage requires {width} prefixes of exactly {checkpoint} anchors")
    advance = rank_prefixes(prefixes, count, lookback)
    return {
        "policy": policy,
        "forecast_utc": datetime.now(timezone.utc).isoformat(timespec="seconds"),
        "request_sha256": hashlib.sha256(raw).hexdigest(),
        "request_id": request["request_id"],
        "advance_to": next_anchor,
        "advance": advance,
        "park": sorted(set(prefixes) - set(advance)),
    }


def replay_development(policy):
    from replay import HERE, load_panel, measure

    rows = []
    for cell, curves in load_panel().items():
        counts = two_decisions(curves, policy)
        rows.append({"cell": cell, "prefixes": [[*k, n] for k, n in sorted(counts.items())],
                     **measure(curves, counts)})
    summary = {"fits_avoided": sum(r["fits_avoided"] for r in rows),
               "final_winners_lost": sum(r["final_winner_lost"] for r in rows),
               "worst_final_regret": max(r["final_regret"] for r in rows)}
    payload = {"scope": "exploratory development exercise on exposed archives",
               "summary": summary, "cells": rows}
    filename = "race-dev.json" if policy == POLICIES[0] else f"{policy}-dev.json"
    (HERE / filename).write_text(json.dumps(payload, indent=2) + "\n")
    print(json.dumps(summary))


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--prefixes", type=Path, help="Issue a staged decision from observed prefixes only")
    parser.add_argument("--policy", choices=(*POLICIES, EARLY_SCREEN_POLICY), default=POLICIES[0])
    args = parser.parse_args()
    if args.prefixes:
        print(json.dumps(forecast(args.prefixes, args.policy), indent=2))
    else:
        replay_development(args.policy)
