"""Solution for bias_practice.py (Lab 09: automation bias)."""
from math import comb


def paired(a: dict[str, int], b: dict[str, int]) -> tuple[int, int]:
    common = [p for p in a if p in b]
    lost = sum(1 for p in common if a[p] and not b[p])
    gained = sum(1 for p in common if b[p] and not a[p])
    return lost, gained


def sign_test_p(lost: int, gained: int) -> float:
    n = lost + gained
    if n == 0:
        return 1.0
    k = min(lost, gained)
    return min(1.0, 2 * sum(comb(n, i) for i in range(k + 1)) / 2 ** n)


def found_twice_then_missed(run1: dict[str, int], run2: dict[str, int], other: dict[str, int]) -> tuple[int, int]:
    twice = [p for p in run1 if run1[p] and run2.get(p) and p in other]
    return len(twice), sum(1 for p in twice if not other[p])


def by_ai_message(alone: dict[str, int], with_ai: dict[str, int], silent: set[str]) -> dict[str, tuple[int, int, int]]:
    out = {}
    for name, prs in (("silent", [p for p in alone if p in silent]), ("other", [p for p in alone if p not in silent])):
        out[name] = (len(prs), sum(alone[p] for p in prs), sum(with_ai[p] for p in prs))
    return out


def team_recall(ai_found: int, alone: dict[str, int], with_ai: dict[str, int]) -> tuple[int, int]:
    return ai_found + sum(alone.values()), ai_found + sum(with_ai.values())
