"""Solution for the Lab 10 practice: shards, a keyed store, completeness and refusals."""
import hashlib


def shard_of(clip_id: str, n_shards: int) -> int:
    return int(hashlib.sha256(clip_id.encode()).hexdigest()[:8], 16) % n_shards


def corpus_wer(rows: list[dict]) -> float:
    words = sum(r["words"] for r in rows)
    return 100 * sum(r["errors"] for r in rows) / words if words else 0.0


def merge_keyed(rows: list[dict]) -> dict[str, dict]:
    store = {}
    for r in rows:
        store[r["clip_id"]] = r  # a repeat overwrites its slot instead of adding a row
    return store


def completeness(stored_ids, manifest_ids: list[str]) -> tuple[str, list[str]]:
    stored = set(stored_ids)
    missing = [c for c in manifest_ids if c not in stored]
    return ("complete" if not missing else "incomplete"), missing


def comparable(a: dict, b: dict) -> list[str]:
    problems = []
    for r in (a, b):
        if r["status"] != "complete":
            problems.append(f"run {r['run_id']} is {r['status']}")
    if a["fingerprint"] != b["fingerprint"]:
        problems.append(f"different dataset versions ({a['dataset']} {a['fingerprint']} vs "
                        f"{b['dataset']} {b['fingerprint']})")
    if a["normalizer"] != b["normalizer"]:
        problems.append(f"different normalizers ({a['normalizer']} vs {b['normalizer']})")
    return problems
