import hashlib
import json


def check_hash(hash: str, content: dict) -> bool:
    """Check that the stored hash from the metadata file matches the pyproject.toml file."""
    # OG source: https://github.com/python-poetry/poetry/blob/fe59f689f255ea7f3290daf635aefb0060add056/poetry/packages/locker.py#L44 # noqa: E501
    # This code is as verbatim as possible, with a few changes to be non-object-oriented.

    _relevant_keys = ["dependencies", "dev-dependencies", "source", "extras"]

    def get_hash(content: dict) -> str:
        """Returns the sha256 hash of the sorted content of the pyproject file."""
        content = content["tool"]["poetry"]

        relevant_content = {}
        for key in _relevant_keys:
            relevant_content[key] = content.get(key)

        content_hash = hashlib.sha256(json.dumps(relevant_content, sort_keys=True).encode()).hexdigest()

        return content_hash

    return hash == get_hash(content)