"""Derive Table 3 measures from matched, separately recorded probability vectors."""

import math
import statistics


def normalize(values, state_keys):
    if set(values) != set(state_keys) or len(state_keys) < 2:
        raise ValueError("A complete matched vector with at least two states is required")
    if any(isinstance(v, bool) or not isinstance(v, (int, float))
           or not math.isfinite(v) or not 0 <= v <= 1 for v in values.values()):
        raise ValueError("Probabilities must be finite values in [0, 1]")
    total = math.fsum(values.values())
    if abs(total - 1) > 1e-6:
        raise ValueError("Raw posterior vector fails the sum-to-one check")
    return {key: values[key] / total for key in state_keys}


def summarize(raw_vectors, state_keys):
    if not raw_vectors:
        raise ValueError("No documented vectors were supplied")
    normalized = [normalize(v, state_keys) for v in raw_vectors]
    mean = {key: statistics.mean(v[key] for v in normalized) for key in state_keys}
    statistics_by_state = {}
    for key in state_keys:
        fields = {}
        for label, vectors in (("before", raw_vectors), ("after", normalized)):
            values = [v[key] for v in vectors]
            fields[f"sd_{label}_normalization"] = statistics.stdev(values) if len(values) > 1 else None
            fields[f"range_{label}_normalization"] = max(values) - min(values) if len(values) > 1 else None
        statistics_by_state[key] = fields
    summary = {
        "max_" + field: max(s[field] for s in statistics_by_state.values())
        if len(raw_vectors) > 1 else None
        for field in next(iter(statistics_by_state.values()))
    }
    ordered = sorted(mean.values(), reverse=True)
    summary.update(
        maximum_probability=ordered[0],
        top_two_gap=ordered[0] - ordered[1],
        normalized_entropy=min(1.0, max(0.0, -math.fsum(p * math.log(p) for p in mean.values() if p > 0)
                                       / math.log(len(mean)))),
    )
    return {"raw_vectors": raw_vectors, "normalized_vectors": normalized,
            "mean_vector": mean, "state_statistics": statistics_by_state,
            "summary": summary, "n_runs": len(raw_vectors)}


def rank_groups(vector, tolerance):
    if tolerance < 0 or not math.isfinite(tolerance):
        raise ValueError("Ranking tolerance must be finite and nonnegative")
    ordered = sorted(vector, key=lambda key: (-vector[key], key))
    groups = []
    for key in ordered:
        # Anchor each group at its maximum; adjacent-gap chaining can create false ties.
        if not groups or vector[groups[-1][0]] - vector[key] > tolerance:
            groups.append([key])
        else:
            groups[-1].append(key)
    return groups


def compare(a, b):
    if set(a) != set(b):
        raise ValueError("Route comparison requires identical candidate-state identities")
    normalize(a, list(a))
    normalize(b, list(a))
    differences = [abs(a[key] - b[key]) for key in a]
    metrics = {
        "maximum_absolute_difference": max(differences),
        "total_variation": math.fsum(differences) / 2,
        "euclidean_distance": math.sqrt(math.fsum(d * d for d in differences)),
        "hellinger_distance": math.sqrt(math.fsum(
            (math.sqrt(a[key]) - math.sqrt(b[key])) ** 2 for key in a) / 2),
    }
    rankings = {}
    for rule, tolerance in (("exact", 0), ("tolerance", 1e-6)):
        ga, gb = rank_groups(a, tolerance), rank_groups(b, tolerance)
        metrics["highest_set_agreement_" + rule] = set(ga[0]) == set(gb[0])
        metrics["complete_ranking_agreement_" + rule] = [set(g) for g in ga] == [set(g) for g in gb]
        rankings[rule] = {"highest_set_a": ga[0], "highest_set_b": gb[0],
                          "groups_a": ga, "groups_b": gb}
    return {"metrics": metrics, "ranking_details": rankings,
            "ranking_rule_id": "group_max_anchor_exact_0_tolerance_1e-6"}
