"""Solution for tools_practice.py (Lab 05: let tools catch it first)."""
from collections import Counter


def _key(f: tuple) -> tuple:
    check, rule, file, _line, message = f
    return (check, rule, file, message)


def new_findings(pr: list[tuple], base: list[tuple]) -> list[tuple]:
    left = Counter(_key(f) for f in base)
    out = []
    for f in sorted(pr, key=lambda f: (f[2], f[3], f[1])):
        if left[_key(f)] > 0:
            left[_key(f)] -= 1
        else:
            out.append(f)
    return out


def flags_near(defect_lines: dict[str, list[int]], buggy_new: list[tuple], clean_new: list[tuple],
               window: int = 3) -> list[tuple]:
    out = []
    for f in new_findings(buggy_new, clean_new):
        file, line = f[2], f[3]
        if file not in defect_lines:
            continue
        lines = defect_lines[file]
        if not lines or any(abs(line - n) <= window for n in lines):
            out.append(f)
    return out


def gate_price(gates: set[str], clean_blocks: dict[str, list[str]],
               exposed_by: dict[str, list[str]], n_clean: int = 77) -> dict:
    exposed = sum(any(c in gates for c in checks) for checks in exposed_by.values())
    blocked = sum(any(c in gates for c in checks) for checks in clean_blocks.values())
    return {"exposed": exposed, "blocked": blocked, "blocked_pct": round(100 * blocked / n_clean)}


def diff_ratio(a: list[list[tuple]], b: list[list[tuple]], tolerance: int = 16) -> float:
    if len(a) != len(b) or any(len(ra) != len(rb) for ra, rb in zip(a, b)):
        return 1.0
    total = sum(len(r) for r in a)
    changed = sum(
        1
        for ra, rb in zip(a, b)
        for pa, pb in zip(ra, rb)
        if max(abs(x - y) for x, y in zip(pa, pb)) > tolerance
    )
    return changed / total if total else 0.0
