"""Solution for routing_practice.py (Lab 08: not every PR needs a human)."""


def auc(scores: list[float], buggy: list[bool]) -> float:
    pos = [s for s, b in zip(scores, buggy) if b]
    neg = [s for s, b in zip(scores, buggy) if not b]
    if not pos or not neg:
        raise ValueError("need both buggy and clean PRs")
    wins = sum((p > n) + 0.5 * (p == n) for p in pos for n in neg)
    return wins / (len(pos) * len(neg))


def twin_auc(values: dict[str, float]) -> float:
    by_change: dict[str, list[str]] = {}
    for pr in values:
        by_change.setdefault(pr.rsplit("-", 1)[0], []).append(pr)
    wins = pairs = 0.0
    for prs in by_change.values():
        clean = [p for p in prs if p.endswith("-clean")]
        for b in (p for p in prs if not p.endswith("-clean")):
            for c in clean:
                wins += (values[b] > values[c]) + 0.5 * (values[b] == values[c])
                pairs += 1
    return wins / pairs


def risk_points(s: dict, shape_only: bool = False) -> int:
    points = (min(s["code_lines"] // 25, 6) + s["packages"] - 1 + 2 * s["sensitive"]
              + min(s["blast_radius"] // 3, 3) - (1 if s["test_share"] >= 0.5 else 0))
    if not shape_only:
        points += (2 if s["unprotected"] >= 0.25 else 0) + (2 if s["gate_flags"] else 0) + min(2 * s["ai_flags"], 4)
    return points


def tiers(scores: dict[str, float], rule: set[str], auto_share: float, full_share: float = 0.25) -> dict[str, int]:
    out = {p: 3 for p in scores if p in rule}
    ranked = sorted((p for p in scores if p not in rule), key=lambda p: (scores[p], p))
    n_auto = round(auto_share * len(ranked))
    n_full = round(full_share * len(ranked))
    for i, p in enumerate(ranked):
        out[p] = 0 if i < n_auto else 2 if i >= len(ranked) - n_full else 1
    return out


def per_100_prs(escaped_share: float, prevalence: float) -> float:
    return round(100 * prevalence * escaped_share, 1)
