"""
Solution: the scoring behind Lab 07, where an AI reviewer read 81 wrong plans (each one states a
planted bug as a design decision) and 77 right ones, and the same 81 bugs in the finished PRs' diffs.
"""


def score_plan(kind: str, comments: list[dict]) -> bool:
    """Score one plan review.

    kind: "wrong" (the plan states a planted bug) or "right" (the agent's own plan, no planted bug).
    comments: the reviewer's comments, each {"severity": "bug" or "nit", "same": bool}, where
    "same" is the judge model's verdict: does this comment object to the planted decision?

    A wrong plan is caught when at least one comment, of any severity, is judged the same.
    A right plan is sent back when at least one comment has severity "bug" (the judge isn't asked:
    there's no planted bug to match). Return True for caught / sent back, False otherwise."""
    if kind == "wrong":
        return any(c["same"] for c in comments)
    if kind == "right":
        return any(c["severity"] == "bug" for c in comments)
    raise ValueError(f"unknown kind: {kind}")


def paired_split(ids: set[str], in_plan: set[str], in_diff: set[str]) -> dict[str, int]:
    """Pair the two stages on the same bugs.

    ids: every bug compared. in_plan / in_diff: the ones caught at each stage.
    Return {"both": .., "only_plan": .., "only_diff": .., "neither": ..}; the four add up to len(ids)."""
    p, d = in_plan & ids, in_diff & ids
    return {
        "both": len(p & d),
        "only_plan": len(p - d),
        "only_diff": len(d - p),
        "neither": len(ids - p - d),
    }


def points(ids: set[str], in_plan: set[str], in_diff: set[str]) -> int:
    """Plan minus diff, in percentage points: (caught in plan − caught in diff) / len(ids) × 100,
    rounded to a whole number (round half away from zero is fine; the lab's numbers never land on .5)."""
    x = 100 * (len(in_plan & ids) - len(in_diff & ids)) / len(ids)
    return int(x + 0.5) if x >= 0 else -int(-x + 0.5)


def flag_changes(before: set[str], after: set[str]) -> dict[str, int]:
    """How a change to the reviewer's input moved its false alarms on clean PRs.

    before / after: the clean PRs flagged as buggy without and with the approved plan.
    Return {"before": .., "after": .., "new": .. (flagged only after), "no_longer": .. (only before)}."""
    return {"before": len(before), "after": len(after), "new": len(after - before), "no_longer": len(before - after)}
