import json
import logging


def read_locks(s):
    """Reads locks from lock file content given as string.
       Returns ``{'snapname': {'locks': ['lock', ...], ...},
       'parent_locks': ['lock', ...}``.
       If format is invalid, ``ValueError`` is raised."""

    s = s.strip()
    if not s:
        return {}

    try:
        content = json.loads(s)
        assert isinstance(content, dict)
        for snap_name, snap_entry in content.items():
            assert isinstance(snap_name, str)
            assert isinstance(snap_entry, dict)
            for lock_type, locks in dict(snap_entry).items():
                assert lock_type in ("locks", "parent_locks")
                assert isinstance(locks, list)
                for lock in locks:
                    assert isinstance(lock, str)
                # eliminate multiple occurances of locks
                snap_entry[lock_type] = list(set(locks))
    except (AssertionError, json.JSONDecodeError) as e:
        logging.error("Lock file couldn't be parsed: {}".format(e))
        raise ValueError("invalid lock file format")

    return content