"""Solution for reviewable_practice.py (Lab 06: make the PR reviewable)."""
import math
import statistics


def noise_floor(runs: list[dict[str, int]]) -> dict:
    counts = [sum(r.values()) for r in runs]
    prs = list(runs[0])
    flips = sum(len({r[p] for r in runs}) > 1 for p in prs)
    spread = round((max(counts) - min(counts)) / len(prs) * 100)
    return {"counts": counts, "flips": flips, "spread": spread}


def _rates(runs: list[dict[str, int]]) -> dict[str, float]:
    every = set().union(*runs)
    return {p: statistics.mean(r[p] for r in runs if p in r) for p in every}


def paired_change(base_runs: list[dict[str, int]], new_runs: list[dict[str, int]]) -> tuple[int, int, int]:
    base, new = _rates(base_runs), _rates(new_runs)
    both = [p for p in base if p in new]
    b = statistics.mean(base[p] for p in both)
    n = statistics.mean(new[p] for p in both)
    return round(b * 100), round(n * 100), round((n - b) * 100)


def plan_problems(parts: list[dict], files: list[str]) -> list[str]:
    problems = []
    seen: dict[str, int] = {}
    for i, p in enumerate(parts, 1):
        if not p["files"]:
            problems.append(f"part {i} has no files")
        for f in p["files"]:
            if f not in files:
                problems.append(f"part {i} lists {f}, which the PR doesn't change")
            elif f in seen:
                problems.append(f"{f} is in part {seen[f]} and part {i}")
            else:
                seen[f] = i
    missing = [f for f in files if f not in seen]
    if missing:
        problems.append("not in any part: " + ", ".join(missing))
    if not 1 <= len(parts) <= 5:
        problems.append(f"{len(parts)} parts (use 1 to 5)")
    return problems


def defect_parts(defect_files: list[str], parts: list[dict]) -> list[int]:
    return sorted({i for i, p in enumerate(parts, 1) for f in defect_files if f in p["files"]})


def defects_per_arm(p1: float, p2: float, z_alpha: float = 1.96, z_power: float = 0.84) -> int:
    if p1 == p2:
        raise ValueError("p1 and p2 must differ")
    n = (z_alpha + z_power) ** 2 * (p1 * (1 - p1) + p2 * (1 - p2)) / (p1 - p2) ** 2
    return math.ceil(n)


def break_even_seconds(cents_per_pr: float, dollars_per_hour: float) -> float:
    cents_per_second = dollars_per_hour * 100 / 3600
    return cents_per_pr / cents_per_second
