"""The rating summary a page shows: big number, bars, the four counts, the seven category averages.

The generator NEVER works a rating out from the few reviews printed on the page (that was the bug: the bars came
from the top 3 reviews while the big number came from all of them). It takes ONE summary per school, the same
object the server sends from GET /api/ato/{slug}/public (cloudflare/lib/reviews/rating.mjs, ratingCard):

    {"shown": true, "count": 9, "written": 8, "rated_hi": 8, "certificates": 2, "score": "4.3", "gold": true,
     "bars": [{"stars": 5, "count": 4}, ... {"stars": 1, "count": 0}],
     "categories": [{"key": "org", "label": "Organisation", "score": "4.2", "gold": true, "count": 9}, ...]}

summarise() below is a small mirror of the server's arithmetic. It exists for the tests and for writing example
data. It uses whole fractions, so 4.5 is always exactly 4.5 and "4.0 or more" never fails on a float.
"""
from fractions import Fraction
import datetime as dt

MIN_RATINGS = 3          # REV-011
AGE_DAYS = 7
GOLD_FROM = 4            # NEW-01: raw average 4.0 and up
COLLECTED = ("published", "deleted")      # CORE-01 / REV-055
CATEGORIES = [           # A-30: fixed order and names
    ("org", "Organisation"), ("flt", "Fleet"), ("gnd", "Ground school"), ("ins", "Instructors"),
    ("saf", "Safety culture"), ("val", "Value"), ("avl", "Availability"),
]


def display1(num, den):
    """num/den rounded half up to one decimal, as text: 17/4 -> '4.3', 79/20 -> '4.0'. Integers only (SUG-51)."""
    if not den:
        return None
    tenths = (20 * num + den) // (2 * den)
    return f"{tenths // 10}.{tenths % 10}"


def bar_of(overall):
    """Which of the 5-to-1 bars a review falls in: its overall rounded half UP (SUG-50). 4.5 -> 5, 3.5 -> 4.
    Python's round() rounds halves to the even number (4.5 -> 4, 3.5 -> 4); never use it for this."""
    overall = Fraction(overall)
    return int((2 * overall + 1) // 2)


def overall_of(stars):
    """One review's overall = the average of the categories it rated (REV-032). Returns a Fraction."""
    rated = [v for v in (stars or {}).values() if v is not None]
    if not rated:
        raise ValueError("a review must rate at least one category (SUG-20)")
    if any(not isinstance(v, int) or isinstance(v, bool) or v < 1 or v > 5 for v in rated):
        raise ValueError("stars are whole numbers from 1 to 5 (REV-008)")
    return Fraction(sum(rated), len(rated))


def empty(certificates=0):
    return {"shown": False, "count": 0, "written": 0, "rated_hi": None, "certificates": certificates,
            "score": None, "gold": False, "bars": None, "categories": None}


def summarise(ratings, today, certificates=0, mode="review_overalls"):
    """Mirror of the server summary. `ratings` = [{"stars": {"org": 5, ...}, "status": "published",
    "text": "...", "account_created": "2026-01-31"}, ...], one per member (the current review)."""
    collected = [r for r in ratings if str(r.get("status") or "published") in COLLECTED and not r.get("duplicate")]
    # Written reviews remain visible and count as written; only rows with scores enter rating arithmetic.
    rows = []
    for r in collected:
        stars = r.get("stars")
        if stars is None:
            continue
        if not isinstance(stars, dict):
            raise ValueError("stars must be a category object")
        if any(v is not None for v in stars.values()):
            overall_of(stars)                         # validate supplied scores even below the public threshold
            try:
                if (today - dt.date.fromisoformat(str(r.get("account_created")))).days >= AGE_DAYS:
                    rows.append(r)
            except ValueError:
                pass                               # no known account date: does not count (RATE-1)
    n = len(rows)
    out = empty(certificates)
    out["count"] = n
    out["written"] = sum(1 for r in collected if r.get("status", "published") == "published" and str(r.get("text") or "").strip())
    if n < MIN_RATINGS:
        return out                                  # under the minimum nothing about the score is given (REV-011)
    overalls = [overall_of(r["stars"]) for r in rows]
    if mode == "every_star":                        # decision D1, the other reading of CORE-01
        vals = [v for r in rows for v in r["stars"].values() if v is not None]
        num, den = sum(vals), len(vals)
    else:
        total = sum(overalls, Fraction(0))
        num, den = total.numerator, total.denominator * n
    cats = []
    for key, label in CATEGORIES:
        vals = [r["stars"].get(key) for r in rows if r["stars"].get(key) is not None]
        ok = len(vals) >= MIN_RATINGS
        cats.append({"key": key, "label": label, "score": display1(sum(vals), len(vals)) if ok else None,
                     "gold": ok and sum(vals) >= GOLD_FROM * len(vals), "count": len(vals)})
    out.update(shown=True, score=display1(num, den), gold=num >= GOLD_FROM * den,
               rated_hi=sum(1 for o in overalls if o >= GOLD_FROM),
               bars=[{"stars": k, "count": sum(1 for o in overalls if bar_of(o) == k)} for k in (5, 4, 3, 2, 1)],
               categories=cats)
    return out


def normalise(raw, certificates, who="?"):
    """Checks a school's rating summary and fills what a page with no reviews leaves out. Stops on a summary
    that cannot be right, so a page is never built with bars that disagree with its count."""
    if not raw:
        return empty(certificates)
    r = dict(raw)
    count = r.get("count") or 0
    if not isinstance(count, int) or count < 0:
        raise ValueError(f"{who}: rating count must be a whole number")
    if "shown" not in r:
        if count == 0:
            return empty(certificates)
        raise ValueError(f"{who}: the rating must be the server summary (shown, score, gold, bars, written, rated_hi). "
                         "An average with a count is not enough: the bars and the counts must come from the same set.")
    out = empty(certificates)
    out["count"] = count
    minimum = r.get("minimum_reviews", MIN_RATINGS)
    if not isinstance(minimum, int) or isinstance(minimum, bool) or minimum < 1:
        raise ValueError(f"{who}: minimum reviews must be a positive whole number")
    if minimum != MIN_RATINGS:
        out["minimum_reviews"] = minimum
    written = r.get("written")
    if written is None:
        written = 0
    if not isinstance(written, int) or isinstance(written, bool) or written < 0:
        raise ValueError(f"{who}: written count must be a nonnegative whole number")
    out["written"] = written                     # words-only reviews can make this exceed the scored count
    if not r["shown"]:
        return out
    if count < minimum:
        raise ValueError(f"{who}: a rating cannot show under {minimum} eligible reviews (RATE-2)")
    bars = r.get("bars") or []
    if [b.get("stars") for b in bars] != [5, 4, 3, 2, 1] or sum(b.get("count", 0) for b in bars) != count:
        raise ValueError(f"{who}: the five bars must add up to the review count ({count})")
    score = str(r.get("score") or "")
    if len(score) != 3 or score[1] != "." or not (score[0] + score[2]).isdigit() or not (1.0 <= float(score) <= 5.0):
        raise ValueError(f"{who}: score must look like 4.3")
    hi = r.get("rated_hi")
    if not isinstance(hi, int) or hi < 0 or hi > count:
        raise ValueError(f"{who}: 'Rated 4.0+' must be between 0 and the review count")
    cats = r.get("categories") or []
    if cats and [c.get("key") for c in cats] != [k for k, _ in CATEGORIES]:
        raise ValueError(f"{who}: the seven categories must come in the fixed order (A-30)")
    out.update(shown=True, score=score, gold=bool(r.get("gold")), rated_hi=hi, bars=bars, categories=cats or None)
    return out
