#!/usr/bin/env python3
"""Retrospective selection using only single-substitution GFP brightness measurements.

Predeclared rule: rank pairs by the average of the two single-substitution scores.
Break score ties lexicographically by pair name. Held-out double scores are used only
for evaluation. The mean is a ranking score, not a calibrated brightness prediction.
The unmeasured choice uses the identical rule and excludes pairs in the frozen file.
"""
import argparse
import csv
import hashlib
import io
import itertools
import json
import math
import random
import statistics
import urllib.request
from collections import Counter
from pathlib import Path

DATASET = "https://huggingface.co/datasets/OATML-Markslab/ProteinGym_v0.1/resolve/main/ProteinGym_substitutions/GFP_AEQVI_Sarkisyan_2016.csv"
SHA256 = "dcfe5eb754186eb9eb3a2fe7889d83d791640963a4512b55e91e3c3d4ac65eb2"
SEED = 20261124


def average_ranks(values):
    """Return one-based, ascending ranks, averaging ties."""
    order = sorted(range(len(values)), key=values.__getitem__)
    ranks = [0.0] * len(values)
    start = 0
    while start < len(order):
        end = start + 1
        while end < len(order) and values[order[end]] == values[order[start]]:
            end += 1
        for idx in order[start:end]:
            ranks[idx] = (start + 1 + end) / 2
        start = end
    return ranks


def position(mutation):
    return int(mutation[1:-1])


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--source", type=Path, help="optional local copy of the pinned CSV")
    parser.add_argument("--output-dir", type=Path, default=Path("."))
    args = parser.parse_args()
    if args.source:
        raw = args.source.read_bytes()
    else:
        with urllib.request.urlopen(DATASET, timeout=60) as response:
            raw = response.read()
    if hashlib.sha256(raw).hexdigest() != SHA256:
        raise ValueError("Source checksum differs from the frozen assay.")
    singles = {}
    doubles = {}
    sizes = Counter()
    for row in csv.DictReader(io.StringIO(raw.decode())):
        parts = sorted(row["mutant"].split(":"), key=position)
        score = float(row["DMS_score"])
        sizes[len(parts)] += 1
        if len(parts) == 1:
            singles[parts[0]] = score
        elif len(parts) == 2:
            doubles[":".join(parts)] = score
    assert len(singles) == sizes[1] and len(doubles) == sizes[2]

    evaluated = []
    best_unmeasured = None
    unmeasured_count = 0
    for a, b in itertools.combinations(sorted(singles, key=position), 2):
        if position(a) == position(b):
            continue
        name = f"{a}:{b}"
        score = (singles[a] + singles[b]) / 2
        if name in doubles:
            evaluated.append((score, name, singles[a], singles[b], doubles[name]))
        else:
            unmeasured_count += 1
            key = (-score, name)
            if best_unmeasured is None or key < best_unmeasured[0]:
                best_unmeasured = (key, name, singles[a], singles[b], score)
    evaluated.sort(key=lambda row: (-row[0], row[1]))
    actual = [row[4] for row in evaluated]
    predicted = [row[0] for row in evaluated]
    top = actual[:10]
    ranks = average_ranks(actual)
    # Nearest-rank 90th percentile, pooled over eligible double mutants.
    threshold = sorted(actual)[math.ceil(0.9 * len(actual)) - 1]
    upper_fraction = sum(v >= threshold for v in actual) / len(actual)
    sample = random.Random(SEED).sample(evaluated, 10)
    _, name, a, b, candidate_score = best_unmeasured
    summary = {
        "sources": {"paper": "https://www.nature.com/articles/nature17995",
                    "frozen_assay": DATASET, "sha256": SHA256},
        "method": "Score a pair by averaging the measured assay scores of its two single substitutions. Sort descending with alphabetical pair names breaking ties. All double outcomes are withheld from scoring.",
        "units": "Observed values are the published GFP log-fluorescence assay scores (higher is brighter). Pair scores rank candidates and are not calibrated brightness predictions.",
        "assay_rows": sum(sizes.values()), "singles": len(singles),
        "all_measured_doubles": len(doubles), "eligible_doubles": len(evaluated),
        "eligible_unmeasured_pairs": unmeasured_count,
        "top_ten_mean": statistics.mean(top), "top_ten_median": statistics.median(top),
        "all_eligible_mean": statistics.mean(actual), "all_eligible_median": statistics.median(actual),
        "expected_random_ten_mean": statistics.mean(actual), "expected_random_ten_upper_decile_count": 10 * upper_fraction,
        "upper_decile_threshold": threshold, "top_ten_upper_decile_count": sum(v >= threshold for v in top),
        "spearman_rho": statistics.correlation(average_ranks(predicted), ranks),
        "random_example": {"seed": SEED, "mean": statistics.mean(row[4] for row in sample),
                           "variants": [row[1] for row in sample]},
        "top_ten": [{"rank": i, "mutant": row[1], "score": row[0], "observed": row[4]} for i, row in enumerate(evaluated[:10], 1)],
        "unmeasured_candidate": {"mutant": name, "single_a_score": a, "single_b_score": b,
                                 "rank_score": candidate_score, "observed": None},
        "limits": "Retrospective single-assay test on pairs whose two singles were measured. The scoring rule ignores interactions. Unmeasured means absent as a double from this dataset only. No new fluorescence measurement has been made."
    }
    args.output_dir.mkdir(parents=True, exist_ok=True)
    with (args.output_dir / "gfp-check.csv").open("w", newline="") as stream:
        writer = csv.writer(stream, lineterminator="\n")
        writer.writerow(["predicted_rank", "mutant", "single_a_score", "single_b_score",
                         "ranking_score", "observed_log_fluorescence", "observed_rank_best_first"])
        for i, (score, pair, first, second, observed) in enumerate(evaluated, 1):
            writer.writerow([i, pair, first, second, score, observed, len(ranks) + 1 - ranks[i - 1]])
    (args.output_dir / "gfp-summary.json").write_text(json.dumps(summary, indent=2) + "\n")


if __name__ == "__main__":
    main()
