# Rank one comparison by a values file, with the engine's rules written out in Python.
# Run: python score.py banking.json my-values.json
import json
import math
import sys

MIN_COVERAGE = 0.25


def score(option, criteria, weights):
    """The score of one option, or None when too little of the weight has facts."""
    total = weighted = known = 0
    cap = None
    for c in criteria:
        w = weights.get(c["key"], 0)
        if w <= 0:
            continue
        total += w
        s = option["scores"].get(c["key"])
        if s is None:
            continue
        weighted += w * s
        known += w
        # A value weighted 4 or 5 with a fact of 20 or less caps the score at 49,
        # unless the criterion is a label check, where 0 means no label was found.
        if w >= 4 and s <= 20 and c.get("tier") != "certified":
            cap = s if cap is None else min(cap, s)
    if not known or not total or known / total < MIN_COVERAGE:
        return None
    coverage = known / total
    # Missing facts pull the score toward 50. floor(x + 0.5) rounds halves up, as JavaScript does.
    raw = math.floor(weighted / known * coverage + 50 * (1 - coverage) + 0.5)
    return {"score": 49 if cap is not None and raw > 49 else raw, "coverage": coverage}


def apply_values(values, mapping):
    """Weights for this comparison's criteria, and the strong values it has no place for."""
    weights, dropped = {}, []
    for value, w in values["values"].items():
        if value in mapping:
            weights[mapping[value]] = max(w, weights.get(mapping[value], 0))
        elif w >= 4:
            dropped.append((value, w))
    return weights, dropped


if __name__ == "__main__":
    with open(sys.argv[1], encoding="utf-8") as f:
        data = json.load(f)
    with open(sys.argv[2], encoding="utf-8") as f:
        values = json.load(f)

    # Which of this comparison's criteria each shared value stands for. You write this per comparison.
    MAP = {"planet": "environment", "people": "ethics", "openness": "transparency", "access": "fees"}
    weights, dropped = apply_values(values, MAP)

    ranked = [(p, score(p, data["criteria"], weights)) for p in data["products"]]
    ranked = sorted([r for r in ranked if r[1]], key=lambda r: (-r[1]["score"], r[0]["code"]))

    for p, s in ranked[:5]:
        print(f"{s['score']:>3}  {p['name']} (facts for {math.floor(s['coverage'] * 100 + 0.5)}% of the weight)")
    print(f"{len(data['products']) - len(ranked)} of {len(data['products'])} have too few facts to score")
    for value, w in dropped:
        print(f"{value} matters to you ({w}) but this comparison has no criterion for it")
